Documentation
¶
Overview ¶
Package metrics 提供統一的指標查詢介面,支援多種資料來源
Index ¶
- Variables
- type AggregatedValue
- type AggregationFunc
- type AggregationOptions
- type AggregationResult
- type CachedResult
- type CircuitBreakerConfig
- type CircuitBreakerState
- type DataPoint
- type DownsampledQuery
- type HistoricalQuery
- type HistoricalResult
- type LongTermMetricsProvider
- type MemoryProvider
- func (p *MemoryProvider) BatchQuery(ctx context.Context, queries []MetricQuery) ([]*QueryResult, error)
- func (p *MemoryProvider) Close() error
- func (p *MemoryProvider) GetAggregation(ctx context.Context, opts AggregationOptions) (*AggregationResult, error)
- func (p *MemoryProvider) HealthCheck(ctx context.Context) error
- func (p *MemoryProvider) Query(ctx context.Context, query MetricQuery) (*QueryResult, error)
- type MetricQuery
- type MetricsProvider
- type PrometheusConfig
- type PrometheusProvider
- func (p *PrometheusProvider) BatchQuery(ctx context.Context, queries []MetricQuery) ([]*QueryResult, error)
- func (p *PrometheusProvider) Close() error
- func (p *PrometheusProvider) GetAggregation(ctx context.Context, opts AggregationOptions) (*AggregationResult, error)
- func (p *PrometheusProvider) HealthCheck(ctx context.Context) error
- func (p *PrometheusProvider) Query(ctx context.Context, query MetricQuery) (*QueryResult, error)
- type ProviderConfig
- type QueryResult
- type QueryRouterConfig
- type QueryStats
- type ResultLimits
- type RetentionInfo
- type SimpleFactory
- type TimeRange
- type TimeSeries
Constants ¶
This section is empty.
Variables ¶
var ( // ErrProviderNotAvailable indicates the metrics provider is not accessible ErrProviderNotAvailable = fmt.Errorf("metrics provider not available") // ErrQueryTimeout indicates a query exceeded the timeout ErrQueryTimeout = fmt.Errorf("query timeout") // ErrInvalidQuery indicates an invalid query format ErrInvalidQuery = fmt.Errorf("invalid query") // ErrNoData indicates no data was found for the query ErrNoData = fmt.Errorf("no data found") // ErrTooManyDataPoints indicates the query would return too many data points ErrTooManyDataPoints = fmt.Errorf("too many data points") )
Error types for metrics operations
Functions ¶
This section is empty.
Types ¶
type AggregatedValue ¶
type AggregatedValue struct {
// Metric name
Metric string `json:"metric"`
// Group labels (if grouped)
Labels map[string]string `json:"labels,omitempty"`
// Aggregated value
Value float64 `json:"value"`
// Number of samples aggregated
SampleCount int64 `json:"sample_count"`
}
AggregatedValue represents an aggregated metric value
type AggregationFunc ¶
type AggregationFunc string
AggregationFunc represents an aggregation function
const ( AggregationAvg AggregationFunc = "avg" AggregationMax AggregationFunc = "max" AggregationMin AggregationFunc = "min" AggregationSum AggregationFunc = "sum" AggregationCount AggregationFunc = "count" AggregationP50 AggregationFunc = "p50" AggregationP95 AggregationFunc = "p95" AggregationP99 AggregationFunc = "p99" )
type AggregationOptions ¶
type AggregationOptions struct {
// 要聚合的指標
Metrics []string `json:"metrics"`
// 聚合的時間範圍
TimeRange TimeRange `json:"time_range"`
// 聚合函數
Function AggregationFunc `json:"function"`
// 按標籤分組
GroupBy []string `json:"group_by,omitempty"`
// 額外的篩選條件
Filters map[string]string `json:"filters,omitempty"`
}
AggregationOptions 定義聚合查詢的選項
type AggregationResult ¶
type AggregationResult struct {
// Aggregation options used
Options *AggregationOptions `json:"options"`
// Aggregated values
Values []AggregatedValue `json:"values"`
// Warnings from the aggregation
Warnings []string `json:"warnings,omitempty"`
}
AggregationResult represents the result of an aggregation query
type CachedResult ¶
type CachedResult struct {
Result *QueryResult
Timestamp time.Time
}
CachedResult 快取的查詢結果
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
FailureThreshold int64 `yaml:"failure_threshold" json:"failure_threshold"`
RecoveryTimeout time.Duration `yaml:"recovery_timeout" json:"recovery_timeout"`
}
CircuitBreakerConfig 電路斷路器配置
type CircuitBreakerState ¶
type CircuitBreakerState int
CircuitBreakerState 表示電路斷路器的狀態
const ( // StateClosed 關閉狀態,請求正常通過 StateClosed CircuitBreakerState = iota // StateOpen 開啟狀態,請求被阻斷 StateOpen // StateHalfOpen 半開狀態,嘗試性地允許部分請求通過 StateHalfOpen )
func (CircuitBreakerState) String ¶
func (s CircuitBreakerState) String() string
type DownsampledQuery ¶
type DownsampledQuery struct {
MetricQuery
// Downsampling method (avg, max, min)
Method string `json:"method"`
// Target resolution
Resolution time.Duration `json:"resolution"`
}
DownsampledQuery represents a query for downsampled data
type HistoricalQuery ¶
type HistoricalQuery struct {
MetricQuery
// Downsampling resolution for long-term data
Resolution time.Duration `json:"resolution"`
// Whether to include raw samples
IncludeRaw bool `json:"include_raw"`
}
HistoricalQuery represents a query for historical data (future Mimir support)
type HistoricalResult ¶
type HistoricalResult struct {
QueryResult
// Data retention information
RetentionInfo *RetentionInfo `json:"retention_info"`
}
HistoricalResult represents the result of a historical query
type LongTermMetricsProvider ¶
type LongTermMetricsProvider interface {
MetricsProvider
// QueryHistorical 查詢超出正常保留期的歷史數據
QueryHistorical(ctx context.Context, query HistoricalQuery) (*HistoricalResult, error)
// QueryDownsampled 查詢降採樣數據,在長時間範圍內獲得更好的性能
QueryDownsampled(ctx context.Context, query DownsampledQuery) (*QueryResult, error)
// QueryTenant 查詢特定租戶的指標(多租戶支援)
QueryTenant(ctx context.Context, tenantID string, query MetricQuery) (*QueryResult, error)
}
LongTermMetricsProvider 擴展 MetricsProvider,支援長期儲存功能 此介面預留給未來的 Mimir 實作
type MemoryProvider ¶
type MemoryProvider struct {
// contains filtered or unexported fields
}
MemoryProvider 簡化的記憶體 provider
func (*MemoryProvider) BatchQuery ¶
func (p *MemoryProvider) BatchQuery(ctx context.Context, queries []MetricQuery) ([]*QueryResult, error)
BatchQuery 實作 MetricsProvider.BatchQuery
func (*MemoryProvider) Close ¶
func (p *MemoryProvider) Close() error
Close 實作 MetricsProvider.Close
func (*MemoryProvider) GetAggregation ¶
func (p *MemoryProvider) GetAggregation(ctx context.Context, opts AggregationOptions) (*AggregationResult, error)
GetAggregation 實作 MetricsProvider.GetAggregation
func (*MemoryProvider) HealthCheck ¶
func (p *MemoryProvider) HealthCheck(ctx context.Context) error
HealthCheck 實作 MetricsProvider.HealthCheck
func (*MemoryProvider) Query ¶
func (p *MemoryProvider) Query(ctx context.Context, query MetricQuery) (*QueryResult, error)
Query 實作 MetricsProvider.Query
type MetricQuery ¶
type MetricQuery struct {
// 指標名稱(例如:"cpu_usage", "http_request_duration_seconds")
Metric string `json:"metric"`
// 用於過濾的標籤(例如:{"service": "api", "env": "prod"})
Labels map[string]string `json:"labels"`
// 查詢的時間範圍
TimeRange TimeRange `json:"time_range"`
// 範圍查詢的步長(例如:1m, 5m, 1h)
Step time.Duration `json:"step"`
// 聚合函數(avg, max, min, sum, count, p50, p95, p99)
Aggregation string `json:"aggregation,omitempty"`
// 額外的提供者特定選項
Options map[string]interface{} `json:"options,omitempty"`
}
MetricQuery 表示指標查詢
type MetricsProvider ¶
type MetricsProvider interface {
// Query 執行單一指標查詢並返回結果
Query(ctx context.Context, query MetricQuery) (*QueryResult, error)
// BatchQuery 並行執行多個查詢以提高效率
BatchQuery(ctx context.Context, queries []MetricQuery) ([]*QueryResult, error)
// GetAggregation 對指標執行聚合查詢
GetAggregation(ctx context.Context, opts AggregationOptions) (*AggregationResult, error)
// HealthCheck 驗證指標提供者是否可訪問且功能正常
HealthCheck(ctx context.Context) error
// Close 釋放提供者持有的任何資源
Close() error
}
MetricsProvider 定義從各種來源查詢指標的統一介面
type PrometheusConfig ¶
type PrometheusConfig struct {
// Prometheus 服務器地址
Address string `yaml:"address" json:"address"`
// 基本認證
Username string `yaml:"username" json:"username"`
Password string `yaml:"password" json:"password"`
// Bearer Token 認證
BearerToken string `yaml:"bearer_token" json:"bearer_token"`
// TLS 配置
TLS struct {
Enabled bool `yaml:"enabled" json:"enabled"`
InsecureSkipVerify bool `yaml:"insecure_skip_verify" json:"insecure_skip_verify"`
CertFile string `yaml:"cert_file" json:"cert_file"`
KeyFile string `yaml:"key_file" json:"key_file"`
CAFile string `yaml:"ca_file" json:"ca_file"`
} `yaml:"tls" json:"tls"`
// 查詢配置
Query struct {
Timeout time.Duration `yaml:"timeout" json:"timeout"`
MaxSamples int `yaml:"max_samples" json:"max_samples"`
} `yaml:"query" json:"query"`
// 快取配置
Cache struct {
Enabled bool `yaml:"enabled" json:"enabled"`
TTL time.Duration `yaml:"ttl" json:"ttl"`
MaxSize int `yaml:"max_size" json:"max_size"`
} `yaml:"cache" json:"cache"`
// 並發控制
Concurrency struct {
MaxConcurrent int `yaml:"max_concurrent" json:"max_concurrent"`
} `yaml:"concurrency" json:"concurrency"`
// 電路斷路器配置
CircuitBreaker CircuitBreakerConfig `yaml:"circuit_breaker" json:"circuit_breaker"`
}
PrometheusConfig Prometheus Provider 配置
type PrometheusProvider ¶
type PrometheusProvider struct {
// contains filtered or unexported fields
}
PrometheusProvider Prometheus 指標提供者
func NewPrometheusProvider ¶
func NewPrometheusProvider(config *PrometheusConfig, logger *zap.Logger) (*PrometheusProvider, error)
NewPrometheusProvider 創建 Prometheus Provider
func (*PrometheusProvider) BatchQuery ¶
func (p *PrometheusProvider) BatchQuery(ctx context.Context, queries []MetricQuery) ([]*QueryResult, error)
BatchQuery 並行執行多個查詢,並對相似的查詢進行合併優化
func (*PrometheusProvider) GetAggregation ¶
func (p *PrometheusProvider) GetAggregation(ctx context.Context, opts AggregationOptions) (*AggregationResult, error)
GetAggregation 執行聚合查詢
func (*PrometheusProvider) HealthCheck ¶
func (p *PrometheusProvider) HealthCheck(ctx context.Context) error
HealthCheck 驗證 Prometheus 連接
func (*PrometheusProvider) Query ¶
func (p *PrometheusProvider) Query(ctx context.Context, query MetricQuery) (*QueryResult, error)
Query 執行單一指標查詢,包含電路斷路器和指標記錄邏輯
type ProviderConfig ¶
type ProviderConfig struct {
// Provider type: "prometheus", "mimir", "memory"
Type string `json:"type"`
// Provider-specific configuration
Config interface{} `json:"config"`
// Query routing configuration
QueryRouter *QueryRouterConfig `json:"query_router,omitempty"`
// Result limits configuration
Limits *ResultLimits `json:"limits,omitempty"`
}
ProviderConfig contains configuration for metrics providers
type QueryResult ¶
type QueryResult struct {
// Query that produced this result
Query *MetricQuery `json:"query"`
// Series contains the time series data
Series []TimeSeries `json:"series"`
// Warnings from the query execution
Warnings []string `json:"warnings,omitempty"`
// Stats contains query statistics
Stats *QueryStats `json:"stats,omitempty"`
// Truncated indicates if results were truncated due to size limits
Truncated bool `json:"truncated,omitempty"`
// MaxSeriesExceeded indicates if max series limit was exceeded
MaxSeriesExceeded bool `json:"max_series_exceeded,omitempty"`
// MaxDataPointsExceeded indicates if max data points limit was exceeded
MaxDataPointsExceeded bool `json:"max_data_points_exceeded,omitempty"`
}
QueryResult represents the result of a metric query
type QueryRouterConfig ¶
type QueryRouterConfig struct {
// Short-term query threshold in days
ShortTermDays int `json:"short_term_days"`
// Provider for short-term queries
ShortTermProvider string `json:"short_term_provider"`
// Provider for long-term queries
LongTermProvider string `json:"long_term_provider"`
}
QueryRouterConfig defines routing rules for queries
type QueryStats ¶
type QueryStats struct {
Duration time.Duration `json:"duration"`
SamplesScanned int64 `json:"samples_scanned"`
SeriesScanned int64 `json:"series_scanned"`
}
QueryStats contains statistics about query execution
type ResultLimits ¶
type ResultLimits struct {
// Maximum number of time series per query
MaxSeries int `json:"max_series"`
// Maximum number of data points per series
MaxDataPointsPerSeries int `json:"max_data_points_per_series"`
// Maximum total data points per query
MaxTotalDataPoints int `json:"max_total_data_points"`
// Maximum query result size in bytes
MaxResultSizeBytes int64 `json:"max_result_size_bytes"`
}
ResultLimits defines limits for query results
type RetentionInfo ¶
type RetentionInfo struct {
// Oldest available data point
OldestDataPoint time.Time `json:"oldest_data_point"`
// Retention policy applied
RetentionPolicy string `json:"retention_policy"`
// Data completeness percentage
Completeness float64 `json:"completeness"`
}
RetentionInfo contains information about data retention
type SimpleFactory ¶
type SimpleFactory struct {
// contains filtered or unexported fields
}
SimpleFactory 提供簡化的 metrics provider 工廠
func NewSimpleFactory ¶
func NewSimpleFactory(logger *zap.Logger) *SimpleFactory
NewSimpleFactory 創建簡化的工廠
func (*SimpleFactory) CreateMemoryProvider ¶
func (f *SimpleFactory) CreateMemoryProvider() MetricsProvider
CreateMemoryProvider 創建記憶體測試 provider
type TimeSeries ¶
type TimeSeries struct {
// Labels identifying this series
Labels map[string]string `json:"labels"`
// Values contains the data points
Values []DataPoint `json:"values"`
}
TimeSeries represents a single time series