prometheus_decoder.cpp 23 KB

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