prometheus_decoder.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. #include "prometheus.h"
  2. #include "prometheus_model.h"
  3. #include <library/cpp/monlib/metrics/histogram_snapshot.h>
  4. #include <library/cpp/monlib/metrics/metric.h>
  5. #include <util/datetime/base.h>
  6. #include <util/generic/hash.h>
  7. #include <util/string/cast.h>
  8. #include <util/string/builder.h>
  9. #include <util/generic/maybe.h>
  10. #include <util/string/ascii.h>
  11. #include <cmath>
  12. #define Y_PARSER_FAIL(message) \
  13. ythrow ::NMonitoring::TPrometheusDecodeException() << message << " at line #" << CurrentLine_
  14. #define Y_PARSER_ENSURE(cond, message) \
  15. Y_ENSURE_EX(cond, ::NMonitoring::TPrometheusDecodeException() << message << " at line #" << CurrentLine_)
  16. namespace NMonitoring {
  17. namespace {
  18. constexpr ui32 MAX_LABEL_VALUE_LEN = 256;
  19. using TLabelsMap = THashMap<TString, TString>;
  20. TString LabelsToStr(const TLabelsMap& labels) {
  21. TStringBuilder sb;
  22. auto it = labels.begin();
  23. auto end = labels.end();
  24. sb << '{';
  25. while (it != end) {
  26. sb << it->first;
  27. sb << '=';
  28. sb << '"' << it->second << '"';
  29. ++it;
  30. if (it != end) {
  31. sb << ", ";
  32. }
  33. }
  34. sb << '}';
  35. return sb;
  36. }
  37. template <typename T, typename U>
  38. bool TryStaticCast(U val, T& out) {
  39. static_assert(std::is_arithmetic_v<U>);
  40. if constexpr (std::is_floating_point_v<T> || std::is_floating_point_v<U>) {
  41. if (val > MaxFloor<T>() || val < -MaxFloor<T>()) {
  42. return false;
  43. }
  44. } else {
  45. if (val > Max<T>() || val < Min<T>()) {
  46. return false;
  47. }
  48. }
  49. out = static_cast<T>(val);
  50. return true;
  51. }
  52. ///////////////////////////////////////////////////////////////////////
  53. // THistogramBuilder
  54. ///////////////////////////////////////////////////////////////////////
  55. class THistogramBuilder {
  56. using TBucketData = std::pair<TBucketBound, TBucketValue>;
  57. constexpr static TBucketData ZERO_BUCKET = { -std::numeric_limits<TBucketBound>::max(), 0 };
  58. public:
  59. TStringBuf GetName() const noexcept {
  60. return Name_;
  61. }
  62. void SetName(TStringBuf name) noexcept {
  63. Name_ = name;
  64. }
  65. const TLabelsMap& GetLabels() const noexcept {
  66. return *Labels_;
  67. }
  68. void SetLabels(TLabelsMap&& labels) {
  69. if (Labels_.Defined()) {
  70. Y_ENSURE(Labels_ == labels,
  71. "mixed labels in one histogram, prev: " << LabelsToStr(*Labels_) <<
  72. ", current: " << LabelsToStr(labels));
  73. } else {
  74. Labels_.ConstructInPlace(std::move(labels));
  75. }
  76. }
  77. TInstant GetTime() const noexcept {
  78. return Time_;
  79. }
  80. void SetTime(TInstant time) noexcept {
  81. Time_ = time;
  82. }
  83. bool Empty() const noexcept {
  84. return Bounds_.empty();
  85. }
  86. bool Same(TStringBuf name, const TLabelsMap& labels) const noexcept {
  87. return Name_ == name && Labels_ == labels;
  88. }
  89. void AddBucket(TBucketBound bound, TBucketValue value) {
  90. Y_ENSURE_EX(PrevBucket_.first < bound, TPrometheusDecodeException() <<
  91. "invalid order of histogram bounds " << PrevBucket_.first <<
  92. " >= " << bound);
  93. Y_ENSURE_EX(PrevBucket_.second <= value, TPrometheusDecodeException() <<
  94. "invalid order of histogram bucket values " << PrevBucket_.second <<
  95. " > " << value);
  96. // convert infinite bound value
  97. if (bound == std::numeric_limits<TBucketBound>::infinity()) {
  98. bound = HISTOGRAM_INF_BOUND;
  99. }
  100. Bounds_.push_back(bound);
  101. Values_.push_back(value - PrevBucket_.second); // keep only delta between buckets
  102. PrevBucket_ = { bound, value };
  103. }
  104. // will clear builder state
  105. IHistogramSnapshotPtr ToSnapshot() {
  106. Y_ENSURE_EX(!Empty(), TPrometheusDecodeException() << "histogram cannot be empty");
  107. Time_ = TInstant::Zero();
  108. PrevBucket_ = ZERO_BUCKET;
  109. Labels_.Clear();
  110. auto snapshot = ExplicitHistogramSnapshot(Bounds_, Values_);
  111. Bounds_.clear();
  112. Values_.clear();
  113. return snapshot;
  114. }
  115. private:
  116. TStringBuf Name_;
  117. TMaybe<TLabelsMap> Labels_;
  118. TInstant Time_;
  119. TBucketBounds Bounds_;
  120. TBucketValues Values_;
  121. TBucketData PrevBucket_ = ZERO_BUCKET;
  122. };
  123. ///////////////////////////////////////////////////////////////////////
  124. // EPrometheusMetricType
  125. ///////////////////////////////////////////////////////////////////////
  126. enum class EPrometheusMetricType {
  127. GAUGE,
  128. COUNTER,
  129. SUMMARY,
  130. UNTYPED,
  131. HISTOGRAM,
  132. };
  133. ///////////////////////////////////////////////////////////////////////
  134. // TPrometheusReader
  135. ///////////////////////////////////////////////////////////////////////
  136. class TPrometheusReader {
  137. public:
  138. TPrometheusReader(TStringBuf data, IMetricConsumer* c, TStringBuf metricNameLabel)
  139. : Data_(data)
  140. , Consumer_(c)
  141. , MetricNameLabel_(metricNameLabel)
  142. {
  143. }
  144. void Read() {
  145. Consumer_->OnStreamBegin();
  146. if (HasRemaining()) {
  147. ReadNextByte();
  148. SkipSpaces();
  149. try {
  150. while (HasRemaining()) {
  151. switch (CurrentByte_) {
  152. case '\n':
  153. ReadNextByte(); // skip '\n'
  154. CurrentLine_++;
  155. SkipSpaces();
  156. break;
  157. case '#':
  158. ParseComment();
  159. break;
  160. default:
  161. ParseMetric();
  162. break;
  163. }
  164. }
  165. if (!HistogramBuilder_.Empty()) {
  166. ConsumeHistogram();
  167. }
  168. } catch (const TPrometheusDecodeException& e) {
  169. throw e;
  170. } catch (...) {
  171. Y_PARSER_FAIL("unexpected error " << CurrentExceptionMessage());
  172. }
  173. }
  174. Consumer_->OnStreamEnd();
  175. }
  176. private:
  177. bool HasRemaining() const noexcept {
  178. return CurrentPos_ < Data_.Size();
  179. }
  180. // # 'TYPE' metric_name {counter|gauge|histogram|summary|untyped}
  181. // # 'HELP' metric_name some help info
  182. // # general comment message
  183. void ParseComment() {
  184. SkipExpectedChar('#');
  185. SkipSpaces();
  186. TStringBuf keyword = ReadToken();
  187. if (keyword == TStringBuf("TYPE")) {
  188. SkipSpaces();
  189. TStringBuf nextName = ReadTokenAsMetricName();
  190. Y_PARSER_ENSURE(!nextName.Empty(), "invalid metric name");
  191. SkipSpaces();
  192. EPrometheusMetricType nextType = ReadType();
  193. bool inserted = SeenTypes_.emplace(nextName, nextType).second;
  194. Y_PARSER_ENSURE(inserted, "second TYPE line for metric " << nextName);
  195. if (nextType == EPrometheusMetricType::HISTOGRAM) {
  196. if (!HistogramBuilder_.Empty()) {
  197. ConsumeHistogram();
  198. }
  199. HistogramBuilder_.SetName(nextName);
  200. }
  201. } else {
  202. // skip HELP and general comments
  203. SkipUntilEol();
  204. }
  205. Y_PARSER_ENSURE(CurrentByte_ == '\n', "expected '\\n', found '" << CurrentByte_ << '\'');
  206. }
  207. // metric_name [labels] value [timestamp]
  208. void ParseMetric() {
  209. TStringBuf name = ReadTokenAsMetricName();
  210. SkipSpaces();
  211. TLabelsMap labels = ReadLabels();
  212. SkipSpaces();
  213. double value = ParseGoDouble(ReadToken());
  214. SkipSpaces();
  215. TInstant time = TInstant::Zero();
  216. if (CurrentByte_ != '\n') {
  217. time = TInstant::MilliSeconds(FromString<ui64>(ReadToken()));
  218. }
  219. TStringBuf baseName = name;
  220. EPrometheusMetricType type = EPrometheusMetricType::UNTYPED;
  221. if (auto* seenType = SeenTypes_.FindPtr(name)) {
  222. type = *seenType;
  223. } else {
  224. baseName = NPrometheus::ToBaseName(name);
  225. if (auto* baseType = SeenTypes_.FindPtr(baseName)) {
  226. type = *baseType;
  227. }
  228. }
  229. switch (type) {
  230. case EPrometheusMetricType::HISTOGRAM:
  231. if (NPrometheus::IsBucket(name)) {
  232. double bound = 0.0;
  233. auto it = labels.find(NPrometheus::BUCKET_LABEL);
  234. if (it != labels.end()) {
  235. bound = ParseGoDouble(it->second);
  236. labels.erase(it);
  237. } else {
  238. Y_PARSER_FAIL(
  239. "metric " << name << "has no " << NPrometheus::BUCKET_LABEL <<
  240. " label at line #" << CurrentLine_);
  241. }
  242. if (!HistogramBuilder_.Empty() && !HistogramBuilder_.Same(baseName, labels)) {
  243. ConsumeHistogram();
  244. HistogramBuilder_.SetName(baseName);
  245. }
  246. TBucketValue bucketVal;
  247. Y_PARSER_ENSURE(TryStaticCast(value, bucketVal), "Cannot convert " << value << " to bucket value type");
  248. HistogramBuilder_.AddBucket(bound, bucketVal);
  249. HistogramBuilder_.SetTime(time);
  250. HistogramBuilder_.SetLabels(std::move(labels));
  251. } else if (NPrometheus::IsCount(name)) {
  252. // translate x_count metric as COUNTER metric
  253. ConsumeCounter(name, labels, time, value);
  254. } else if (NPrometheus::IsSum(name)) {
  255. // translate x_sum metric as GAUGE metric
  256. ConsumeGauge(name, labels, time, value);
  257. } else {
  258. Y_PARSER_FAIL(
  259. "metric " << name <<
  260. " should be part of HISTOGRAM " << baseName);
  261. }
  262. break;
  263. case EPrometheusMetricType::SUMMARY:
  264. if (NPrometheus::IsCount(name)) {
  265. // translate x_count metric as COUNTER metric
  266. ConsumeCounter(name, labels, time, value);
  267. } else if (NPrometheus::IsSum(name)) {
  268. // translate x_sum metric as GAUGE metric
  269. ConsumeGauge(name, labels, time, value);
  270. } else {
  271. ConsumeGauge(name, labels, time, value);
  272. }
  273. break;
  274. case EPrometheusMetricType::COUNTER:
  275. ConsumeCounter(name, labels, time, value);
  276. break;
  277. case EPrometheusMetricType::GAUGE:
  278. ConsumeGauge(name, labels, time, value);
  279. break;
  280. case EPrometheusMetricType::UNTYPED:
  281. ConsumeGauge(name, labels, time, value);
  282. break;
  283. }
  284. Y_PARSER_ENSURE(CurrentByte_ == '\n', "expected '\\n', found '" << CurrentByte_ << '\'');
  285. }
  286. // { name = "value", name2 = "value2", }
  287. TLabelsMap ReadLabels() {
  288. TLabelsMap labels;
  289. if (CurrentByte_ != '{') {
  290. return labels;
  291. }
  292. SkipExpectedChar('{');
  293. SkipSpaces();
  294. while (CurrentByte_ != '}') {
  295. TStringBuf name = ReadTokenAsLabelName();
  296. SkipSpaces();
  297. SkipExpectedChar('=');
  298. SkipSpaces();
  299. TString value = ReadTokenAsLabelValue();
  300. SkipSpaces();
  301. labels.emplace(name, value);
  302. if (CurrentByte_ == ',') {
  303. SkipExpectedChar(',');
  304. SkipSpaces();
  305. }
  306. }
  307. SkipExpectedChar('}');
  308. return labels;
  309. }
  310. EPrometheusMetricType ReadType() {
  311. TStringBuf keyword = ReadToken();
  312. if (AsciiEqualsIgnoreCase(keyword, "GAUGE")) {
  313. return EPrometheusMetricType::GAUGE;
  314. } else if (AsciiEqualsIgnoreCase(keyword, "COUNTER")) {
  315. return EPrometheusMetricType::COUNTER;
  316. } else if (AsciiEqualsIgnoreCase(keyword, "SUMMARY")) {
  317. return EPrometheusMetricType::SUMMARY;
  318. } else if (AsciiEqualsIgnoreCase(keyword, "HISTOGRAM")) {
  319. return EPrometheusMetricType::HISTOGRAM;
  320. } else if (AsciiEqualsIgnoreCase(keyword, "UNTYPED")) {
  321. return EPrometheusMetricType::UNTYPED;
  322. }
  323. Y_PARSER_FAIL(
  324. "unknown metric type: " << keyword <<
  325. " at line #" << CurrentLine_);
  326. }
  327. Y_FORCE_INLINE void ReadNextByteUnsafe() {
  328. CurrentByte_ = Data_[CurrentPos_++];
  329. }
  330. Y_FORCE_INLINE bool IsSpace(char ch) {
  331. return ch == ' ' || ch == '\t';
  332. }
  333. void ReadNextByte() {
  334. Y_PARSER_ENSURE(HasRemaining(), "unexpected end of file");
  335. ReadNextByteUnsafe();
  336. }
  337. void SkipExpectedChar(char ch) {
  338. Y_PARSER_ENSURE(CurrentByte_ == ch,
  339. "expected '" << CurrentByte_ << "', found '" << ch << '\'');
  340. ReadNextByte();
  341. }
  342. void SkipSpaces() {
  343. while (HasRemaining() && IsSpace(CurrentByte_)) {
  344. ReadNextByteUnsafe();
  345. }
  346. }
  347. void SkipUntilEol() {
  348. while (HasRemaining() && CurrentByte_ != '\n') {
  349. ReadNextByteUnsafe();
  350. }
  351. }
  352. TStringBuf ReadToken() {
  353. Y_VERIFY_DEBUG(CurrentPos_ > 0);
  354. size_t begin = CurrentPos_ - 1; // read first byte again
  355. while (HasRemaining() && !IsSpace(CurrentByte_) && CurrentByte_ != '\n') {
  356. ReadNextByteUnsafe();
  357. }
  358. return TokenFromPos(begin);
  359. }
  360. TStringBuf ReadTokenAsMetricName() {
  361. if (!NPrometheus::IsValidMetricNameStart(CurrentByte_)) {
  362. return "";
  363. }
  364. Y_VERIFY_DEBUG(CurrentPos_ > 0);
  365. size_t begin = CurrentPos_ - 1; // read first byte again
  366. while (HasRemaining()) {
  367. ReadNextByteUnsafe();
  368. if (!NPrometheus::IsValidMetricNameContinuation(CurrentByte_)) {
  369. break;
  370. }
  371. }
  372. return TokenFromPos(begin);
  373. }
  374. TStringBuf ReadTokenAsLabelName() {
  375. if (!NPrometheus::IsValidLabelNameStart(CurrentByte_)) {
  376. return "";
  377. }
  378. Y_VERIFY_DEBUG(CurrentPos_ > 0);
  379. size_t begin = CurrentPos_ - 1; // read first byte again
  380. while (HasRemaining()) {
  381. ReadNextByteUnsafe();
  382. if (!NPrometheus::IsValidLabelNameContinuation(CurrentByte_)) {
  383. break;
  384. }
  385. }
  386. return TokenFromPos(begin);
  387. }
  388. TString ReadTokenAsLabelValue() {
  389. TString labelValue;
  390. SkipExpectedChar('"');
  391. for (ui32 i = 0; i < MAX_LABEL_VALUE_LEN; i++) {
  392. switch (CurrentByte_) {
  393. case '"':
  394. SkipExpectedChar('"');
  395. return labelValue;
  396. case '\n':
  397. Y_PARSER_FAIL("label value contains unescaped new-line");
  398. case '\\':
  399. ReadNextByte();
  400. switch (CurrentByte_) {
  401. case '"':
  402. case '\\':
  403. labelValue.append(CurrentByte_);
  404. break;
  405. case 'n':
  406. labelValue.append('\n');
  407. break;
  408. default:
  409. Y_PARSER_FAIL("invalid escape sequence '" << CurrentByte_ << '\'');
  410. }
  411. break;
  412. default:
  413. labelValue.append(CurrentByte_);
  414. break;
  415. }
  416. ReadNextByte();
  417. }
  418. Y_PARSER_FAIL("trying to parse too long label value, size >= " << MAX_LABEL_VALUE_LEN);
  419. }
  420. TStringBuf TokenFromPos(size_t begin) {
  421. Y_VERIFY_DEBUG(CurrentPos_ > begin);
  422. size_t len = CurrentPos_ - begin - 1;
  423. if (len == 0) {
  424. return {};
  425. }
  426. return Data_.SubString(begin, len);
  427. }
  428. void ConsumeLabels(TStringBuf name, const TLabelsMap& labels) {
  429. Y_PARSER_ENSURE(labels.count(MetricNameLabel_) == 0,
  430. "label name '" << MetricNameLabel_ <<
  431. "' is reserved, but is used with metric: " << name << LabelsToStr(labels));
  432. Consumer_->OnLabelsBegin();
  433. Consumer_->OnLabel(MetricNameLabel_, TString(name)); // TODO: remove this string allocation
  434. for (const auto& it: labels) {
  435. Consumer_->OnLabel(it.first, it.second);
  436. }
  437. Consumer_->OnLabelsEnd();
  438. }
  439. void ConsumeCounter(TStringBuf name, const TLabelsMap& labels, TInstant time, double value) {
  440. i64 intValue{0};
  441. // not nan
  442. if (value == value) {
  443. Y_PARSER_ENSURE(TryStaticCast(value, intValue), "value " << value << " is out of range");
  444. }
  445. // see https://st.yandex-team.ru/SOLOMON-4142 for more details
  446. // why we convert Prometheus COUNTER into Solomon RATE
  447. // TODO: need to fix after server-side aggregation become correct for COUNTERs
  448. Consumer_->OnMetricBegin(EMetricType::RATE);
  449. ConsumeLabels(name, labels);
  450. Consumer_->OnUint64(time, intValue);
  451. Consumer_->OnMetricEnd();
  452. }
  453. void ConsumeGauge(TStringBuf name, const TLabelsMap& labels, TInstant time, double value) {
  454. Consumer_->OnMetricBegin(EMetricType::GAUGE);
  455. ConsumeLabels(name, labels);
  456. Consumer_->OnDouble(time, value);
  457. Consumer_->OnMetricEnd();
  458. }
  459. void ConsumeHistogram() {
  460. Consumer_->OnMetricBegin(EMetricType::HIST_RATE);
  461. ConsumeLabels(HistogramBuilder_.GetName(), HistogramBuilder_.GetLabels());
  462. auto time = HistogramBuilder_.GetTime();
  463. auto hist = HistogramBuilder_.ToSnapshot();
  464. Consumer_->OnHistogram(time, std::move(hist));
  465. Consumer_->OnMetricEnd();
  466. }
  467. double ParseGoDouble(TStringBuf str) {
  468. if (str == TStringBuf("+Inf")) {
  469. return std::numeric_limits<double>::infinity();
  470. } else if (str == TStringBuf("-Inf")) {
  471. return -std::numeric_limits<double>::infinity();
  472. } else if (str == TStringBuf("NaN")) {
  473. return NAN;
  474. }
  475. double r = 0.0;
  476. if (TryFromString(str, r)) {
  477. return r;
  478. }
  479. Y_PARSER_FAIL("cannot parse double value from '" << str << "\' at line #" << CurrentLine_);
  480. }
  481. private:
  482. TStringBuf Data_;
  483. IMetricConsumer* Consumer_;
  484. TStringBuf MetricNameLabel_;
  485. THashMap<TString, EPrometheusMetricType> SeenTypes_;
  486. THistogramBuilder HistogramBuilder_;
  487. ui32 CurrentLine_ = 1;
  488. ui32 CurrentPos_ = 0;
  489. char CurrentByte_ = 0;
  490. };
  491. } // namespace
  492. void DecodePrometheus(TStringBuf data, IMetricConsumer* c, TStringBuf metricNameLabel) {
  493. TPrometheusReader reader(data, c, metricNameLabel);
  494. reader.Read();
  495. }
  496. } // namespace NMonitoring