metric

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2024 License: Apache-2.0, BSD-3-Clause, MIT Imports: 27 Imported by: 6

Documentation

Overview

Package metric

Package metric

Package metric

Package metric

Index

Constants

View Source
const (
	// ClientStartedCounter the total number of RPCs started on the client.
	ClientStartedCounter = "ClientStartedCounter"
	// ClientHandledCounter the total number of RPCs completed by the client, regardless of success or failure.
	ClientHandledCounter = "ClientHandledCounter"
	// ClientHandledHistogram the Histogram of response latency (seconds) of the RPC
	// until it is finished by the application.
	ClientHandledHistogram = "ClientHandledHistogram"
)
View Source
const (
	CodeTypeSuccess   = codes.CodeTypeSuccess
	CodeTypeException = codes.CodeTypeException
	CodeTypeTimeout   = codes.CodeTypeTimeout
)
View Source
const (
	// ServerStartedCounter the number of RPCs started on the server.
	ServerStartedCounter = "ServerStartedCounter"
	// ServerHandledCounter the number of RPCs completed on the server, regardless of success or failure.
	ServerHandledCounter = "ServerHandledCounter"
	// ServerHandledHistogram the response latency (seconds) of RPC that had been application-level handled by the server.
	ServerHandledHistogram = "ServerHandledHistogram"
)

Variables

View Source
var (
	// PerMetricCardinalityLimit ...
	// ref: https://prometheus.io/docs/practices/naming/#labels
	// https://prometheus.io/docs/prometheus/latest/querying/basics/#avoiding-slow-queries-and-overloads
	PerMetricCardinalityLimit = 2000
	// TotalMetricCardinalityLimit ...
	TotalMetricCardinalityLimit = 10000
)
View Source
var (
	// DefaultRegisterTTL default register ttl
	DefaultRegisterTTL = registry.DefaultRegisterTTL
	// DefaultDialTimeout default dail timeout
	DefaultDialTimeout = registry.DefaultDialTimeout
)
View Source
var (
	DefaultCodeTypeFunc = codes.DefaultCodeTypeFunc

	NewCodeTypeMappingDescription = codes.NewCodeTypeMappingDescription
)
View Source
var CleanRPCMethod = defaultCleanRPCMethod

CleanRPCMethod for high-cardinality problem

View Source
var DefaultClientMetrics = NewClientMetrics()

DefaultClientMetrics is the default instance of ClientMetrics. It is intended to be used in conjunction the default Prometheus metrics registry. Note: only used stream metrics now

View Source
var DefaultServerMetrics = NewServerMetrics()

DefaultServerMetrics is the default instance of ServerMetrics. It is intended to be used in conjunction the default Prometheus metrics registry.

View Source
var (
	NewCode = codes.NewCode
)
View Source
var (
	NewEtcdRegistry = registry.NewEtcdRegistry
)
View Source
var (
	// ServerPanicTotal server panic count total
	ServerPanicTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Subsystem: "rpc",
			Name:      "server_panic_total",
			Help:      "Total number of RPCs panic on the server.",
		},
		[]string{"system_name"})
)

Functions

func DeletePrometheusPush

func DeletePrometheusPush() error

DeletePrometheusPush send delete request to prometheus push gateway

func EnableClientStreamReceiveTimeHistogram

func EnableClientStreamReceiveTimeHistogram(opts ...HistogramOption)

EnableClientStreamReceiveTimeHistogram turns on recording of single message receive time of streaming RPCs. This function acts on the DefaultClientMetrics variable and the default Prometheus metrics registry.

func EnableClientStreamSendTimeHistogram

func EnableClientStreamSendTimeHistogram(opts ...HistogramOption)

EnableClientStreamSendTimeHistogram turns on recording of single message send time of streaming RPCs. This function acts on the DefaultClientMetrics variable and the default Prometheus metrics registry.

func LimitMetricsHandler

func LimitMetricsHandler() http.Handler

LimitMetricsHandler handler for limited metrics avoiding Prometheus server OOM

func RegisterMethodMapping

func RegisterMethodMapping(regexStr string, pattern string)

RegisterMethodMapping 在初始化函数中注册 method regex->pattern 映射, 将含有 path 参数的 高基数method 转换为 低基数的 method pattern, regexStr 不合法将 Panic.

func SetCleanRPCMethodFunc

func SetCleanRPCMethodFunc(f CleanRPCMethodFunc)

SetCleanRPCMethodFunc set cleanRPCMethod for high-cardinality problem

func SetClientLabelsOption

func SetClientLabelsOption(f func(name string) []string)

SetClientLabelsOption other users can use this function to redefine clientLabelsOption.

func SetProcessor

func SetProcessor(p Processor)

SetProcessor set metric processor

func SetServerLabelsOption

func SetServerLabelsOption(f func(name string) []string)

SetServerLabelsOption users can use this function to redefine serverLabelsOption.

func Setup

func Setup(opts ...SetupOption) error

Setup setup metrics

func SetupByConfig

func SetupByConfig(cfg Config) error

SetupByConfig setup by config

Types

type CleanRPCMethodFunc

type CleanRPCMethodFunc func(string) string

CleanRPCMethodFunc CleanRPCMethod func

type ClientMetrics

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

ClientMetrics represents a collection of metrics to be registered on a Prometheus metrics registry for a rpc client.

func NewClientMetrics

func NewClientMetrics(counterOpts ...CounterOption) *ClientMetrics

NewClientMetrics returns a ClientMetrics object. Use a new instance of ClientMetrics when not using the default Prometheus metrics registry, for example when wanting to control which metrics are added to a registry as opposed to automatically adding metrics via init functions.

func (*ClientMetrics) ClientStartedCounter

func (m *ClientMetrics) ClientStartedCounter() *prometheus.CounterVec

ClientStartedCounter returns clientStarted counter vec

func (*ClientMetrics) ClientStreamMsgReceived

func (m *ClientMetrics) ClientStreamMsgReceived() *prometheus.CounterVec

ClientStreamMsgReceived returns clientStreamMsgReceived counter vec

func (*ClientMetrics) ClientStreamMsgSent

func (m *ClientMetrics) ClientStreamMsgSent() *prometheus.CounterVec

ClientStreamMsgSent returns clientStreamMsgSent counter vec

func (*ClientMetrics) ClientStreamRecvHistogram

func (m *ClientMetrics) ClientStreamRecvHistogram() *prometheus.HistogramVec

ClientStreamRecvHistogram returns clientStreamRecvHistogram histogram vec

func (*ClientMetrics) ClientStreamSendHistogram

func (m *ClientMetrics) ClientStreamSendHistogram() *prometheus.HistogramVec

ClientStreamSendHistogram returns clientStreamSendHistogram histogram vec

func (*ClientMetrics) Collect

func (m *ClientMetrics) Collect(ch chan<- prometheus.Metric)

Collect is called by the Prometheus registry when collecting metrics. The implementation sends each collected metric via the provided channel and returns once the last metric has been sent.

func (*ClientMetrics) Describe

func (m *ClientMetrics) Describe(ch chan<- *prometheus.Desc)

Describe sends the super-set of all possible descriptors of metrics collected by this Collector to the provided channel and returns once the last descriptor has been sent.

func (*ClientMetrics) EnableClientStreamReceiveTimeHistogram

func (m *ClientMetrics) EnableClientStreamReceiveTimeHistogram(opts ...HistogramOption)

EnableClientStreamReceiveTimeHistogram turns on recording of single message receive time of streaming RPCs. Histogram metrics can be very expensive for Prometheus to retain and query.

func (*ClientMetrics) EnableClientStreamSendTimeHistogram

func (m *ClientMetrics) EnableClientStreamSendTimeHistogram(opts ...HistogramOption)

EnableClientStreamSendTimeHistogram turns on recording of single message send time of streaming RPCs. Histogram metrics can be very expensive for Prometheus to retain and query.

func (*ClientMetrics) Reset

func (m *ClientMetrics) Reset()

Reset resets the metrics.

type ClientOption

type ClientOption func(*ClientReporter)

ClientOption Client 调用参数工具函数。

func WithClientEndTime

func WithClientEndTime(endTime time.Time) ClientOption

WithClientEndTime 设置endTime

func WithClientExtraLabels

func WithClientExtraLabels(labels []string) ClientOption

WithClientExtraLabels 设置 Labels。

func WithClientMetrics

func WithClientMetrics(metrics *ClientMetrics) ClientOption

WithClientMetrics 设置metrics

func WithClientRPCType

func WithClientRPCType(rpcType RPCType) ClientOption

WithClientRPCType 设置rpcType

func WithClientStartTime

func WithClientStartTime(startTime time.Time) ClientOption

WithClientStartTime 设置startTime

func WithClientTraceConfig

func WithClientTraceConfig(enableDeferredSample, deferredSampleError bool,
	deferredSampleSlowDuration time.Duration) ClientOption

WithClientTraceConfig 设置 Trace 相关配置

type ClientReporter

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

ClientReporter ...

func NewClientReporter

func NewClientReporter(systemName, callerService, callerMethod, calleeService, calleeMethod string,
	options ...ClientOption,
) *ClientReporter

NewClientReporter create a client reporter systemName, callerService, callerMethod, calleeService, calleeMethod 为保留字段。 新增labels 为扩展字段,注意使用扩展字段需要重定义 sdk/metric/rpc_client_metrics.go:40 所在的初始化函数。

func (*ClientReporter) Handled

func (r *ClientReporter) Handled(ctx context.Context, code string)

Handled is called after the request is processed. systemName, callerService, callerMethod, calleeService, calleeMethod, code, codeType.Type, codeType.Description are reserved fields. Add labels as extended fields. Note that using extended fields requires redefining the initialization function where sdk/metric/rpc_client_metrics.go:40 is located.

func (*ClientReporter) ReceiveMessageTimer

func (r *ClientReporter) ReceiveMessageTimer() Timer

ReceiveMessageTimer returns Timer for receive message.

func (*ClientReporter) ReceivedMessage

func (r *ClientReporter) ReceivedMessage()

ReceivedMessage reports metrics after stream rpc received a message.

func (*ClientReporter) SendMessageTimer

func (r *ClientReporter) SendMessageTimer() Timer

SendMessageTimer returns Timer for sending a message.

func (*ClientReporter) SentMessage

func (r *ClientReporter) SentMessage()

SentMessage reports metrics after stream rpc message was sent.

type Code

type Code = codes.Code

type CodeType

type CodeType = codes.CodeType

type CodeTypeFunc

type CodeTypeFunc = codes.CodeTypeFunc

type CodeTypeMappingDescription

type CodeTypeMappingDescription = codes.CodeTypeMappingDescription

type Config

type Config struct {
	// Enabled open or close
	Enabled bool `yaml:"enabled"`
	// EnabledRegister default enabled
	EnabledRegister bool `yaml:"enable_register"`
	// RegistryEndpoints registry addrs
	RegistryEndpoints []string `yaml:"registry_endpoints"`
	// TLS credentials
	TLSCert TLSCert `yaml:"tls_cert"`
	// TTL Time to live
	TTL time.Duration `yaml:"ttl"`
	// Instance registry instance info
	Instance Instance `yaml:"instance"`
	// ServerOwner is server owner user, for send alert
	ServerOwner string `yaml:"server_owner"`
	// CmdbID is cmdbID
	CmdbID string `yaml:"cmdb_id"`
	// Codes code mapping
	Codes []*Code `yaml:"codes"`
	// Configurator only for experimental usage
	Configurator remote.Configurator `yaml:"-"`
	// ClientHistogramBuckets user can config client histogram buckets
	ClientHistogramBuckets []float64 `yaml:"client_histogram_buckets"`
	// ServerHistogramBuckets user can config server histogram buckets
	ServerHistogramBuckets []float64 `yaml:"server_histogram_buckets"`
	// ClientStreamRecvHistogramBuckets user can config client stream recv histogram buckets
	ClientStreamRecvHistogramBuckets []float64 `yaml:"client_stream_recv_histogram_buckets"`
	// ClientStreamSendHistogramBuckets user can config client stream recv histogram buckets
	ClientStreamSendHistogramBuckets []float64 `yaml:"client_stream_send_histogram_buckets"`
	// PrometheusPush prometheus push config
	PrometheusPush PrometheusPushConfig `yaml:"prometheus_push"`
	// EnabledZPage zPage option
	EnabledZPage bool
}

Config metric config

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig 默认配置

type CounterOption

type CounterOption func(*prom.CounterOpts)

A CounterOption lets you add options to Counter metrics using With* funcs.

func WithConstLabels

func WithConstLabels(labels prom.Labels) CounterOption

WithConstLabels allows you to add ConstLabels to Counter metrics.

type HistogramOption

type HistogramOption func(*prom.HistogramOpts)

A HistogramOption lets you add options to Histogram metrics using With*funcs.

func WithHistogramBuckets

func WithHistogramBuckets(buckets []float64) HistogramOption

WithHistogramBuckets allows you to specify custom bucket ranges for histograms if EnableHandlingTimeHistogram is on.

func WithHistogramConstLabels

func WithHistogramConstLabels(labels prom.Labels) HistogramOption

WithHistogramConstLabels allows you to add custom ConstLabels to histograms metrics.

type Instance

type Instance struct {
	// Addr metrics server
	Addr string `json:"addr" yaml:"addr"`
	// TenantID tenantID
	TenantID string `json:"tenant_id" yaml:"tenant_id"`
	// Metadata ...
	Metadata map[string]string `json:"metadata" yaml:"metadata"`
	// KeySuffix key suffix for Etcd registration
	KeySuffix string `json:"-" yaml:"-"`
	// Key user-defined key
	Key string `json:"-" yaml:"-"`
}

Instance ...

func (*Instance) GetKey

func (ins *Instance) GetKey() string

GetKey ...

func (*Instance) GetValue

func (ins *Instance) GetValue() string

GetValue marshal instance to string

type LimitCardinalityCollector

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

LimitCardinalityCollector collector for limit cardinality

func (*LimitCardinalityCollector) Collect

func (c *LimitCardinalityCollector) Collect(ch chan<- prometheus.Metric)

Collect called when pull metrics

type LimitCardinalityGatherer

type LimitCardinalityGatherer struct {
	prometheus.Gatherer
	PerMetirclimit   int
	TotalMetricLimit int
}

LimitCardinalityGatherer struct for limit cardinality gatherer

func (*LimitCardinalityGatherer) Gather

func (l *LimitCardinalityGatherer) Gather() ([]*dto.MetricFamily, error)

Gather implements prometheus.Gatherer

type MethodMapping

type MethodMapping struct {
	Regex   *regexp.Regexp
	Pattern string
}

MethodMapping ...

type Processor

type Processor func(metrics []*dto.MetricFamily) []*dto.MetricFamily

Processor metric processor user-defined hook for metric

type PrometheusPushConfig

type PrometheusPushConfig struct {
	Enabled      bool              `yaml:"enabled"`
	URL          string            `yaml:"url"`
	Job          string            `yaml:"job"`
	Interval     time.Duration     `yaml:"interval"`
	UseBasicAuth bool              `yaml:"use_basic_auth"`
	Username     string            `yaml:"username"`
	Password     string            `yaml:"password"`
	Grouping     map[string]string `yaml:"grouping"`
	HTTPHeaders  map[string]string `yaml:"http_headers"`
}

PrometheusPushConfig prometheus push config

func DefaultPrometheusPushConfig

func DefaultPrometheusPushConfig() PrometheusPushConfig

DefaultPrometheusPushConfig default prometheus push config

type RPCType

type RPCType string

RPCType is the type of RPC.

const (
	Unary        RPCType = "unary"         // Unary RPC
	ClientStream RPCType = "client_stream" // Client-stream RPC
	ServerStream RPCType = "server_stream" // Server-stream RPC
	BidiStream   RPCType = "bidi_stream"   // Bidi-stream RPC
)

RPCType enum

type Registry

type Registry = registry.Registry

type RegistryInstance

type RegistryInstance = registry.Instance

type ServerMetrics

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

ServerMetrics represents a collection of metrics to be registered on a Prometheus metrics registry for a rpc server. NOTE: only used for stream rpc now

func NewServerMetrics

func NewServerMetrics(counterOpts ...CounterOption) *ServerMetrics

NewServerMetrics returns a ServerMetrics object. Use a new instance of ServerMetrics when not using the default Prometheus metrics registry, for example when wanting to control which metrics are added to a registry as opposed to automatically adding metrics via init functions.

func (*ServerMetrics) Collect

func (m *ServerMetrics) Collect(ch chan<- prometheus.Metric)

Collect is called by the Prometheus registry when collecting metrics. The implementation sends each collected metric via the provided channel and returns once the last metric has been sent.

func (*ServerMetrics) Describe

func (m *ServerMetrics) Describe(ch chan<- *prometheus.Desc)

Describe sends the super-set of all possible descriptors of metrics collected by this Collector to the provided channel and returns once the last descriptor has been sent.

func (*ServerMetrics) Reset

func (m *ServerMetrics) Reset()

Reset resets the metrics.

func (*ServerMetrics) ServerStartedCounter

func (m *ServerMetrics) ServerStartedCounter() *prometheus.CounterVec

ServerStartedCounter returns serverStartedCounter counter vec

func (*ServerMetrics) ServerStreamMsgReceived

func (m *ServerMetrics) ServerStreamMsgReceived() *prometheus.CounterVec

ServerStreamMsgReceived returns serverStreamMsgReceived counter vec

func (*ServerMetrics) ServerStreamMsgSent

func (m *ServerMetrics) ServerStreamMsgSent() *prometheus.CounterVec

ServerStreamMsgSent returns serverStreamMsgSent counter vec

type ServerOption

type ServerOption func(reporter *ServerReporter)

ServerOption Server option

func WithServerEndTime

func WithServerEndTime(endTime time.Time) ServerOption

WithServerEndTime set endTime

func WithServerExtraLabels

func WithServerExtraLabels(labels []string) ServerOption

WithServerExtraLabels set server extraLabels.

func WithServerMetrics

func WithServerMetrics(metrics *ServerMetrics) ServerOption

WithServerMetrics set metrics

func WithServerRPCType

func WithServerRPCType(rpcType RPCType) ServerOption

WithServerRPCType set rpcType

func WithServerStartTime

func WithServerStartTime(startTime time.Time) ServerOption

WithServerStartTime set startTime

func WithServerTraceConfig

func WithServerTraceConfig(enableDeferredSample, deferredSampleError bool,
	deferredSampleSlowDuration time.Duration) ServerOption

WithServerTraceConfig set server trace config

type ServerReporter

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

ServerReporter server metrics reporter

func NewServerReporter

func NewServerReporter(systemName, callerService, callerMethod, calleeService, calleeMethod string,
	options ...ServerOption,
) *ServerReporter

NewServerReporter create a server reporter. systemName, callerService, callerMethod, calleeService, calleeMethod are reserved fields. Add labels as extended fields. Note that using extended fields requires redefining the initialization function in sdk/metric/rpc_server_metrics.go.

func (*ServerReporter) Handled

func (r *ServerReporter) Handled(ctx context.Context, code string)

Handled called after the request has been processed. systemName, callerService, callerMethod, calleeService, calleeMethod, code, codeType.Type, codeType.Description are reserved fields. Add labels as extended fields. Note that using extended fields requires redefining the initialization function in sdk/metric/rpc_server_metrics.go.

func (*ServerReporter) ReceivedMessage

func (r *ServerReporter) ReceivedMessage()

ReceivedMessage reports metrics for server stream received message.

func (*ServerReporter) SentMessage

func (r *ServerReporter) SentMessage()

SentMessage reports metrics for server stream sent message.

type SetupOption

type SetupOption func(config *Config)

func WithClientHistogramBuckets

func WithClientHistogramBuckets(buckets []float64) SetupOption

WithClientHistogramBuckets set client histogram buckets

func WithConfigurator

func WithConfigurator(configurator remote.Configurator) SetupOption

WithConfigurator .

func WithEnabled

func WithEnabled(enabled bool) SetupOption

WithEnabled .

func WithEnabledRegister

func WithEnabledRegister(enabled bool) SetupOption

WithEnabledRegister .

func WithEnabledZPage

func WithEnabledZPage(enabled bool) SetupOption

WithEnabledZPage .

func WithInstance

func WithInstance(ins *Instance) SetupOption

WithInstance .

func WithMetricsPrometheusPush

func WithMetricsPrometheusPush(p PrometheusPushConfig) SetupOption

WithMetricsPrometheusPush prometheus push config

func WithRegistryEndpoints

func WithRegistryEndpoints(endpoints []string) SetupOption

WithRegistryEndpoints registry endpoints addr

func WithServerHistogramBuckets

func WithServerHistogramBuckets(buckets []float64) SetupOption

WithServerHistogramBuckets set server histogram buckets

func WithTLSCert

func WithTLSCert(cert TLSCert) SetupOption

WithTLSCert .

func WithTSLCert

func WithTSLCert(cert TLSCert) SetupOption

WithTSLCert set TSLCert

func WithTTL

func WithTTL(ttl time.Duration) SetupOption

WithTTL register ttl

type TLSCert

type TLSCert struct {
	CertContent   string `yaml:"cert_content"`    // CA in string
	KeyContent    string `yaml:"key_content"`     // private key in string
	CaCertContent string `yaml:"ca_cert_content"` // CaCert in string
}

TLSCert etcd need 3 credentials

type Timer

type Timer interface {
	ObserveDuration() time.Duration
}

Timer is a helper interface to time functions.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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