prometheus_decoder.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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_, true);
  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. auto emplaceResult = SeenTypes_.emplace(nextName, nextType);
  194. if (!emplaceResult.second) {
  195. Y_PARSER_ENSURE(emplaceResult.first->second == nextType, "second diferent TYPE for metric " << nextName);
  196. }
  197. if (nextType == EPrometheusMetricType::HISTOGRAM) {
  198. if (!HistogramBuilder_.Empty()) {
  199. ConsumeHistogram();
  200. }
  201. HistogramBuilder_.SetName(nextName);
  202. }
  203. } else {
  204. // skip HELP and general comments
  205. SkipUntilEol();
  206. }
  207. Y_PARSER_ENSURE(CurrentByte_ == '\n', "expected '\\n', found '" << CurrentByte_ << '\'');
  208. }
  209. // metric_name [labels] value [timestamp]
  210. void ParseMetric() {
  211. TStringBuf name = ReadTokenAsMetricName();
  212. SkipSpaces();
  213. TLabelsMap labels = ReadLabels();
  214. SkipSpaces();
  215. double value = ParseGoDouble(ReadToken());
  216. SkipSpaces();
  217. TInstant time = TInstant::Zero();
  218. if (CurrentByte_ != '\n') {
  219. time = TInstant::MilliSeconds(FromString<ui64>(ReadToken()));
  220. }
  221. TStringBuf baseName = name;
  222. EPrometheusMetricType type = EPrometheusMetricType::UNTYPED;
  223. if (auto* seenType = SeenTypes_.FindPtr(name)) {
  224. type = *seenType;
  225. } else {
  226. baseName = NPrometheus::ToBaseName(name);
  227. if (auto* baseType = SeenTypes_.FindPtr(baseName)) {
  228. type = *baseType;
  229. }
  230. }
  231. switch (type) {
  232. case EPrometheusMetricType::HISTOGRAM:
  233. if (NPrometheus::IsBucket(name)) {
  234. double bound = 0.0;
  235. auto it = labels.find(NPrometheus::BUCKET_LABEL);
  236. if (it != labels.end()) {
  237. bound = ParseGoDouble(it->second);
  238. labels.erase(it);
  239. } else {
  240. Y_PARSER_FAIL(
  241. "metric " << name << "has no " << NPrometheus::BUCKET_LABEL <<
  242. " label at line #" << CurrentLine_);
  243. }
  244. if (!HistogramBuilder_.Empty() && !HistogramBuilder_.Same(baseName, labels)) {
  245. ConsumeHistogram();
  246. HistogramBuilder_.SetName(baseName);
  247. }
  248. TBucketValue bucketVal;
  249. Y_PARSER_ENSURE(TryStaticCast(value, bucketVal), "Cannot convert " << value << " to bucket value type");
  250. HistogramBuilder_.AddBucket(bound, bucketVal);
  251. HistogramBuilder_.SetTime(time);
  252. HistogramBuilder_.SetLabels(std::move(labels));
  253. } else if (NPrometheus::IsCount(name)) {
  254. // translate x_count metric as COUNTER metric
  255. ConsumeCounter(name, labels, time, value);
  256. } else if (NPrometheus::IsSum(name)) {
  257. // translate x_sum metric as GAUGE metric
  258. ConsumeGauge(name, labels, time, value);
  259. } else {
  260. Y_PARSER_FAIL(
  261. "metric " << name <<
  262. " should be part of HISTOGRAM " << baseName);
  263. }
  264. break;
  265. case EPrometheusMetricType::SUMMARY:
  266. if (NPrometheus::IsCount(name)) {
  267. // translate x_count metric as COUNTER metric
  268. ConsumeCounter(name, labels, time, value);
  269. } else if (NPrometheus::IsSum(name)) {
  270. // translate x_sum metric as GAUGE metric
  271. ConsumeGauge(name, labels, time, value);
  272. } else {
  273. ConsumeGauge(name, labels, time, value);
  274. }
  275. break;
  276. case EPrometheusMetricType::COUNTER:
  277. ConsumeCounter(name, labels, time, value);
  278. break;
  279. case EPrometheusMetricType::GAUGE:
  280. ConsumeGauge(name, labels, time, value);
  281. break;
  282. case EPrometheusMetricType::UNTYPED:
  283. ConsumeGauge(name, labels, time, value);
  284. break;
  285. }
  286. Y_PARSER_ENSURE(CurrentByte_ == '\n', "expected '\\n', found '" << CurrentByte_ << '\'');
  287. }
  288. // { name = "value", name2 = "value2", }
  289. TLabelsMap ReadLabels() {
  290. TLabelsMap labels;
  291. if (CurrentByte_ != '{') {
  292. return labels;
  293. }
  294. SkipExpectedChar('{');
  295. SkipSpaces();
  296. while (CurrentByte_ != '}') {
  297. TStringBuf name = ReadTokenAsLabelName();
  298. SkipSpaces();
  299. SkipExpectedChar('=');
  300. SkipSpaces();
  301. TString value = ReadTokenAsLabelValue();
  302. SkipSpaces();
  303. labels.emplace(name, value);
  304. if (CurrentByte_ == ',') {
  305. SkipExpectedChar(',');
  306. SkipSpaces();
  307. }
  308. }
  309. SkipExpectedChar('}');
  310. return labels;
  311. }
  312. EPrometheusMetricType ReadType() {
  313. TStringBuf keyword = ReadToken();
  314. if (AsciiEqualsIgnoreCase(keyword, "GAUGE")) {
  315. return EPrometheusMetricType::GAUGE;
  316. } else if (AsciiEqualsIgnoreCase(keyword, "COUNTER")) {
  317. return EPrometheusMetricType::COUNTER;
  318. } else if (AsciiEqualsIgnoreCase(keyword, "SUMMARY")) {
  319. return EPrometheusMetricType::SUMMARY;
  320. } else if (AsciiEqualsIgnoreCase(keyword, "HISTOGRAM")) {
  321. return EPrometheusMetricType::HISTOGRAM;
  322. } else if (AsciiEqualsIgnoreCase(keyword, "UNTYPED")) {
  323. return EPrometheusMetricType::UNTYPED;
  324. }
  325. Y_PARSER_FAIL(
  326. "unknown metric type: " << keyword <<
  327. " at line #" << CurrentLine_);
  328. }
  329. Y_FORCE_INLINE void ReadNextByteUnsafe() {
  330. CurrentByte_ = Data_[CurrentPos_++];
  331. }
  332. Y_FORCE_INLINE bool IsSpace(char ch) {
  333. return ch == ' ' || ch == '\t';
  334. }
  335. void ReadNextByte() {
  336. Y_PARSER_ENSURE(HasRemaining(), "unexpected end of file");
  337. ReadNextByteUnsafe();
  338. }
  339. void SkipExpectedChar(char ch) {
  340. Y_PARSER_ENSURE(CurrentByte_ == ch,
  341. "expected '" << CurrentByte_ << "', found '" << ch << '\'');
  342. ReadNextByte();
  343. }
  344. void SkipSpaces() {
  345. while (HasRemaining() && IsSpace(CurrentByte_)) {
  346. ReadNextByteUnsafe();
  347. }
  348. }
  349. void SkipUntilEol() {
  350. while (HasRemaining() && CurrentByte_ != '\n') {
  351. ReadNextByteUnsafe();
  352. }
  353. }
  354. TStringBuf ReadToken() {
  355. Y_DEBUG_ABORT_UNLESS(CurrentPos_ > 0);
  356. size_t begin = CurrentPos_ - 1; // read first byte again
  357. while (HasRemaining() && !IsSpace(CurrentByte_) && CurrentByte_ != '\n') {
  358. ReadNextByteUnsafe();
  359. }
  360. return TokenFromPos(begin);
  361. }
  362. TStringBuf ReadTokenAsMetricName() {
  363. if (!NPrometheus::IsValidMetricNameStart(CurrentByte_)) {
  364. return "";
  365. }
  366. Y_DEBUG_ABORT_UNLESS(CurrentPos_ > 0);
  367. size_t begin = CurrentPos_ - 1; // read first byte again
  368. while (HasRemaining()) {
  369. ReadNextByteUnsafe();
  370. if (!NPrometheus::IsValidMetricNameContinuation(CurrentByte_)) {
  371. break;
  372. }
  373. }
  374. return TokenFromPos(begin);
  375. }
  376. TStringBuf ReadTokenAsLabelName() {
  377. if (!NPrometheus::IsValidLabelNameStart(CurrentByte_)) {
  378. return "";
  379. }
  380. Y_DEBUG_ABORT_UNLESS(CurrentPos_ > 0);
  381. size_t begin = CurrentPos_ - 1; // read first byte again
  382. while (HasRemaining()) {
  383. ReadNextByteUnsafe();
  384. if (!NPrometheus::IsValidLabelNameContinuation(CurrentByte_)) {
  385. break;
  386. }
  387. }
  388. return TokenFromPos(begin);
  389. }
  390. TString ReadTokenAsLabelValue() {
  391. TString labelValue;
  392. SkipExpectedChar('"');
  393. for (ui32 i = 0; i < MAX_LABEL_VALUE_LEN; i++) {
  394. switch (CurrentByte_) {
  395. case '"':
  396. SkipExpectedChar('"');
  397. return labelValue;
  398. case '\n':
  399. Y_PARSER_FAIL("label value contains unescaped new-line");
  400. case '\\':
  401. ReadNextByte();
  402. switch (CurrentByte_) {
  403. case '"':
  404. case '\\':
  405. labelValue.append(CurrentByte_);
  406. break;
  407. case 'n':
  408. labelValue.append('\n');
  409. break;
  410. default:
  411. Y_PARSER_FAIL("invalid escape sequence '" << CurrentByte_ << '\'');
  412. }
  413. break;
  414. default:
  415. labelValue.append(CurrentByte_);
  416. break;
  417. }
  418. ReadNextByte();
  419. }
  420. Y_PARSER_FAIL("trying to parse too long label value, size >= " << MAX_LABEL_VALUE_LEN);
  421. }
  422. TStringBuf TokenFromPos(size_t begin) {
  423. Y_DEBUG_ABORT_UNLESS(CurrentPos_ > begin);
  424. size_t len = CurrentPos_ - begin - 1;
  425. if (len == 0) {
  426. return {};
  427. }
  428. return Data_.SubString(begin, len);
  429. }
  430. void ConsumeLabels(TStringBuf name, const TLabelsMap& labels) {
  431. Y_PARSER_ENSURE(labels.count(MetricNameLabel_) == 0,
  432. "label name '" << MetricNameLabel_ <<
  433. "' is reserved, but is used with metric: " << name << LabelsToStr(labels));
  434. Consumer_->OnLabelsBegin();
  435. Consumer_->OnLabel(MetricNameLabel_, TString(name)); // TODO: remove this string allocation
  436. for (const auto& it: labels) {
  437. Consumer_->OnLabel(it.first, it.second);
  438. }
  439. Consumer_->OnLabelsEnd();
  440. }
  441. void ConsumeCounter(TStringBuf name, const TLabelsMap& labels, TInstant time, double value) {
  442. i64 intValue{0};
  443. // not nan
  444. if (value == value) {
  445. Y_PARSER_ENSURE(TryStaticCast(value, intValue), "value " << value << " is out of range");
  446. }
  447. // see https://st.yandex-team.ru/SOLOMON-4142 for more details
  448. // why we convert Prometheus COUNTER into Solomon RATE
  449. // TODO: need to fix after server-side aggregation become correct for COUNTERs
  450. Consumer_->OnMetricBegin(EMetricType::RATE);
  451. ConsumeLabels(name, labels);
  452. Consumer_->OnUint64(time, intValue);
  453. Consumer_->OnMetricEnd();
  454. }
  455. void ConsumeGauge(TStringBuf name, const TLabelsMap& labels, TInstant time, double value) {
  456. Consumer_->OnMetricBegin(EMetricType::GAUGE);
  457. ConsumeLabels(name, labels);
  458. Consumer_->OnDouble(time, value);
  459. Consumer_->OnMetricEnd();
  460. }
  461. void ConsumeHistogram() {
  462. Consumer_->OnMetricBegin(EMetricType::HIST_RATE);
  463. ConsumeLabels(HistogramBuilder_.GetName(), HistogramBuilder_.GetLabels());
  464. auto time = HistogramBuilder_.GetTime();
  465. auto hist = HistogramBuilder_.ToSnapshot();
  466. Consumer_->OnHistogram(time, std::move(hist));
  467. Consumer_->OnMetricEnd();
  468. }
  469. double ParseGoDouble(TStringBuf str) {
  470. if (str == TStringBuf("+Inf")) {
  471. return std::numeric_limits<double>::infinity();
  472. } else if (str == TStringBuf("-Inf")) {
  473. return -std::numeric_limits<double>::infinity();
  474. } else if (str == TStringBuf("NaN")) {
  475. return NAN;
  476. }
  477. double r = 0.0;
  478. if (TryFromString(str, r)) {
  479. return r;
  480. }
  481. Y_PARSER_FAIL("cannot parse double value from '" << str << "\' at line #" << CurrentLine_);
  482. }
  483. private:
  484. TStringBuf Data_;
  485. IMetricConsumer* Consumer_;
  486. TStringBuf MetricNameLabel_;
  487. THashMap<TString, EPrometheusMetricType> SeenTypes_;
  488. THistogramBuilder HistogramBuilder_;
  489. ui32 CurrentLine_ = 1;
  490. ui32 CurrentPos_ = 0;
  491. char CurrentByte_ = 0;
  492. };
  493. } // namespace
  494. void DecodePrometheus(TStringBuf data, IMetricConsumer* c, TStringBuf metricNameLabel) {
  495. TPrometheusReader reader(data, c, metricNameLabel);
  496. reader.Read();
  497. }
  498. } // namespace NMonitoring