userver: utils::statistics Namespace Reference
Loading...
Searching...
No Matches
utils::statistics Namespace Reference

Detailed Description

Statistics writers, metric types, and histogram helpers.

Classes

class  BaseFormatBuilder
class  BusyMarker
 A RAII-style guard to account code block execution time in utils::statistics::BusyStorage. Aware of recursive invocations in the same thread. More...
class  BusyStorage
class  DuplicateLabelError
 Thrown when one metric lists the same label name more than once. The values may differ. More...
class  DuplicateMetricError
 Thrown when a snapshot contains two metrics with the same path and labels. More...
class  Histogram
 A histogram with a dynamically-allocated array of buckets. More...
class  HistogramAggregator
 Used to aggregate multiple utils::statistics::Histogram metrics. More...
class  HistogramView
 The non-owning reader API for "histogram" metrics. More...
class  InvalidMetricError
 Thrown when metrics written into a snapshot are invalid. More...
class  Label
 Label name+value storage. More...
class  LabelsSpan
 View over a continuous range of LabelView. More...
class  LabelView
 Non owning label name+value storage. More...
class  MetricQueryError
 Thrown by utils::statistics::Snapshot queries on unexpected metrics states. More...
class  MetricsStorage
 Storage of metrics registered with MetricTag<Metric>. More...
class  MetricTag
 Metric description and registration in a declarative way. More...
class  MetricValue
 The value of a metric. More...
struct  MetricView
 A non-owning view of a single metric: its path, labels and value. More...
class  MinMaxAvg
 Class for concurrent safe calculation of minimum, maximum and average over series of values. More...
class  MonotonicByLabelStorage
 Thread-safe monotonic storage of metrics indexed by label values. More...
class  Percentile
 Class allows easy calculation of percentiles. More...
struct  Rate
 Rate metrics (or "counter" metrics) are metrics that only monotonically increase or are reset to zero on restart. Some monitoring systems give them special treatment with regard to maintaining proper non-negative derivative. More...
class  RateCounter
 Atomic counter of type Rate with relaxed memory ordering by default. More...
class  RecentPeriod
 Class maintains circular buffer of Counters. More...
class  RelaxedCounter
 Atomic counter of type T with relaxed memory ordering. More...
class  Request
 Class describing the request for metrics data. More...
class  Snapshot
 A snapshot of metrics dumped via utils::statistics::Writer. More...
struct  SnapshotBuildOptions
 Filters metrics collected by utils::statistics::Snapshot constructors. More...
struct  SnapshotLoadOptions
 Prefix and labels applied to every metric in utils::statistics::Snapshot::FromJson and utils::statistics::Snapshot::FromLayeredJson. More...
class  Storage
class  StripedRateCounter
 Atomic counter of type Rate with relaxed memory ordering, increased memory consumption and decreased contention. More...
struct  Warning
class  Writer
 Class for writing metrics that is provided by utils::statistics::Storage. More...

Typedefs

using MetricsStoragePtr = std::shared_ptr<MetricsStorage>
using PortabilityWarnings = std::unordered_map<WarningCode, std::vector<Warning>>
using WriterFuncRef = utils::function_ref<void(Writer&) const>
 Non-owning reference to a function that writes metrics via utils::statistics::Writer.
using WriterFunc = std::function<void(Writer&)>

Enumerations

enum class  WarningCode {
  kInf ,
  kNan ,
  kHistogramBucketsCount ,
  kLabelsCount ,
  kReservedLabelApplication ,
  kReservedLabelCluster ,
  kReservedLabelGroup ,
  kReservedLabelHost ,
  kReservedLabelProject ,
  kReservedLabelSensor ,
  kReservedLabelService ,
  kLabelNameLength ,
  kLabelValueLength ,
  kPathLength ,
  kLabelNameMismatch
}

Functions

std::string DurationToString (std::chrono::seconds duration)
std::string ToGraphiteFormat (WriterFuncRef writer, const Request &statistics_request={})
 Output statistics in Graphite format with tags (labels).
std::string ToGraphiteFormat (const HasWriterSupport auto &metric, const Request &statistics_request={})
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void DumpMetric (Writer &writer, const Histogram &histogram)
 Metric serialization support for Histogram.
void DumpMetric (Writer &writer, const HistogramAggregator &histogram)
 Metric serialization support for utils::statistics::HistogramAggregator.
bool operator== (HistogramView lhs, HistogramView rhs) noexcept
std::string ToJsonFormat (WriterFuncRef writer, const Request &statistics_request={})
std::string ToJsonFormat (const HasWriterSupport auto &metric, const Request &statistics_request={})
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
std::strong_ordering operator<=> (const LabelView &x, const LabelView &y) noexcept
bool operator== (const LabelView &x, const LabelView &y) noexcept
std::strong_ordering operator<=> (const Label &x, const Label &y) noexcept
bool operator== (const Label &x, const Label &y) noexcept
template<typename ValueType, typename AverageType>
auto Serialize (const MinMaxAvg< ValueType, AverageType > &mma, formats::serialize::To< formats::json::Value >)
template<typename ValueType, typename AverageType>
void DumpMetric (Writer &writer, const MinMaxAvg< ValueType, AverageType > &value)
std::string GetPercentileFieldName (double perc)
template<size_t M, typename Counter, size_t ExtraBuckets, size_t ExtraBucketSize>
void DumpMetric (Writer &writer, const Percentile< M, Counter, ExtraBuckets, ExtraBucketSize > &perc, std::initializer_list< double > percents={0, 50, 90, 95, 98, 99, 99.6, 99.9, 100})
formats::json::Value Serialize (const std::vector< Label > &labels, formats::serialize::To< formats::json::Value >)
formats::json::Value Serialize (const Warning &entry, formats::serialize::To< formats::json::Value >)
std::string_view ToString (WarningCode code)
formats::json::Value Serialize (const PortabilityWarnings &info, formats::serialize::To< formats::json::Value >)
PortabilityWarnings GetPortabilityWarnings (WriterFuncRef writer, const Request &request)
PortabilityWarnings GetPortabilityWarnings (const HasWriterSupport auto &metric, const Request &request)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
std::string ToPrettyFormat (WriterFuncRef writer, const Request &statistics_request={})
 Output statistics in a human-readable, compact format, useful for visual inspection.
std::string ToPrettyFormat (const HasWriterSupport auto &metric, const Request &statistics_request={})
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
std::string ToPrometheusFormat (WriterFuncRef writer, const Request &request={})
 Output statistics in Prometheus format, each metric has gauge type.
std::string ToPrometheusFormat (const HasWriterSupport auto &metric, const Request &request={})
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
std::string ToPrometheusFormatUntyped (WriterFuncRef writer, const Request &request={})
 Output statistics in Prometheus format, without metric types.
std::string ToPrometheusFormatUntyped (const HasWriterSupport auto &metric, const Request &request={})
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Rate operator+ (Rate first, Rate second) noexcept
void DumpMetric (Writer &writer, const RateCounter &value)
void ResetMetric (RateCounter &value)
template<typename Counter, typename Result, typename Timer>
void DumpMetric (Writer &writer, const RecentPeriod< Counter, Result, Timer > &recent_period)
 Exports the full configured window of utils::statistics::RecentPeriod, excluding the current epoch. Use utils::statistics::RecentPeriod::GetStatsForPeriod explicitly when a different window or inclusion of the current epoch is required.
template<typename Counter, typename Result, typename Timer>
void ResetMetric (RecentPeriod< Counter, Result, Timer > &recent_period)
 Reset support for RecentPeriod.
template<typename T>
void DumpMetric (Writer &writer, const RelaxedCounter< T > &value)
template<typename T>
void ResetMetric (RelaxedCounter< T > &value)
std::string ToSolomonFormat (WriterFuncRef writer, const std::unordered_map< std::string, std::string > &common_labels, const Request &statistics_request={})
std::string ToSolomonFormat (const HasWriterSupport auto &metric, const std::unordered_map< std::string, std::string > &common_labels, const Request &statistics_request={})
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void VisitMetrics (WriterFuncRef func, BaseFormatBuilder &out, const Request &request={})
 Low-level connecting function that dumps metrics from func into out.
void VisitMetrics (const HasWriterSupport auto &metric, BaseFormatBuilder &out, const Request &request={})
template<class Metric>
void DumpMetric (Writer &writer, const std::atomic< Metric > &m)
void DumpMetric (Writer &writer, const MetricView &metric)
 Writes metric through writer.
void PrintTo (const Snapshot &data, std::ostream *)
 Support for gtest diagnostics for utils::statistics::Snapshot.
void PrintTo (MetricValue value, std::ostream *)
 Support for gtest diagnostics for utils::statistics::MetricValue.
void PrintTo (Rate value, std::ostream *)
 Support for gtest diagnostics for utils::statistics::Rate.
::testing::Matcher< Snapshot > EqualsNumerically (const Snapshot &expected)
 GTest matcher for utils::statistics::Snapshot::EqualsNumerically.
void RegisterWriterScope (const components::ComponentContext &, std::string common_prefix, WriterFunc func, std::vector< Label > add_labels={})
 Registers a writer in the default components::StatisticsStorage. Call this helper in the component constructor. Registration is deferred until the complete component, including derived classes, has been constructed. The callback is unregistered before the component destructor starts. The callback may run concurrently with other code and must be thread-safe.
MetricsStoragePtr MakeBoundMetricsStorage (Storage &storage, const std::optional< std::vector< std::string > > &allowed_metric_paths)
 Creates a MetricsStorage that considers only MetricTag<Metric> instances whose paths are listed in allowed_metric_paths (or all of them, if it is std::nullopt), and registers it in storage using the scoped utils::statistics::Storage::RegisterWriter overload, with an empty prefix.
void DumpMetric (Writer &writer, const Storage &storage)
 Dumps metrics registered in storage.
void DumpMetric (Writer &writer, const StripedRateCounter &value)
void ResetMetric (StripedRateCounter &value)

Variables

constexpr auto kDefaultMaxPeriod = std::chrono::seconds(60)
constexpr auto kDefaultEpochDuration = std::chrono::seconds(5)

Typedef Documentation

◆ MetricsStoragePtr

typedef std::shared_ptr< MetricsStorage > utils::statistics::MetricsStoragePtr = std::shared_ptr<MetricsStorage>

Definition at line 26 of file fwd.hpp.

◆ PortabilityWarnings

using utils::statistics::PortabilityWarnings = std::unordered_map<WarningCode, std::vector<Warning>>

Definition at line 54 of file portability_info.hpp.

◆ WriterFunc

using utils::statistics::WriterFunc = std::function<void(Writer&)>

Definition at line 20 of file storage.hpp.

◆ WriterFuncRef

typedef utils::function_ref< void(Writer &) const > utils::statistics::WriterFuncRef = utils::function_ref<void(Writer&) const>

Non-owning reference to a function that writes metrics via utils::statistics::Writer.

Definition at line 16 of file visit.hpp.

Enumeration Type Documentation

◆ WarningCode

enum class utils::statistics::WarningCode
strong

Definition at line 31 of file portability_info.hpp.

Function Documentation

◆ DumpMetric() [1/5]

template<typename ValueType, typename AverageType>
void utils::statistics::DumpMetric ( Writer & writer,
const MinMaxAvg< ValueType, AverageType > & value )

Definition at line 152 of file min_max_avg.hpp.

◆ DumpMetric() [2/5]

template<size_t M, typename Counter, size_t ExtraBuckets, size_t ExtraBucketSize>
void utils::statistics::DumpMetric ( Writer & writer,
const Percentile< M, Counter, ExtraBuckets, ExtraBucketSize > & perc,
std::initializer_list< double > percents = {0, 50, 90, 95, 98, 99, 99.6, 99.9, 100} )

Definition at line 217 of file percentile.hpp.

◆ DumpMetric() [3/5]

template<typename Counter, typename Result, typename Timer>
void utils::statistics::DumpMetric ( Writer & writer,
const RecentPeriod< Counter, Result, Timer > & recent_period )

Exports the full configured window of utils::statistics::RecentPeriod, excluding the current epoch. Use utils::statistics::RecentPeriod::GetStatsForPeriod explicitly when a different window or inclusion of the current epoch is required.

Definition at line 191 of file recentperiod.hpp.

◆ DumpMetric() [4/5]

template<typename T>
void utils::statistics::DumpMetric ( Writer & writer,
const RelaxedCounter< T > & value )

Definition at line 79 of file relaxed_counter.hpp.

◆ DumpMetric() [5/5]

template<class Metric>
void utils::statistics::DumpMetric ( Writer & writer,
const std::atomic< Metric > & m )

Definition at line 226 of file writer.hpp.

◆ EqualsNumerically()

::testing::Matcher< Snapshot > utils::statistics::EqualsNumerically ( const Snapshot & expected)

GTest matcher for utils::statistics::Snapshot::EqualsNumerically.

namespace {
struct DbMetrics {
utils::statistics::RateCounter queries;
};
struct HandlerMetrics {
utils::statistics::RateCounter requests;
double duration_seconds{0};
};
struct ServiceMetrics {
HandlerMetrics handler;
DbMetrics db;
};
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const DbMetrics& metrics) {
writer["queries"].ValueWithLabels(metrics.queries, {"query", "select_order"});
}
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const HandlerMetrics& metrics) {
writer["requests"].ValueWithLabels(metrics.requests, {"http_code", "200"});
writer["duration_seconds"] = metrics.duration_seconds;
}
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const ServiceMetrics& metrics) {
writer["handler"] = metrics.handler;
writer["db"] = metrics.db;
}
} // namespace
TEST(Snapshot, NestedMetricsMatchLayeredReference) {
ServiceMetrics metrics;
metrics.handler.requests = utils::statistics::Rate{120};
metrics.handler.duration_seconds = 1.5;
metrics.db.queries = utils::statistics::Rate{3};
const utils::statistics::Snapshot snapshot{metrics};
"handler.requests": {"http_code = 200": 120},
"handler.duration_seconds": 1.5,
"db.queries": {"query = select_order": 3}
})"));
EXPECT_THAT(snapshot, EqualsNumerically(reference));
}

◆ GetPortabilityWarnings() [1/2]

PortabilityWarnings utils::statistics::GetPortabilityWarnings ( const HasWriterSupport auto & metric,
const Request & request )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 86 of file portability_info.hpp.

◆ GetPortabilityWarnings() [2/2]

PortabilityWarnings utils::statistics::GetPortabilityWarnings ( WriterFuncRef writer,
const Request & request )

Output portability info for statistics.

See also
Functional service tests (testsuite)

◆ MakeBoundMetricsStorage()

MetricsStoragePtr utils::statistics::MakeBoundMetricsStorage ( Storage & storage,
const std::optional< std::vector< std::string > > & allowed_metric_paths )

Creates a MetricsStorage that considers only MetricTag<Metric> instances whose paths are listed in allowed_metric_paths (or all of them, if it is std::nullopt), and registers it in storage using the scoped utils::statistics::Storage::RegisterWriter overload, with an empty prefix.

The returned pointer is an aliasing shared_ptr: it keeps alive an internal holder that unregisters the writer when the last pointer is destroyed. The storage must outlive the returned pointer (and all its copies).

◆ operator+()

Rate utils::statistics::operator+ ( Rate first,
Rate second )
inlinenoexcept

Definition at line 58 of file rate.hpp.

◆ operator==()

bool utils::statistics::operator== ( HistogramView lhs,
HistogramView rhs )
noexcept

Compares equal if bounds are close and values are equal. Bucket sums are ignored.

◆ PrintTo()

void utils::statistics::PrintTo ( const Snapshot & data,
std::ostream *  )

Support for gtest diagnostics for utils::statistics::Snapshot.

Warning
Never check the printed value programmatically! The string is not stable and may change, depending on the version of stdlib and userver.

Valid usage:

EXPECT_EQ(..., ...) << testing::PrintToString(snapshot);

Invalid usage:

std::ostringstream stream;
PrintTo(snapshot, &stream);
EXPECT_EQ(stream.str(), ...);

◆ RegisterWriterScope()

void utils::statistics::RegisterWriterScope ( const components::ComponentContext & ,
std::string common_prefix,
WriterFunc func,
std::vector< Label > add_labels = {} )

Registers a writer in the default components::StatisticsStorage. Call this helper in the component constructor. Registration is deferred until the complete component, including derived classes, has been constructed. The callback is unregistered before the component destructor starts. The callback may run concurrently with other code and must be thread-safe.

Uses components::ComponentContext::Scopes for the component automatically. See choosing scopes for the lifetime rules.

See also
utils::statistics::Storage::RegisterWriter

◆ ResetMetric() [1/2]

template<typename Counter, typename Result, typename Timer>
void utils::statistics::ResetMetric ( RecentPeriod< Counter, Result, Timer > & recent_period)

Reset support for RecentPeriod.

Definition at line 197 of file recentperiod.hpp.

◆ ResetMetric() [2/2]

template<typename T>
void utils::statistics::ResetMetric ( RelaxedCounter< T > & value)

Definition at line 84 of file relaxed_counter.hpp.

◆ Serialize() [1/2]

template<typename ValueType, typename AverageType>
auto utils::statistics::Serialize ( const MinMaxAvg< ValueType, AverageType > & mma,
formats::serialize::To< formats::json::Value >  )

Definition at line 146 of file min_max_avg.hpp.

◆ Serialize() [2/2]

formats::json::Value utils::statistics::Serialize ( const PortabilityWarnings & info,
formats::serialize::To< formats::json::Value >  )

JSON serialization for the PortabilityInfo in the following format:

{
"warning_code": [
{
"error_message": "Human readable message",
"path": "foo-bar",
"labels": {
"some-label": "label-value",
"some-other-label": "other-label-value",
}
}
],
"another_error_id": [
{
"path": "foo.bar",
"labels": {
"another-label": "another-value"
}
},
]
}

◆ ToGraphiteFormat()

std::string utils::statistics::ToGraphiteFormat ( const HasWriterSupport auto & metric,
const Request & statistics_request = {} )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 20 of file graphite.hpp.

◆ ToJsonFormat() [1/2]

std::string utils::statistics::ToJsonFormat ( const HasWriterSupport auto & metric,
const Request & statistics_request = {} )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 46 of file json.hpp.

◆ ToJsonFormat() [2/2]

std::string utils::statistics::ToJsonFormat ( WriterFuncRef writer,
const Request & statistics_request = {} )

Output statistics in JSON format:

{
"metric-path": [
{
"type": "GAUGE",
"value": 42,
"labels": {
"some-label": "label-value",
"some-other-label": "other-label-value",
}
},
{
"type": "RATE",
"value": 43,
"labels": {
"another-label": "another-value"
}
},
]
}
Note
An integer GAUGE and a floating-point GAUGE are both written as a JSON number of the same type. In practice they cannot be told apart.
A histogram writes only utils::statistics::HistogramView::GetTotalSum into sum. Sums of individual buckets are not written.

◆ ToPrettyFormat() [1/2]

std::string utils::statistics::ToPrettyFormat ( const HasWriterSupport auto & metric,
const Request & statistics_request = {} )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 29 of file pretty_format.hpp.

◆ ToPrettyFormat() [2/2]

std::string utils::statistics::ToPrettyFormat ( WriterFuncRef writer,
const Request & statistics_request = {} )

Output statistics in a human-readable, compact format, useful for visual inspection.

Warning
This format is unstable, we reserve the right to change it at any point. Don't use it in scripts, use utils::statistics::ToJsonFormat instead!

The current version of this unstable format is:

metric-path: some-label=label-value, other-label=other-label-value\tRATE\t42

◆ ToPrometheusFormat()

std::string utils::statistics::ToPrometheusFormat ( const HasWriterSupport auto & metric,
const Request & request = {} )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 36 of file prometheus.hpp.

◆ ToPrometheusFormatUntyped()

std::string utils::statistics::ToPrometheusFormatUntyped ( const HasWriterSupport auto & metric,
const Request & request = {} )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 44 of file prometheus.hpp.

◆ ToSolomonFormat() [1/2]

std::string utils::statistics::ToSolomonFormat ( const HasWriterSupport auto & metric,
const std::unordered_map< std::string, std::string > & common_labels,
const Request & statistics_request = {} )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 69 of file solomon.hpp.

◆ ToSolomonFormat() [2/2]

std::string utils::statistics::ToSolomonFormat ( WriterFuncRef writer,
const std::unordered_map< std::string, std::string > & common_labels,
const Request & statistics_request = {} )

Output statistics in Solomon format with tags (labels). It's JSON format in the form

{
"commonLabels": {
"application": "some-service-name"
},
"metrics": [
{
"labels": {
"sensor": "cpu_time_sec"
},
"value": 34155.69
},
{
"labels": {
"sensor": "postgresql.replication-lag.min",
"postgresql_database": "some_pg_db",
"postgresql_database_shard": "shard_0",
"postgresql_cluster_host_type": "slaves",
"postgresql_instance": "some_host:6432"
},
"value": 0
},
{
"labels": {
"sensor": "http.handler.in-flight",
"http_path": "/ping",
"http_handler": "handler-ping"
},
"value": 1
},
{
"labels": {
"sensor": "cache.full.time.last-update-duration-ms",
"cache_name": "some-cache-name"
},
"value": 23
}
]
}

◆ VisitMetrics() [1/2]

void utils::statistics::VisitMetrics ( const HasWriterSupport auto & metric,
BaseFormatBuilder & out,
const Request & request = {} )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Dumps metric via writer = metric (DumpMetric / built-in Writer support).

Definition at line 47 of file visit.hpp.

◆ VisitMetrics() [2/2]

void utils::statistics::VisitMetrics ( WriterFuncRef func,
BaseFormatBuilder & out,
const Request & request = {} )

Low-level connecting function that dumps metrics from func into out.

Calls func with a utils::statistics::Writer. Each metric written through that Writer is forwarded to out.HandleMetric. request filters the metrics and may attach extra labels; request.prefix is a match filter, not a path to write under.

This function dumps Writer-based metrics. It is used to implement formats such as:

To define a custom output format, implement utils::statistics::BaseFormatBuilder:

class MetricsMessageBuilder final : public utils::statistics::BaseFormatBuilder {
public:
void HandleMetric(
std::string_view path,
utils::statistics::LabelsSpan labels,
const utils::statistics::MetricValue& value
) override {
fmt::format_to(std::back_inserter(message_), "{}\t{}\t{}\n", path, labels, value);
}
const std::string& GetMessage() const { return message_; }
private:
std::string message_;
};

Collect metrics using the custom format builder:

MetricsMessageBuilder builder;
writer["requests"] = requests;
writer["errors"].ValueWithLabels(errors, {"kind", "timeout"});
},
builder
);
EXPECT_EQ(builder.GetMessage(), "requests\t\t10\nerrors\tkind=timeout\t2\n");
Parameters
funcwrites metrics to the provided utils::statistics::Writer
outreceives each written metric via utils::statistics::BaseFormatBuilder::HandleMetric
requestmetric filter and extra labels

Variable Documentation

◆ kDefaultEpochDuration

auto utils::statistics::kDefaultEpochDuration = std::chrono::seconds(5)
constexpr

Definition at line 17 of file common.hpp.

◆ kDefaultMaxPeriod

auto utils::statistics::kDefaultMaxPeriod = std::chrono::seconds(60)
constexpr

Definition at line 15 of file common.hpp.