metric

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: AGPL-3.0 Imports: 25 Imported by: 1 module, 2 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 metric provides metric queries and subscription streams.

Resource inputs use the canonical resource/v2 Value without Struct conversion. ResourceData, Reference, or Route selects resource intent; opaque ResourceKey selectors and Params alone do not. Query automatically selects QueryResource for resource intent and never retries the legacy operation.

StreamMetrics accepts only nonresource frames. StreamResourceMetrics is an explicit mixed resource/nonresource lane: its wire-v2 opening handshake must succeed before a client publishes the stream. Every subsequent subscription and control frame uses wire version two. Resource references and access routes remain optional actual inputs, never synthesized from ordinary selectors.

QueryContext.Context and StreamContext.Context carry callback cancellation. Polling retains the complete resource input and Params for every query. StreamOutput.OperationError carries typed admission and transport failures; Error remains the native provider diagnostic field.

Index

Constants

View Source
const ResourceWireVersion uint32 = 2

ResourceWireVersion identifies the lossless resource-aware metric protocol.

Variables

This section is empty.

Functions

func RegisterMetricPluginServer added in v0.9.0

func RegisterMetricPluginServer(registrar grpc.ServiceRegistrar, server metricpb.MetricPluginServer)

RegisterMetricPluginServer admits resource frames before generated protobuf decode.

func RegisterPlugin

func RegisterPlugin(
	p *sdk.Plugin,
	opts PluginOpts,
) error

RegisterPlugin registers the metric capability with the plugin system.

func ValidateStreamInput added in v0.9.0

func ValidateStreamInput(input StreamInput) error

ValidateStreamInput checks a frame before a host enqueues it on a shared stream.

Types

type AggregateValue

type AggregateValue struct {
	MetricID string            `json:"metric_id"`
	Min      float64           `json:"min"`
	Max      float64           `json:"max"`
	Avg      float64           `json:"avg"`
	Sum      float64           `json:"sum"`
	P50      float64           `json:"p50"`
	P90      float64           `json:"p90"`
	P99      float64           `json:"p99"`
	Count    int64             `json:"count"`
	Window   time.Duration     `json:"window"`
	Labels   map[string]string `json:"labels"`
}

AggregateValue represents aggregated metric data over a window.

func AggregateValueFromProto

func AggregateValueFromProto(p *metricpb.AggregateValue) AggregateValue

AggregateValueFromProto shares labels and uses zero duration for a missing window.

func (*AggregateValue) ToProto

func (a *AggregateValue) ToProto() *metricpb.AggregateValue

ToProto encodes the statistical window and shares the labels map.

type ColorRange

type ColorRange struct {
	Min   float64 `json:"min"`
	Max   float64 `json:"max"`
	Color string  `json:"color"`
}

ColorRange defines a color to use for a range of metric values.

func ColorRangeFromProto

func ColorRangeFromProto(p *metricpb.MetricColorRange) ColorRange

ColorRangeFromProto returns a zero range for nil input.

func (*ColorRange) ToProto

func (c *ColorRange) ToProto() *metricpb.MetricColorRange

ToProto copies the range into a new wire message.

type CurrentValue

type CurrentValue struct {
	MetricID  string            `json:"metric_id"`
	Value     float64           `json:"value"`
	Timestamp time.Time         `json:"timestamp"`
	Labels    map[string]string `json:"labels"`
}

CurrentValue represents the current value of a metric.

func CurrentValueFromProto

func CurrentValueFromProto(p *metricpb.CurrentValue) CurrentValue

CurrentValueFromProto shares labels and uses zero time for a missing timestamp.

func (*CurrentValue) ToProto

func (c *CurrentValue) ToProto() *metricpb.CurrentValue

ToProto encodes the value and timestamp; the labels map remains shared.

type DataPoint

type DataPoint struct {
	Timestamp time.Time         `json:"timestamp"`
	Value     float64           `json:"value"`
	Labels    map[string]string `json:"labels"`
}

DataPoint represents a single data point in a time series.

func DataPointFromProto

func DataPointFromProto(p *metricpb.DataPoint) DataPoint

DataPointFromProto decodes a sample and shares labels with the input. A missing timestamp yields the zero time.

func (*DataPoint) ToProto

func (d *DataPoint) ToProto() *metricpb.DataPoint

ToProto encodes the timestamp and value; the labels map remains shared.

type Handler

type Handler struct {
	Resource string             `json:"resource"`
	Metrics  []MetricDescriptor `json:"metrics"`
}

Handler maps a resource key to its available metrics.

func HandlerFromProto

func HandlerFromProto(p *metricpb.MetricHandler) Handler

HandlerFromProto decodes the available metrics; nil input yields an empty handler.

func (*Handler) ToProto

func (h *Handler) ToProto() *metricpb.MetricHandler

ToProto copies the handler and its metric descriptors into wire messages.

type Manager

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

Manager manages metric queries and streams within a plugin process.

func NewManager

func NewManager(
	log logging.Logger,
	sp settings.Provider,
	providerInfo ProviderInfo,
	handlers map[string]Handler,
	queryFunc QueryFunc,
	streamFunc StreamFunc,
) *Manager

NewManager creates a process-local manager. A nil logger disables logging. Bind the connection provider before starting concurrent queries or streams.

func (*Manager) BindConnectionContextProvider added in v0.9.0

func (m *Manager) BindConnectionContextProvider(provider resourcev2.ConnectionContextProvider)

BindConnectionContextProvider installs the sole configured native registry during capability setup, before any stream or query starts.

func (*Manager) GetSupportedResources

func (m *Manager) GetSupportedResources(_ *types.PluginContext) (*ProviderInfo, []Handler)

GetSupportedResources returns provider metadata and an unordered handler snapshot.

func (*Manager) Query

func (m *Manager) Query(ctx *types.PluginContext, req QueryRequest) (*QueryResponse, error)

Query runs a non-resource query; resource intent requires QueryResource.

func (*Manager) QueryResource added in v0.9.0

func (m *Manager) QueryResource(ctx *types.PluginContext, req QueryRequest) (*QueryResponse, error)

QueryResource validates resource input before leasing its configured connection.

func (*Manager) StreamMetrics

func (m *Manager) StreamMetrics(ctx context.Context, in chan StreamInput) (chan StreamOutput, error)

StreamMetrics starts an owner-isolated non-resource lane until cancellation or input closure.

func (*Manager) StreamResourceMetrics added in v0.9.0

func (m *Manager) StreamResourceMetrics(ctx context.Context, in chan StreamInput) (chan StreamOutput, error)

StreamResourceMetrics leases the selected connection for the lane's lifetime. Cancellation stops native work and prevents further delivery.

type MetricDescriptor

type MetricDescriptor struct {
	ID              string        `json:"id"`
	Name            string        `json:"name"`
	Unit            MetricUnit    `json:"unit"`
	Icon            string        `json:"icon"`
	ColorRanges     []ColorRange  `json:"color_ranges"`
	FormatString    string        `json:"format_string"`
	SupportedShapes []MetricShape `json:"supported_shapes"`
	ChartGroup      string        `json:"chart_group"`
}

MetricDescriptor describes a single metric.

func MetricDescriptorFromProto

func MetricDescriptorFromProto(p *metricpb.MetricDescriptor) MetricDescriptor

MetricDescriptorFromProto decodes descriptor slices; nil input yields zero metadata.

func (*MetricDescriptor) ToProto

ToProto copies descriptor slices into a new wire message.

type MetricResult

type MetricResult struct {
	TimeSeries     *TimeSeries     `json:"time_series,omitempty"`
	CurrentValue   *CurrentValue   `json:"current_value,omitempty"`
	AggregateValue *AggregateValue `json:"aggregate_value,omitempty"`
}

MetricResult wraps one of the possible metric result types.

func MetricResultFromProto

func MetricResultFromProto(p *metricpb.MetricResult) MetricResult

MetricResultFromProto decodes the selected wire variant; absent variants yield zero.

func (*MetricResult) ToProto

func (r *MetricResult) ToProto() *metricpb.MetricResult

ToProto encodes the first present result in series, current, aggregate order.

type MetricShape

type MetricShape int

MetricShape indicates the type of metric data.

const (
	// ShapeCurrent requests the latest value.
	ShapeCurrent MetricShape = 0
	// ShapeTimeseries requests timestamped samples.
	ShapeTimeseries MetricShape = 1
	// ShapeAggregate requests a statistical window.
	ShapeAggregate MetricShape = 2
)

func MetricShapeFromProto

func MetricShapeFromProto(p metricpb.MetricShape) MetricShape

MetricShapeFromProto preserves every int32 wire shape, including unknown values.

func (MetricShape) ToProto

func (s MetricShape) ToProto() metricpb.MetricShape

ToProto converts the shape to the int32 wire enum. Out-of-range ints truncate.

type MetricStreamCommand

type MetricStreamCommand int

MetricStreamCommand represents a command for the metric stream.

const (
	// StreamCommandSubscribe starts a subscription within its owning lane.
	StreamCommandSubscribe MetricStreamCommand = 0
	// StreamCommandUnsubscribe retires a subscription within its owning lane.
	StreamCommandUnsubscribe MetricStreamCommand = 1
	// StreamCommandClose retires the addressed subscription, not other lanes.
	StreamCommandClose MetricStreamCommand = 2
)

func MetricStreamCommandFromProto

func MetricStreamCommandFromProto(p metricpb.MetricStreamCommand) MetricStreamCommand

MetricStreamCommandFromProto preserves unknown wire commands for validation.

func (MetricStreamCommand) ToProto

ToProto converts the command to the int32 wire enum. Out-of-range ints truncate.

type MetricUnit

type MetricUnit int

MetricUnit represents the unit of a metric value.

const (
	// UnitNone denotes a dimensionless value.
	UnitNone MetricUnit = 0
	// UnitBytes measures bytes.
	UnitBytes MetricUnit = 1
	// UnitKB measures kilobytes.
	UnitKB MetricUnit = 2
	// UnitMB measures megabytes.
	UnitMB MetricUnit = 3
	// UnitGB measures gigabytes.
	UnitGB MetricUnit = 4
	// UnitPercentage measures percentages.
	UnitPercentage MetricUnit = 5
	// UnitMillis measures milliseconds.
	UnitMillis MetricUnit = 6
	// UnitSeconds measures seconds.
	UnitSeconds MetricUnit = 7
	// UnitCount measures discrete occurrences.
	UnitCount MetricUnit = 8
	// UnitOpsPerSec measures operations per second.
	UnitOpsPerSec MetricUnit = 9
	// UnitBytesPerSec measures byte throughput.
	UnitBytesPerSec MetricUnit = 10
	// UnitMillicores measures thousandths of a CPU core.
	UnitMillicores MetricUnit = 11
	// UnitCores measures CPU cores.
	UnitCores MetricUnit = 12
)

func MetricUnitFromProto

func MetricUnitFromProto(p metricpb.MetricUnit) MetricUnit

MetricUnitFromProto preserves every int32 wire unit, including unknown values.

func (MetricUnit) ToProto

func (u MetricUnit) ToProto() metricpb.MetricUnit

ToProto converts the unit to the int32 wire enum. Out-of-range ints truncate.

type Plugin

type Plugin struct {
	plugin.Plugin

	Impl Provider
}

Plugin implements the hashicorp go-plugin interfaces for metric capability.

func (*Plugin) BindConnectionContextProvider added in v0.9.0

func (p *Plugin) BindConnectionContextProvider(provider resourcev2.ConnectionContextProvider)

BindConnectionContextProvider forwards registry binding to implementations that accept it. Call during setup, before serving requests.

func (*Plugin) GRPCClient

func (p *Plugin) GRPCClient(
	_ context.Context,
	_ *plugin.GRPCBroker,
	c *grpc.ClientConn,
) (any, error)

GRPCClient creates a client backed by the supplied connection; the caller owns that connection.

func (*Plugin) GRPCServer

func (p *Plugin) GRPCServer(_ *plugin.GRPCBroker, s *grpc.Server) error

GRPCServer registers the metric service on the supplied server.

type PluginClient

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

PluginClient forwards metric queries and streams to a remote plugin.

func (*PluginClient) GetSupportedResources

func (c *PluginClient) GetSupportedResources(ctx *types.PluginContext) (*ProviderInfo, []Handler)

GetSupportedResources returns the remote provider and its resource handlers.

func (*PluginClient) Query

Query selects the legacy or resource-aware RPC from the request's intent.

func (*PluginClient) QueryResource added in v0.9.0

func (c *PluginClient) QueryResource(ctx *types.PluginContext, r QueryRequest) (*QueryResponse, error)

QueryResource validates resource intent and requires resource-aware response admission.

func (*PluginClient) StreamMetrics

func (c *PluginClient) StreamMetrics(ctx context.Context, in chan StreamInput) (chan StreamOutput, error)

StreamMetrics opens a legacy metric stream bound to ctx.

func (*PluginClient) StreamResourceMetrics added in v0.9.0

func (c *PluginClient) StreamResourceMetrics(ctx context.Context, in chan StreamInput) (chan StreamOutput, error)

StreamResourceMetrics waits for remote readiness before forwarding resource frames.

type PluginOpts

type PluginOpts struct {
	// ProviderInfo describes this metric provider.
	ProviderInfo ProviderInfo `json:"provider_info"`

	// Handlers maps resource keys to their metric handlers.
	// For example: "core::v1::Pod" -> Handler
	Handlers map[string]Handler `json:"handlers"`

	// QueryFunc is the function that queries metrics from the provider.
	QueryFunc QueryFunc `json:"-"`

	// StreamFunc is the optional function that streams metrics. If nil,
	// the SDK will poll QueryFunc at the requested interval.
	StreamFunc StreamFunc `json:"-"`
}

PluginOpts contains the options for the metric plugin.

type PluginServer

type PluginServer struct{ Impl Provider }

PluginServer adapts metric provider calls to the gRPC transport.

func (*PluginServer) GetSupportedResources

GetSupportedResources exposes the provider's resource handlers.

func (*PluginServer) Query

Query decodes a legacy query and preserves provider error classification.

func (*PluginServer) QueryResource added in v0.9.0

QueryResource admits resource-aware input before invoking the provider.

func (*PluginServer) StreamMetrics

StreamMetrics serves a legacy metric stream until completion or cancellation.

func (*PluginServer) StreamResourceMetrics added in v0.9.0

func (s *PluginServer) StreamResourceMetrics(stream metricpb.MetricPlugin_StreamResourceMetricsServer) error

StreamResourceMetrics validates the open frame and acknowledges provider readiness.

type Provider

type Provider interface {
	GetSupportedResources(ctx *types.PluginContext) (*ProviderInfo, []Handler)
	Query(ctx *types.PluginContext, req QueryRequest) (*QueryResponse, error)
	StreamMetrics(ctx context.Context, in chan StreamInput) (chan StreamOutput, error)
}

Provider is the interface satisfied by the plugin server and client to provide metric querying functionality.

type ProviderInfo

type ProviderInfo struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Icon        string `json:"icon"`
	Description string `json:"description"`
}

ProviderInfo describes a metric provider.

func ProviderInfoFromProto

func ProviderInfoFromProto(p *metricpb.MetricProviderInfo) ProviderInfo

ProviderInfoFromProto returns zero metadata for nil input.

func (*ProviderInfo) ToProto

ToProto encodes provider metadata into a new wire message.

type QueryContext

type QueryContext struct {
	context.Context `json:"-"`

	PluginID     string
	ConnectionID string
	Connection   *types.Connection
}

QueryContext provides context for metric queries. Wraps the plugin context plus connection information passed via gRPC metadata.

type QueryFunc

type QueryFunc func(ctx *QueryContext, req QueryRequest) (*QueryResponse, error)

QueryFunc queries metrics for a resource.

type QueryRequest

type QueryRequest struct {
	ResourceKey       string                        `json:"resource_key"`
	ResourceID        string                        `json:"resource_id"`
	ResourceNamespace string                        `json:"resource_namespace"`
	ResourceData      *resourcev2.Value             `json:"resource_data,omitempty"`
	Reference         *resourcev2.ResourceReference `json:"reference,omitempty"`
	Route             *resourcev2.AccessRoute       `json:"route,omitempty"`
	MetricIDs         []string                      `json:"metric_ids"`
	Shape             MetricShape                   `json:"shape"`
	StartTime         time.Time                     `json:"start_time"`
	EndTime           time.Time                     `json:"end_time"`
	Step              time.Duration                 `json:"step"`
	Params            map[string]string             `json:"params"`
}

QueryRequest is the Go-side representation of a metric query.

func (QueryRequest) HasResourceIntent added in v0.9.0

func (r QueryRequest) HasResourceIntent() bool

HasResourceIntent reports whether the request needs the resource-aware protocol.

func (*QueryRequest) UnmarshalJSON added in v0.9.0

func (r *QueryRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON admits exact field names and validates lossless resource input.

type QueryResponse

type QueryResponse struct {
	Success bool           `json:"success"`
	Results []MetricResult `json:"results"`
	Error   string         `json:"error"`
}

QueryResponse is the Go-side representation of a metric query response.

func QueryResponseFromProto

func QueryResponseFromProto(p *metricpb.QueryMetricsResponse) *QueryResponse

QueryResponseFromProto decodes results; nil input produces an unsuccessful empty response.

func (*QueryResponse) ToProto

ToProto copies result containers; nested label maps remain shared.

type ResourceQueryProvider added in v0.9.0

type ResourceQueryProvider interface {
	QueryResource(*types.PluginContext, QueryRequest) (*QueryResponse, error)
}

ResourceQueryProvider accepts lossless resource queries on the explicit v2 RPC.

type ResourceStreamProvider added in v0.9.0

type ResourceStreamProvider interface {
	StreamResourceMetrics(context.Context, chan StreamInput) (chan StreamOutput, error)
}

ResourceStreamProvider accepts mixed resource and nonresource v2 frames.

type StreamContext

type StreamContext struct {
	context.Context `json:"-"`

	PluginID     string
	ConnectionID string
	Connection   *types.Connection
}

StreamContext provides context for metric streams.

type StreamFunc

type StreamFunc func(ctx *StreamContext, in chan StreamInput) (chan StreamOutput, error)

StreamFunc streams metrics for subscriptions. If nil, the SDK polls QueryFunc.

type StreamInput

type StreamInput struct {
	SubscriptionID    string                        `json:"subscription_id"`
	Command           MetricStreamCommand           `json:"command"`
	ResourceKey       string                        `json:"resource_key"`
	ResourceID        string                        `json:"resource_id"`
	ResourceNamespace string                        `json:"resource_namespace"`
	ResourceData      *resourcev2.Value             `json:"resource_data,omitempty"`
	Reference         *resourcev2.ResourceReference `json:"reference,omitempty"`
	Route             *resourcev2.AccessRoute       `json:"route,omitempty"`
	MetricIDs         []string                      `json:"metric_ids"`
	Interval          time.Duration                 `json:"interval"`
	Params            map[string]string             `json:"params"`
	CatalogRevision   string                        `json:"catalog_revision,omitempty"`
}

StreamInput is a control message for the metric stream.

func (StreamInput) HasResourceIntent added in v0.9.0

func (r StreamInput) HasResourceIntent() bool

HasResourceIntent reports whether the stream frame carries resource-aware input.

func (*StreamInput) UnmarshalJSON added in v0.9.0

func (r *StreamInput) UnmarshalJSON(data []byte) error

UnmarshalJSON validates stream metadata, catalog pins, and resource values.

type StreamOutput

type StreamOutput struct {
	SubscriptionID string                             `json:"subscription_id"`
	Results        []MetricResult                     `json:"results"`
	Timestamp      time.Time                          `json:"timestamp"`
	Error          string                             `json:"error"`
	OperationError *resourcev2.ResourceOperationError `json:"operation_error,omitempty"`
}

StreamOutput is a metric data push from the stream.

type TimeSeries

type TimeSeries struct {
	MetricID   string            `json:"metric_id"`
	DataPoints []DataPoint       `json:"data_points"`
	Labels     map[string]string `json:"labels"`
}

TimeSeries represents a series of data points for a metric.

func TimeSeriesFromProto

func TimeSeriesFromProto(p *metricpb.TimeSeries) TimeSeries

TimeSeriesFromProto decodes samples and shares label maps with the wire input.

func (*TimeSeries) ToProto

func (t *TimeSeries) ToProto() *metricpb.TimeSeries

ToProto allocates sample messages and shares their label maps with the result.

Jump to

Keyboard shortcuts

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