util

package
v3.3.2 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2024 License: AGPL-3.0 Imports: 54 Imported by: 10

Documentation

Index

Constants

View Source
const (
	// ShardingStrategyDefault shards rule groups across available rulers in the ring.
	ShardingStrategyDefault = "default"
	// ShardingStrategyShuffle shards tenants' rule groups across available rulers in the ring using a
	// shuffle-sharding algorithm.
	ShardingStrategyShuffle = "shuffle-sharding"

	// ShardingAlgoByGroup is an alias of ShardingStrategyDefault.
	ShardingAlgoByGroup = "by-group"
	// ShardingAlgoByRule shards all rules evenly across available rules in the ring, regardless of group.
	// This can be achieved because currently Loki recording/alerting rules cannot not any inter-dependency, unlike
	// Prometheus rules, so there's really no need to shard by group. This will eventually become the new default strategy.
	ShardingAlgoByRule = "by-rule" // this will eventually become the new default strategy.
)

Sharding strategies & algorithms.

View Source
const (
	RingKeyOfLeader = 0
)
View Source
const SplitGap = time.Millisecond

Variables

This section is empty.

Functions

func AllNonGreedy

func AllNonGreedy(regs ...*syntax.Regexp)

AllNonGreedy turns greedy quantifiers such as `.*` and `.+` into non-greedy ones. This is the same effect as writing `.*?` and `.+?`. This is only safe because we use `Match`. If we were to find the exact position and length of the match we would not be allowed to make this optimization. `Match` can return quicker because it is not looking for the longest match. Prepending the expression with `(?U)` or passing `NonGreedy` to the expression compiler is not enough since it will just negate `.*` and `.*?`.

func ClearCapture

func ClearCapture(regs ...*syntax.Regexp)

ClearCapture removes capture operation as they are not used for filtering.

func CopyMap

func CopyMap(m map[string]string) map[string]string

CopyMap makes a copy of the given map

func DeleteMatchingLabels

func DeleteMatchingLabels(c CollectorVec, filter map[string]string) error

DeleteMatchingLabels removes metric with labels matching the filter.

func DurationWithJitter

func DurationWithJitter(input time.Duration, variancePerc float64) time.Duration

DurationWithJitter returns random duration from "input - input*variance" to "input + input*variance" interval.

func DurationWithPositiveJitter

func DurationWithPositiveJitter(input time.Duration, variancePerc float64) time.Duration

DurationWithPositiveJitter returns random duration from "input" to "input + input*variance" interval.

func EntriesTotalSize added in v3.3.0

func EntriesTotalSize(entries []push.Entry) int

func EntryTotalSize added in v3.3.0

func EntryTotalSize(entry *push.Entry) int

func Event

func Event() log.Logger

Event is the log-like API for event sampling

func FlagFromValues

func FlagFromValues(values url.Values, key string, d bool) bool

func ForInterval

func ForInterval(interval time.Duration, start, end time.Time, endTimeInclusive bool, callback func(start, end time.Time))

ForInterval splits the given start and end time into given interval. The start and end time in splits would be aligned to the interval except for the start time of first split and end time of last split which would be kept same as original start/end When endTimeInclusive is true, it would keep a gap of 1ms between the splits.

func FormatTimeMillis

func FormatTimeMillis(ms int64) string

FormatTimeMillis returns a human readable version of the input time (in milliseconds).

func FormatTimeModel

func FormatTimeModel(t model.Time) string

FormatTimeModel returns a human readable version of the input time.

func FromLabelPairsToLabels

func FromLabelPairsToLabels(pairs []*dto.LabelPair) labels.Labels

FromLabelPairsToLabels converts dto.LabelPair into labels.Labels.

func GetFactorOfTime

func GetFactorOfTime(from, through int64, minTime, maxTime int64) (factor float64)

GetFactorOfTime returns the percentage of time that the span `from` to `through` accounts for inside the range `minTime` to `maxTime`. It also returns the leading and trailing time that is not accounted for. Note that `from`, `through`, `minTime` and `maxTime` should have the same scale (e.g. milliseconds).

MinTime  From              Through  MaxTime
┌────────┬─────────────────┬────────┐
│        *                 *        │
└────────┴─────────────────┴────────┘
▲   A    |        C        |   B    ▲
└───────────────────────────────────┘
        T = MinTime - MaxTime

We get the percentage of time that fits into C factor = C = (T - (A + B)) / T = (chunkTime - (leadingTime + trailingTime)) / chunkTime

func GetFirstAddressOf

func GetFirstAddressOf(names []string, logger log.Logger) (string, error)

GetFirstAddressOf returns the first IPv4 address of the supplied interface names, omitting any 169.254.x.x automatic private IPs if possible.

func GetLabels

func GetLabels(c prometheus.Collector, filter map[string]string) ([]labels.Labels, error)

GetLabels returns list of label combinations used by this collector at the time of call. This can be used to find and delete unused metrics.

func GetSumOfHistogramSampleCount

func GetSumOfHistogramSampleCount(families []*dto.MetricFamily, metricName string, matchers labels.Selector) uint64

GetSumOfHistogramSampleCount returns the sum of samples count of histograms matching the provided metric name and optional label matchers. Returns 0 if no metric matches.

func HashFP

func HashFP(fp model.Fingerprint) uint32

HashFP simply moves entropy from the most significant 48 bits of the fingerprint into the least significant 16 bits (by XORing) so that a simple MOD on the result can be used to pick a mutex while still making use of changes in more significant bits of the fingerprint. (The fast fingerprinting function we use is prone to only change a few bits for similar metrics. We really want to make use of every change in the fingerprint to vary mutex selection.)

func HashedQuery

func HashedQuery(query string) uint32

HashedQuery returns a unique hash value for the given `query`.

func HumanizeBytes added in v3.3.0

func HumanizeBytes(val uint64) string

HumanizeBytes returns a human readable string representation of the given byte value and removes all whitespaces.

func InitEvents

func InitEvents(freq int)

InitEvents initializes event sampling, with the given frequency. Zero=off.

func IsCaseInsensitive

func IsCaseInsensitive(reg *syntax.Regexp) bool

func IsConnCanceled

func IsConnCanceled(err error) bool

IsConnCanceled returns true, if error is from a closed gRPC connection. copied from https://github.com/etcd-io/etcd/blob/7f47de84146bdc9225d2080ec8678ca8189a2d2b/clientv3/client.go#L646

func IsRequestBodyTooLarge

func IsRequestBodyTooLarge(err error) bool

IsRequestBodyTooLarge returns true if the error is "http: request body too large".

func IsValidURL added in v3.3.0

func IsValidURL(endpoint string) bool

func LabelsToMetric

func LabelsToMetric(ls labels.Labels) model.Metric

LabelsToMetric converts a Labels to Metric Don't do this on any performance sensitive paths.

func LogConfig

func LogConfig(cfg interface{}) error

LogConfig takes a pointer to a config object, marshalls it to YAML and prints each line in REVERSE order The reverse order makes display in Grafana in easier which typically sorts newest entries at the top.

func LogError

func LogError(message string, f func() error)

LogError logs any error returned by f; useful when deferring Close etc.

func LogErrorWithContext

func LogErrorWithContext(ctx context.Context, message string, f func() error)

LogError logs any error returned by f; useful when deferring Close etc.

func MapToModelLabelSet

func MapToModelLabelSet(m map[string]string) model.LabelSet

MapToModelLabelSet converts a map into a model.LabelSet

func MergeMaps

func MergeMaps(base map[string]string, overlay map[string]string) map[string]string

MergeMaps merges the overlay map onto the base map, with overlay taking precedence NOTE: this treats the given base and overlay maps as immutable, and returns a copy

func MergeNSampleSets

func MergeNSampleSets(sampleSets ...[]model.SamplePair) []model.SamplePair

MergeNSampleSets merges and dedupes n sets of already sorted sample pairs.

func MergeSampleSets

func MergeSampleSets(a, b []model.SamplePair) []model.SamplePair

MergeSampleSets merges and dedupes two sets of already sorted sample pairs.

func MergeStringLists

func MergeStringLists(ss ...[]string) []string

func MergeStringPair

func MergeStringPair(s1, s2 []string) []string

func ModelLabelSetToMap

func ModelLabelSetToMap(m model.LabelSet) map[string]string

ModelLabelSetToMap convert a model.LabelSet to a map[string]string

func NewDNSWatcher

func NewDNSWatcher(address string, dnsLookupPeriod time.Duration, notifications DNSNotifications) (services.Service, error)

NewDNSWatcher creates a new DNS watcher and returns a service that is wrapping it.

func NewDisableableTicker

func NewDisableableTicker(interval time.Duration) (func(), <-chan time.Time)

NewDisableableTicker essentially wraps NewTicker but allows the ticker to be disabled by passing zero duration as the interval. Returns a function for stopping the ticker, and the ticker channel.

func NewRingWatcher

func NewRingWatcher(log log.Logger, ring ring.ReadRing, lookupPeriod time.Duration, notifications DNSNotifications) (services.Service, error)

NewRingWatcher creates a new Ring watcher and returns a service that is wrapping it.

func ParseProtoReader

func ParseProtoReader(ctx context.Context, reader io.Reader, expectedSize, maxSize int, req proto.Message, compression CompressionType) error

ParseProtoReader parses a compressed proto from an io.Reader.

func ParseTime

func ParseTime(s string) (int64, error)

ParseTime parses the string into an int64, milliseconds since epoch.

func PrepareLabelsAndMatchers

func PrepareLabelsAndMatchers(targetLabels []string, matchers []*labels.Matcher, tenantLabel ...string) (map[string]struct{}, []*labels.Matcher, bool)

PrepareLabelsAndMatchers is used by the ingester and index gateway to service volume requests. It returns a map of labels to aggregate into, a list of matchers to match streams against, as well a boolean to indicate if a match all selector was provided.

The last argument, tenantLabel, is optional. If povided, a single string of the internal tenant label namne is expected.

func PrintConfig

func PrintConfig(w io.Writer, config interface{}) error

PrintConfig will takes a pointer to a config object, marshalls it to YAML and prints the result to the provided writer unlike LogConfig, PrintConfig prints the object in naturally ocurring order.

func RegisterCounterVec

func RegisterCounterVec(registerer prometheus.Registerer, namespace, name, help string, labels []string) *prometheus.CounterVec

RegisterCounterVec registers new CounterVec with given name,namespace and labels. If metric was already registered it returns existing instance.

func RenderHTTPResponse

func RenderHTTPResponse(w http.ResponseWriter, v interface{}, t *template.Template, r *http.Request)

RenderHTTPResponse either responds with json or a rendered html page using the passed in template by checking the Accepts header

func RoundToMilliseconds

func RoundToMilliseconds(from, through time.Time) (model.Time, model.Time)

RoundToMilliseconds returns milliseconds precision time from nanoseconds. from will be rounded down to the nearest milliseconds while through is rounded up.

func SerializeProtoResponse

func SerializeProtoResponse(w http.ResponseWriter, resp proto.Message, compression CompressionType) error

SerializeProtoResponse serializes a protobuf response into an HTTP response.

func ShuffleShardExpectedInstances

func ShuffleShardExpectedInstances(shardSize, numZones int) int

ShuffleShardExpectedInstances returns the total number of instances that should be selected for a given tenant. If zone-aware replication is disabled, the input numZones should be 1.

func ShuffleShardExpectedInstancesPerZone

func ShuffleShardExpectedInstancesPerZone(shardSize, numZones int) int

ShuffleShardExpectedInstancesPerZone returns the number of instances that should be selected for each zone when zone-aware replication is enabled. The algorithm expects the shard size to be divisible by the number of zones, in order to have nodes balanced across zones. If it's not, we do round up.

func ShuffleShardSeed

func ShuffleShardSeed(identifier, zone string) int64

ShuffleShardSeed returns seed for random number generator, computed from provided identifier.

func SnakeCase

func SnakeCase(s string) string

SnakeCase converts given string `s` into `snake_case`.

func SplitFiltersAndMatchers

func SplitFiltersAndMatchers(allMatchers []*labels.Matcher) (filters, matchers []*labels.Matcher)

SplitFiltersAndMatchers splits empty matchers off, which are treated as filters, see #220

func StreamWriteYAMLResponse

func StreamWriteYAMLResponse(w http.ResponseWriter, iter chan interface{}, logger log.Logger)

StreamWriteYAMLResponse stream writes data as http response

func StringRef

func StringRef(value string) *string

func StringsContain

func StringsContain(values []string, search string) bool

StringsContain returns true if the search value is within the list of input values.

func StructuredMetadataSize added in v3.3.0

func StructuredMetadataSize(metas push.LabelsAdapter) int

func TimeFromMillis

func TimeFromMillis(ms int64) time.Time

TimeFromMillis is a helper to turn milliseconds -> time.Time

func TimeToMillis

func TimeToMillis(t time.Time) int64

func WriteHTMLResponse

func WriteHTMLResponse(w http.ResponseWriter, message string)

Sends message as text/html response with 200 status code.

func WriteJSONResponse

func WriteJSONResponse(w http.ResponseWriter, v interface{})

WriteJSONResponse writes some JSON as a HTTP response.

func WriteTextResponse

func WriteTextResponse(w http.ResponseWriter, message string)

Sends message as text/plain response with 200 status code.

func WriteYAMLResponse

func WriteYAMLResponse(w http.ResponseWriter, v interface{})

WriteYAMLResponse writes some YAML as a HTTP response.

func YoloBuf

func YoloBuf(s string) []byte

Types

type ActiveUsers

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

ActiveUsers keeps track of latest user's activity timestamp, and allows purging users that are no longer active.

func NewActiveUsers

func NewActiveUsers() *ActiveUsers

func (*ActiveUsers) PurgeInactiveUsers

func (m *ActiveUsers) PurgeInactiveUsers(deadline int64) []string

PurgeInactiveUsers removes users that were last active before given deadline, and returns removed users.

func (*ActiveUsers) UpdateUserTimestamp

func (m *ActiveUsers) UpdateUserTimestamp(userID string, ts int64)

type ActiveUsersCleanupService

type ActiveUsersCleanupService struct {
	services.Service
	// contains filtered or unexported fields
}

ActiveUsersCleanupService tracks active users, and periodically purges inactive ones while running.

func NewActiveUsersCleanupService

func NewActiveUsersCleanupService(cleanupInterval, inactiveTimeout time.Duration, cleanupFn func(string)) *ActiveUsersCleanupService

func NewActiveUsersCleanupWithDefaultValues

func NewActiveUsersCleanupWithDefaultValues(cleanupFn func(string)) *ActiveUsersCleanupService

func (*ActiveUsersCleanupService) ActiveUsers

func (s *ActiveUsersCleanupService) ActiveUsers() []string

func (*ActiveUsersCleanupService) UpdateUserTimestamp

func (s *ActiveUsersCleanupService) UpdateUserTimestamp(user string, now time.Time)

type AllowedTenants

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

AllowedTenants that can answer whether tenant is allowed or not based on configuration. Default value (nil) allows all tenants.

func NewAllowedTenants

func NewAllowedTenants(enabled []string, disabled []string) *AllowedTenants

NewAllowedTenants builds new allowed tenants based on enabled and disabled tenants. If there are any enabled tenants, then only those tenants are allowed. If there are any disabled tenants, then tenant from that list, that would normally be allowed, is disabled instead.

func (*AllowedTenants) IsAllowed

func (a *AllowedTenants) IsAllowed(tenantID string) bool

type BasicAuth

type BasicAuth struct {
	Username string `yaml:"basic_auth_username"`
	Password string `yaml:"basic_auth_password"`
}

BasicAuth configures basic authentication for HTTP clients.

func (BasicAuth) IsEnabled

func (b BasicAuth) IsEnabled() bool

IsEnabled returns false if basic authentication isn't enabled.

func (*BasicAuth) RegisterFlagsWithPrefix

func (b *BasicAuth) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet)

type CollectorVec

type CollectorVec interface {
	prometheus.Collector
	Delete(labels prometheus.Labels) bool
}

CollectorVec is a collector that can delete metrics by labels. Implemented by *prometheus.MetricVec (used by CounterVec, GaugeVec, SummaryVec, and HistogramVec).

type CompressionType

type CompressionType int

CompressionType for encoding and decoding requests and responses.

const (
	NoCompression CompressionType = iota
	RawSnappy
)

Values for CompressionType

type DNSNotifications

type DNSNotifications interface {
	// New address has been discovered by DNS watcher for supplied hostname.
	AddressAdded(address string)

	// Previously-discovered address is no longer resolved for the hostname.
	AddressRemoved(address string)
}

Notifications about address resolution. All notifications are sent on the same goroutine.

type EvictingQueue

type EvictingQueue struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewEvictingQueue

func NewEvictingQueue(capacity int, onEvict func()) (*EvictingQueue, error)

func (*EvictingQueue) Append

func (q *EvictingQueue) Append(entry interface{})

func (*EvictingQueue) Capacity

func (q *EvictingQueue) Capacity() int

func (*EvictingQueue) Clear

func (q *EvictingQueue) Clear()

func (*EvictingQueue) Entries

func (q *EvictingQueue) Entries() []interface{}

func (*EvictingQueue) Length

func (q *EvictingQueue) Length() int

func (*EvictingQueue) SetCapacity

func (q *EvictingQueue) SetCapacity(capacity int) error

type ExtendedMock

type ExtendedMock struct {
	mock.Mock
}

func (*ExtendedMock) GetMockedCallsByMethod

func (m *ExtendedMock) GetMockedCallsByMethod(method string) []mock.Call

type GenerationalMap

type GenerationalMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func NewGenMap

func NewGenMap[K comparable, V any](maxSize int, newV func() V, gcCb func()) GenerationalMap[K, V]

NewGenMap created which maintains at most maxSize recently used entries

func (*GenerationalMap[K, T]) GetOrCreate

func (m *GenerationalMap[K, T]) GetOrCreate(key K) T

type GroupedErrors

type GroupedErrors struct {
	MultiError
}

GroupedErrors implements the error interface, and it contains the errors used to construct it grouped by the error message.

func (GroupedErrors) Error

func (es GroupedErrors) Error() string

Error Returns a concatenated string of the errors grouped by the error message along with the number of occurrences of each error message.

type HeaderAuth

type HeaderAuth struct {
	Type            string `yaml:"type,omitempty"`
	Credentials     string `yaml:"credentials,omitempty"`
	CredentialsFile string `yaml:"credentials_file,omitempty"`
}

HeaderAuth condigures header based authorization for HTTP clients.

func (HeaderAuth) IsEnabled

func (h HeaderAuth) IsEnabled() bool

IsEnabled returns false if header authorization isn't enabled.

func (*HeaderAuth) RegisterFlagsWithPrefix

func (h *HeaderAuth) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet)

type HistogramData

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

HistogramData keeps data required to build histogram Metric.

func (*HistogramData) AddHistogram

func (d *HistogramData) AddHistogram(histo *dto.Histogram)

AddHistogram adds histogram from gathered metrics to this histogram data. Do not call this function after Metric() has been invoked, because histogram created by Metric is using the buckets map (doesn't make a copy), and it's not allowed to change the buckets after they've been passed to a prometheus.Metric.

func (*HistogramData) AddHistogramData

func (d *HistogramData) AddHistogramData(histo HistogramData)

AddHistogramData merges another histogram data into this one. Do not call this function after Metric() has been invoked, because histogram created by Metric is using the buckets map (doesn't make a copy), and it's not allowed to change the buckets after they've been passed to a prometheus.Metric.

func (*HistogramData) Copy

func (d *HistogramData) Copy() *HistogramData

Copy returns a copy of this histogram data.

func (*HistogramData) Metric

func (d *HistogramData) Metric(desc *prometheus.Desc, labelValues ...string) prometheus.Metric

Metric returns prometheus metric from this histogram data.

Note that returned metric shares bucket with this HistogramData, so avoid doing more modifications to this HistogramData after calling Metric.

type HistogramDataCollector

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

HistogramDataCollector combines histogram data, with prometheus descriptor. It can be registered into prometheus to report histogram with stored data. Data can be updated via Add method.

func NewHistogramDataCollector

func NewHistogramDataCollector(desc *prometheus.Desc) *HistogramDataCollector

NewHistogramDataCollector creates new histogram data collector.

func (*HistogramDataCollector) Add

func (*HistogramDataCollector) Collect

func (h *HistogramDataCollector) Collect(out chan<- prometheus.Metric)

func (*HistogramDataCollector) Describe

func (h *HistogramDataCollector) Describe(out chan<- *prometheus.Desc)

type IngesterQueryOptions

type IngesterQueryOptions interface {
	QueryStoreOnly() bool
	QueryIngestersWithin() time.Duration
}

IngesterQueryOptions exists because querier.Config cannot be passed directly to the queryrange package due to an import cycle.

type Jitter

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

func NewJitter

func NewJitter(b time.Duration, d time.Duration) Jitter

NewJitter returns a Jitter object that creates durations with random jitter.

func (Jitter) Duration

func (j Jitter) Duration() time.Duration

Duration returns a random duration from the base duration and +/- jitter

type LogAdapter

type LogAdapter struct {
	log.Logger
}

func NewLogAdapter

func NewLogAdapter(l log.Logger) LogAdapter

func (LogAdapter) Fatal

func (l LogAdapter) Fatal(v ...interface{})

Fatal implements tail.logger

func (LogAdapter) Fatalf

func (l LogAdapter) Fatalf(format string, v ...interface{})

Fatalf implements tail.logger

func (LogAdapter) Fatalln

func (l LogAdapter) Fatalln(v ...interface{})

Fatalln implements tail.logger

func (LogAdapter) Panic

func (l LogAdapter) Panic(v ...interface{})

Panic implements tail.logger

func (LogAdapter) Panicf

func (l LogAdapter) Panicf(format string, v ...interface{})

Panicf implements tail.logger

func (LogAdapter) Panicln

func (l LogAdapter) Panicln(v ...interface{})

Panicln implements tail.logger

func (LogAdapter) Print

func (l LogAdapter) Print(v ...interface{})

Print implements tail.logger

func (LogAdapter) Printf

func (l LogAdapter) Printf(format string, v ...interface{})

Printf implements tail.logger

func (LogAdapter) Println

func (l LogAdapter) Println(v ...interface{})

Println implements tail.logger

type MetricFamiliesPerUser

type MetricFamiliesPerUser []struct {
	// contains filtered or unexported fields
}

MetricFamiliesPerUser is a collection of metrics gathered via calling Gatherer.Gather() method on different gatherers, one per user.

func (MetricFamiliesPerUser) GetSumOfCounters

func (d MetricFamiliesPerUser) GetSumOfCounters(counter string) float64

func (MetricFamiliesPerUser) GetSumOfGauges

func (d MetricFamiliesPerUser) GetSumOfGauges(gauge string) float64

func (MetricFamiliesPerUser) SendMaxOfGauges

func (d MetricFamiliesPerUser) SendMaxOfGauges(out chan<- prometheus.Metric, desc *prometheus.Desc, gauge string)

func (MetricFamiliesPerUser) SendMaxOfGaugesPerUser

func (d MetricFamiliesPerUser) SendMaxOfGaugesPerUser(out chan<- prometheus.Metric, desc *prometheus.Desc, gauge string)

func (MetricFamiliesPerUser) SendSumOfCounters

func (d MetricFamiliesPerUser) SendSumOfCounters(out chan<- prometheus.Metric, desc *prometheus.Desc, counter string)

func (MetricFamiliesPerUser) SendSumOfCountersPerUser

func (d MetricFamiliesPerUser) SendSumOfCountersPerUser(out chan<- prometheus.Metric, desc *prometheus.Desc, counter string)

func (MetricFamiliesPerUser) SendSumOfCountersPerUserWithLabels

func (d MetricFamiliesPerUser) SendSumOfCountersPerUserWithLabels(out chan<- prometheus.Metric, desc *prometheus.Desc, metric string, labelNames ...string)

SendSumOfCountersPerUserWithLabels provides metrics with the provided label names on a per-user basis. This function assumes that `user` is the first label on the provided metric Desc

func (MetricFamiliesPerUser) SendSumOfCountersWithLabels

func (d MetricFamiliesPerUser) SendSumOfCountersWithLabels(out chan<- prometheus.Metric, desc *prometheus.Desc, counter string, labelNames ...string)

func (MetricFamiliesPerUser) SendSumOfGauges

func (d MetricFamiliesPerUser) SendSumOfGauges(out chan<- prometheus.Metric, desc *prometheus.Desc, gauge string)

func (MetricFamiliesPerUser) SendSumOfGaugesPerUser

func (d MetricFamiliesPerUser) SendSumOfGaugesPerUser(out chan<- prometheus.Metric, desc *prometheus.Desc, gauge string)

func (MetricFamiliesPerUser) SendSumOfGaugesPerUserWithLabels

func (d MetricFamiliesPerUser) SendSumOfGaugesPerUserWithLabels(out chan<- prometheus.Metric, desc *prometheus.Desc, metric string, labelNames ...string)

SendSumOfGaugesPerUserWithLabels provides metrics with the provided label names on a per-user basis. This function assumes that `user` is the first label on the provided metric Desc

func (MetricFamiliesPerUser) SendSumOfGaugesWithLabels

func (d MetricFamiliesPerUser) SendSumOfGaugesWithLabels(out chan<- prometheus.Metric, desc *prometheus.Desc, gauge string, labelNames ...string)

func (MetricFamiliesPerUser) SendSumOfHistograms

func (d MetricFamiliesPerUser) SendSumOfHistograms(out chan<- prometheus.Metric, desc *prometheus.Desc, histogramName string)

func (MetricFamiliesPerUser) SendSumOfHistogramsWithLabels

func (d MetricFamiliesPerUser) SendSumOfHistogramsWithLabels(out chan<- prometheus.Metric, desc *prometheus.Desc, histogramName string, labelNames ...string)

func (MetricFamiliesPerUser) SendSumOfSummaries

func (d MetricFamiliesPerUser) SendSumOfSummaries(out chan<- prometheus.Metric, desc *prometheus.Desc, summaryName string)

func (MetricFamiliesPerUser) SendSumOfSummariesPerUser

func (d MetricFamiliesPerUser) SendSumOfSummariesPerUser(out chan<- prometheus.Metric, desc *prometheus.Desc, summaryName string)

func (MetricFamiliesPerUser) SendSumOfSummariesWithLabels

func (d MetricFamiliesPerUser) SendSumOfSummariesWithLabels(out chan<- prometheus.Metric, desc *prometheus.Desc, summaryName string, labelNames ...string)

type MetricFamilyMap

type MetricFamilyMap map[string]*dto.MetricFamily

MetricFamilyMap is a map of metric names to their family (metrics with same name, but different labels) Keeping map of metric name to its family makes it easier to do searches later.

func NewMetricFamilyMap

func NewMetricFamilyMap(metrics []*dto.MetricFamily) (MetricFamilyMap, error)

NewMetricFamilyMap sorts output from Gatherer.Gather method into a map. Gatherer.Gather specifies that there metric families are uniquely named, and we use that fact here. If they are not, this method returns error.

func (MetricFamilyMap) MaxGauges

func (mfm MetricFamilyMap) MaxGauges(name string) float64

func (MetricFamilyMap) SumCounters

func (mfm MetricFamilyMap) SumCounters(name string) float64

func (MetricFamilyMap) SumGauges

func (mfm MetricFamilyMap) SumGauges(name string) float64

func (MetricFamilyMap) SumHistograms

func (mfm MetricFamilyMap) SumHistograms(name string) HistogramData

func (MetricFamilyMap) SumHistogramsTo

func (mfm MetricFamilyMap) SumHistogramsTo(name string, output *HistogramData)

func (MetricFamilyMap) SumSummaries

func (mfm MetricFamilyMap) SumSummaries(name string) SummaryData

func (MetricFamilyMap) SumSummariesTo

func (mfm MetricFamilyMap) SumSummariesTo(name string, output *SummaryData)

type MetricLabelTransformFunc

type MetricLabelTransformFunc func(k, v string) string

MetricLabelTransformFunc exists in ruler package, but that would create a cyclic import, so is duplicated here

type MultiError

type MultiError []error

The MultiError type implements the error interface, and contains the Errors used to construct it.

func (*MultiError) Add

func (es *MultiError) Add(err error)

Add adds the error to the error list if it is not nil.

func (MultiError) Err

func (es MultiError) Err() error

Err returns the error list as an error or nil if it is empty.

func (MultiError) Error

func (es MultiError) Error() string

Returns a concatenated string of the contained errors

func (MultiError) Is

func (es MultiError) Is(target error) bool

Is tells if all errors are the same as the target error.

func (MultiError) IsDeadlineExceeded

func (es MultiError) IsDeadlineExceeded() bool

IsDeadlineExceeded tells if all errors are either context.DeadlineExceeded or grpc codes.DeadlineExceeded.

type NoopRegistry

type NoopRegistry struct{}

func (NoopRegistry) MustRegister

func (n NoopRegistry) MustRegister(...prometheus.Collector)

MustRegister implements prometheus.Registerer.

func (NoopRegistry) Register

func (n NoopRegistry) Register(prometheus.Collector) error

Register implements prometheus.Registerer.

func (NoopRegistry) Unregister

func (n NoopRegistry) Unregister(prometheus.Collector) bool

Unregister implements prometheus.Registerer.

type Op

type Op interface {
	Key() string
	Priority() int64 // The larger the number the higher the priority.
}

Op is an operation on the priority queue.

type PriorityQueue

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

PriorityQueue is a priority queue.

func NewPriorityQueue

func NewPriorityQueue(lengthGauge prometheus.Gauge) *PriorityQueue

NewPriorityQueue makes a new priority queue.

func (*PriorityQueue) Close

func (pq *PriorityQueue) Close()

Close signals that the queue should be closed when it is empty. A closed queue will not accept new items.

func (*PriorityQueue) Dequeue

func (pq *PriorityQueue) Dequeue() Op

Dequeue will return the op with the highest priority; block if queue is empty; returns nil if queue is closed.

func (*PriorityQueue) DiscardAndClose

func (pq *PriorityQueue) DiscardAndClose()

DiscardAndClose closes the queue and removes all the items from it.

func (*PriorityQueue) Enqueue

func (pq *PriorityQueue) Enqueue(op Op) bool

Enqueue adds an operation to the queue in priority order. Returns true if added; false if the operation was already on the queue.

func (*PriorityQueue) Length

func (pq *PriorityQueue) Length() int

Length returns the length of the queue.

type QueryStringBuilder

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

func NewQueryStringBuilder

func NewQueryStringBuilder() *QueryStringBuilder

func (*QueryStringBuilder) Encode

func (b *QueryStringBuilder) Encode() string

Encode returns the URL-encoded query string based on key-value parameters added to the builder calling Set functions.

func (*QueryStringBuilder) SetFloat

func (b *QueryStringBuilder) SetFloat(name string, value float64)

func (*QueryStringBuilder) SetFloat32

func (b *QueryStringBuilder) SetFloat32(name string, value float32)

func (*QueryStringBuilder) SetInt

func (b *QueryStringBuilder) SetInt(name string, value int64)

func (*QueryStringBuilder) SetInt32

func (b *QueryStringBuilder) SetInt32(name string, value int)

func (*QueryStringBuilder) SetString

func (b *QueryStringBuilder) SetString(name, value string)

func (*QueryStringBuilder) SetStringArray

func (b *QueryStringBuilder) SetStringArray(name string, values []string)

type Queue

type Queue interface {
	Append(entry interface{})
	Entries() []interface{}
	Length() int
	Clear()
}

type SizeReader

type SizeReader interface {
	io.Reader
	Size() int64
}

func NewSizeReader

func NewSizeReader(r io.Reader) SizeReader

NewSizeReader returns an io.Reader that will have the number of bytes read from r available.

type SummaryData

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

SummaryData keeps all data needed to create summary metric

func (*SummaryData) AddSummary

func (s *SummaryData) AddSummary(sum *dto.Summary)

func (*SummaryData) Metric

func (s *SummaryData) Metric(desc *prometheus.Desc, labelValues ...string) prometheus.Metric

type TickerWithJitter

type TickerWithJitter struct {
	C chan time.Time
	// contains filtered or unexported fields
}

func NewTickerWithJitter

func NewTickerWithJitter(d, dev time.Duration) *TickerWithJitter

NewTickerWithJitter returns a new Ticker-like object, but instead of a constant tick duration, it adds random +/- dev to each iteration.

func (*TickerWithJitter) Stop

func (t *TickerWithJitter) Stop()

type UniqueStrings

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

UniqueStrings keeps a slice of unique strings.

func NewUniqueStrings

func NewUniqueStrings(sizeHint int) UniqueStrings

NewUniqueStrings returns a UniqueStrings instance with a pre-allocated result buffer.

func (*UniqueStrings) Add

func (us *UniqueStrings) Add(strings ...string)

Add adds a new string, dropping duplicates.

func (UniqueStrings) Strings

func (us UniqueStrings) Strings() []string

Strings returns the sorted sliced of unique strings.

type UserRegistries

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

UserRegistries holds Prometheus registries for multiple users, guaranteeing multi-thread safety and stable ordering.

func NewUserRegistries

func NewUserRegistries() *UserRegistries

NewUserRegistries makes new UserRegistries.

func (*UserRegistries) AddUserRegistry

func (r *UserRegistries) AddUserRegistry(user string, reg *prometheus.Registry)

AddUserRegistry adds an user registry. If user already has a registry, previous registry is removed, but latest metric values are preserved in order to avoid counter resets.

func (*UserRegistries) BuildMetricFamiliesPerUser

func (r *UserRegistries) BuildMetricFamiliesPerUser(labelTransformFn MetricLabelTransformFunc) MetricFamiliesPerUser

func (*UserRegistries) Registries

func (r *UserRegistries) Registries() []UserRegistry

Registries returns a copy of the user registries list.

func (*UserRegistries) RemoveUserRegistry

func (r *UserRegistries) RemoveUserRegistry(user string, hard bool)

RemoveUserRegistry removes all Prometheus registries for a given user. If hard is true, registry is removed completely. If hard is false, latest registry values are preserved for future aggregations.

type UserRegistry

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

UserRegistry holds a Prometheus registry associated to a specific user.

Directories

Path Synopsis
Package fakeauth provides middlewares thats injects a fake userID, so the rest of the code can continue to be multitenant.
Package fakeauth provides middlewares thats injects a fake userID, so the rest of the code can continue to be multitenant.
Package marshal converts internal objects to loghttp model objects.
Package marshal converts internal objects to loghttp model objects.
legacy
Package marshal converts internal objects to loghttp model objects.
Package marshal converts internal objects to loghttp model objects.

Jump to

Keyboard shortcuts

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