legacy_proto_decoder.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. #include "legacy_protobuf.h"
  2. #include <library/cpp/monlib/encode/legacy_protobuf/protos/metric_meta.pb.h>
  3. #include <library/cpp/monlib/metrics/metric_consumer.h>
  4. #include <library/cpp/monlib/metrics/labels.h>
  5. #include <util/generic/yexception.h>
  6. #include <util/generic/maybe.h>
  7. #include <util/datetime/base.h>
  8. #include <util/string/split.h>
  9. #include <google/protobuf/reflection.h>
  10. #include <algorithm>
  11. #ifdef LEGACY_PB_TRACE
  12. #define TRACE(msg) \
  13. Cerr << msg << Endl
  14. #else
  15. #define TRACE(...) ;
  16. #endif
  17. namespace NMonitoring {
  18. namespace {
  19. using TMaybeMeta = TMaybe<NMonProto::TMetricMeta>;
  20. TString ReadLabelValue(const NProtoBuf::Message& msg, const NProtoBuf::FieldDescriptor* d, const NProtoBuf::Reflection& r) {
  21. using namespace NProtoBuf;
  22. switch (d->type()) {
  23. case FieldDescriptor::TYPE_UINT32:
  24. return ::ToString(r.GetUInt32(msg, d));
  25. case FieldDescriptor::TYPE_UINT64:
  26. return ::ToString(r.GetUInt64(msg, d));
  27. case FieldDescriptor::TYPE_STRING:
  28. return r.GetString(msg, d);
  29. case FieldDescriptor::TYPE_ENUM: {
  30. auto val = r.GetEnumValue(msg, d);
  31. auto* valDesc = d->enum_type()->FindValueByNumber(val);
  32. return valDesc->name();
  33. }
  34. default:
  35. ythrow yexception() << "type " << d->type_name() << " cannot be used as a field value";
  36. }
  37. return {};
  38. }
  39. double ReadFieldAsDouble(const NProtoBuf::Message& msg, const NProtoBuf::FieldDescriptor* d, const NProtoBuf::Reflection& r) {
  40. using namespace NProtoBuf;
  41. switch (d->type()) {
  42. case FieldDescriptor::TYPE_DOUBLE:
  43. return r.GetDouble(msg, d);
  44. case FieldDescriptor::TYPE_BOOL:
  45. return r.GetBool(msg, d) ? 1 : 0;
  46. case FieldDescriptor::TYPE_INT32:
  47. return r.GetInt32(msg, d);
  48. case FieldDescriptor::TYPE_INT64:
  49. return r.GetInt64(msg, d);
  50. case FieldDescriptor::TYPE_UINT32:
  51. return r.GetUInt32(msg, d);
  52. case FieldDescriptor::TYPE_UINT64:
  53. return r.GetUInt64(msg, d);
  54. case FieldDescriptor::TYPE_SINT32:
  55. return r.GetInt32(msg, d);
  56. case FieldDescriptor::TYPE_SINT64:
  57. return r.GetInt64(msg, d);
  58. case FieldDescriptor::TYPE_FIXED32:
  59. return r.GetUInt32(msg, d);
  60. case FieldDescriptor::TYPE_FIXED64:
  61. return r.GetUInt64(msg, d);
  62. case FieldDescriptor::TYPE_SFIXED32:
  63. return r.GetInt32(msg, d);
  64. case FieldDescriptor::TYPE_SFIXED64:
  65. return r.GetInt64(msg, d);
  66. case FieldDescriptor::TYPE_FLOAT:
  67. return r.GetFloat(msg, d);
  68. case FieldDescriptor::TYPE_ENUM:
  69. return r.GetEnumValue(msg, d);
  70. default:
  71. ythrow yexception() << "type " << d->type_name() << " cannot be used as a field value";
  72. }
  73. return std::numeric_limits<double>::quiet_NaN();
  74. }
  75. double ReadRepeatedAsDouble(const NProtoBuf::Message& msg, const NProtoBuf::FieldDescriptor* d, const NProtoBuf::Reflection& r, size_t i) {
  76. using namespace NProtoBuf;
  77. switch (d->type()) {
  78. case FieldDescriptor::TYPE_DOUBLE:
  79. return r.GetRepeatedDouble(msg, d, i);
  80. case FieldDescriptor::TYPE_BOOL:
  81. return r.GetRepeatedBool(msg, d, i) ? 1 : 0;
  82. case FieldDescriptor::TYPE_INT32:
  83. return r.GetRepeatedInt32(msg, d, i);
  84. case FieldDescriptor::TYPE_INT64:
  85. return r.GetRepeatedInt64(msg, d, i);
  86. case FieldDescriptor::TYPE_UINT32:
  87. return r.GetRepeatedUInt32(msg, d, i);
  88. case FieldDescriptor::TYPE_UINT64:
  89. return r.GetRepeatedUInt64(msg, d, i);
  90. case FieldDescriptor::TYPE_SINT32:
  91. return r.GetRepeatedInt32(msg, d, i);
  92. case FieldDescriptor::TYPE_SINT64:
  93. return r.GetRepeatedInt64(msg, d, i);
  94. case FieldDescriptor::TYPE_FIXED32:
  95. return r.GetRepeatedUInt32(msg, d, i);
  96. case FieldDescriptor::TYPE_FIXED64:
  97. return r.GetRepeatedUInt64(msg, d, i);
  98. case FieldDescriptor::TYPE_SFIXED32:
  99. return r.GetRepeatedInt32(msg, d, i);
  100. case FieldDescriptor::TYPE_SFIXED64:
  101. return r.GetRepeatedInt64(msg, d, i);
  102. case FieldDescriptor::TYPE_FLOAT:
  103. return r.GetRepeatedFloat(msg, d, i);
  104. case FieldDescriptor::TYPE_ENUM:
  105. return r.GetRepeatedEnumValue(msg, d, i);
  106. default:
  107. ythrow yexception() << "type " << d->type_name() << " cannot be used as a field value";
  108. }
  109. return std::numeric_limits<double>::quiet_NaN();
  110. }
  111. TString LabelFromField(const NProtoBuf::Message& msg, const TString& name) {
  112. const auto* fieldDesc = msg.GetDescriptor()->FindFieldByName(name);
  113. const auto* reflection = msg.GetReflection();
  114. Y_ENSURE(fieldDesc && reflection, "Unable to get meta for field " << name);
  115. auto s = ReadLabelValue(msg, fieldDesc, *reflection);
  116. std::replace(std::begin(s), s.vend(), ' ', '_');
  117. return s;
  118. }
  119. TMaybeMeta MaybeGetMeta(const NProtoBuf::FieldOptions& opts) {
  120. if (opts.HasExtension(NMonProto::Metric)) {
  121. return opts.GetExtension(NMonProto::Metric);
  122. }
  123. return Nothing();
  124. }
  125. class ILabelGetter: public TThrRefBase {
  126. public:
  127. enum class EType {
  128. Fixed = 1,
  129. Lazy = 2,
  130. };
  131. virtual TLabel Get(const NProtoBuf::Message&) = 0;
  132. virtual EType Type() const = 0;
  133. };
  134. class TFixedLabel: public ILabelGetter {
  135. public:
  136. explicit TFixedLabel(TLabel&& l)
  137. : Label_{std::move(l)}
  138. {
  139. TRACE("found fixed label " << l);
  140. }
  141. EType Type() const override {
  142. return EType::Fixed;
  143. }
  144. TLabel Get(const NProtoBuf::Message&) override {
  145. return Label_;
  146. }
  147. private:
  148. TLabel Label_;
  149. };
  150. using TFunction = std::function<TLabel(const NProtoBuf::Message&)>;
  151. class TLazyLabel: public ILabelGetter {
  152. public:
  153. TLazyLabel(TFunction&& fn)
  154. : Fn_{std::move(fn)}
  155. {
  156. TRACE("found lazy label");
  157. }
  158. EType Type() const override {
  159. return EType::Lazy;
  160. }
  161. TLabel Get(const NProtoBuf::Message& msg) override {
  162. return Fn_(msg);
  163. }
  164. private:
  165. TFunction Fn_;
  166. };
  167. class TDecoderContext {
  168. public:
  169. void Init(const NProtoBuf::Message* msg) {
  170. Message_ = msg;
  171. Y_ENSURE(Message_);
  172. Reflection_ = msg->GetReflection();
  173. Y_ENSURE(Reflection_);
  174. for (auto it = Labels_.begin(); it != Labels_.end(); ++it) {
  175. if ((*it)->Type() == ILabelGetter::EType::Lazy) {
  176. auto l = (*it)->Get(Message());
  177. *it = ::MakeIntrusive<TFixedLabel>(std::move(l));
  178. } else {
  179. auto l = (*it)->Get(Message());
  180. }
  181. }
  182. }
  183. void Clear() noexcept {
  184. Message_ = nullptr;
  185. Reflection_ = nullptr;
  186. }
  187. TDecoderContext CreateChildFromMeta(const NMonProto::TMetricMeta& metricMeta, const TString& name, i64 repeatedIdx = -1) {
  188. TDecoderContext child{*this};
  189. child.Clear();
  190. if (metricMeta.HasCustomPath()) {
  191. if (const auto& nodePath = metricMeta.GetCustomPath()) {
  192. child.AppendPath(nodePath);
  193. }
  194. } else if (metricMeta.GetPath()) {
  195. child.AppendPath(name);
  196. }
  197. if (metricMeta.HasKeys()) {
  198. child.ParseKeys(metricMeta.GetKeys(), repeatedIdx);
  199. }
  200. return child;
  201. }
  202. TDecoderContext CreateChildFromRepeatedScalar(const NMonProto::TMetricMeta& metricMeta, i64 repeatedIdx = -1) {
  203. TDecoderContext child{*this};
  204. child.Clear();
  205. if (metricMeta.HasKeys()) {
  206. child.ParseKeys(metricMeta.GetKeys(), repeatedIdx);
  207. }
  208. return child;
  209. }
  210. TDecoderContext CreateChildFromEls(const TString& name, const NMonProto::TExtraLabelMetrics& metrics, size_t idx, TMaybeMeta maybeMeta) {
  211. TDecoderContext child{*this};
  212. child.Clear();
  213. auto usePath = [&maybeMeta] {
  214. return !maybeMeta->HasPath() || maybeMeta->GetPath();
  215. };
  216. if (!name.empty() && (!maybeMeta || usePath())) {
  217. child.AppendPath(name);
  218. }
  219. child.Labels_.push_back(::MakeIntrusive<TLazyLabel>(
  220. [ labelName = metrics.GetlabelName(), idx, &metrics ](const auto&) {
  221. const auto& val = metrics.Getvalues(idx);
  222. TString labelVal;
  223. const auto uintLabel = val.GetlabelValueUint();
  224. if (uintLabel) {
  225. labelVal = ::ToString(uintLabel);
  226. } else {
  227. labelVal = val.GetlabelValue();
  228. }
  229. return TLabel{labelName, labelVal};
  230. }));
  231. return child;
  232. }
  233. void ParseKeys(TStringBuf keys, i64 repeatedIdx = -1) {
  234. auto parts = StringSplitter(keys)
  235. .Split(' ')
  236. .SkipEmpty();
  237. for (auto part : parts) {
  238. auto str = part.Token();
  239. TStringBuf lhs, rhs;
  240. const bool isDynamic = str.TrySplit(':', lhs, rhs);
  241. const bool isIndexing = isDynamic && rhs == TStringBuf("#");
  242. if (isIndexing) {
  243. TRACE("parsed index labels");
  244. // <label_name>:# means that we should use index of the repeated
  245. // field as label value
  246. Y_ENSURE(repeatedIdx != -1);
  247. Labels_.push_back(::MakeIntrusive<TLazyLabel>([=](const auto&) {
  248. return TLabel{lhs, ::ToString(repeatedIdx)};
  249. }));
  250. } else if (isDynamic) {
  251. TRACE("parsed dynamic labels");
  252. // <label_name>:<field_name> means that we need to take label value
  253. // later from message's field
  254. Labels_.push_back(::MakeIntrusive<TLazyLabel>([=](const auto& msg) {
  255. return TLabel{lhs, LabelFromField(msg, TString{rhs})};
  256. }));
  257. } else if (str.TrySplit('=', lhs, rhs)) {
  258. TRACE("parsed static labels");
  259. // <label_name>=<label_value> stands for constant label
  260. Labels_.push_back(::MakeIntrusive<TFixedLabel>(TLabel{lhs, rhs}));
  261. } else {
  262. ythrow yexception() << "Incorrect Keys format";
  263. }
  264. }
  265. }
  266. void AppendPath(TStringBuf fieldName) {
  267. Path_ += '/';
  268. Path_ += fieldName;
  269. }
  270. const TString& Path() const {
  271. return Path_;
  272. }
  273. TLabels Labels() const {
  274. TLabels result;
  275. for (auto&& l : Labels_) {
  276. result.Add(l->Get(Message()));
  277. }
  278. return result;
  279. }
  280. const NProtoBuf::Message& Message() const {
  281. Y_VERIFY_DEBUG(Message_);
  282. return *Message_;
  283. }
  284. const NProtoBuf::Reflection& Reflection() const {
  285. return *Reflection_;
  286. }
  287. private:
  288. const NProtoBuf::Message* Message_{nullptr};
  289. const NProtoBuf::Reflection* Reflection_{nullptr};
  290. TString Path_;
  291. TVector<TIntrusivePtr<ILabelGetter>> Labels_;
  292. };
  293. class TDecoder {
  294. public:
  295. TDecoder(IMetricConsumer* consumer, const NProtoBuf::Message& message, TInstant timestamp)
  296. : Consumer_{consumer}
  297. , Message_{message}
  298. , Timestamp_{timestamp}
  299. {
  300. }
  301. void Decode() const {
  302. Consumer_->OnStreamBegin();
  303. DecodeToStream();
  304. Consumer_->OnStreamEnd();
  305. }
  306. void DecodeToStream() const {
  307. DecodeImpl(Message_, {});
  308. }
  309. private:
  310. static const NMonProto::TExtraLabelMetrics& ExtractExtraMetrics(TDecoderContext& ctx, const NProtoBuf::FieldDescriptor& f) {
  311. const auto& parent = ctx.Message();
  312. const auto& reflection = ctx.Reflection();
  313. auto& subMessage = reflection.GetMessage(parent, &f);
  314. return dynamic_cast<const NMonProto::TExtraLabelMetrics&>(subMessage);
  315. }
  316. void DecodeImpl(const NProtoBuf::Message& msg, TDecoderContext ctx) const {
  317. std::vector<const NProtoBuf::FieldDescriptor*> fields;
  318. ctx.Init(&msg);
  319. ctx.Reflection().ListFields(msg, &fields);
  320. for (const auto* f : fields) {
  321. Y_ENSURE(f);
  322. const auto& opts = f->options();
  323. const auto isMessage = f->type() == NProtoBuf::FieldDescriptor::TYPE_MESSAGE;
  324. const auto isExtraLabelMetrics = isMessage && f->message_type()->full_name() == "NMonProto.TExtraLabelMetrics";
  325. const auto maybeMeta = MaybeGetMeta(opts);
  326. if (!(maybeMeta || isExtraLabelMetrics)) {
  327. continue;
  328. }
  329. if (isExtraLabelMetrics) {
  330. const auto& extra = ExtractExtraMetrics(ctx, *f);
  331. RecurseExtraLabelMetrics(ctx, extra, f->name(), maybeMeta);
  332. } else if (isMessage) {
  333. RecurseMessage(ctx, *maybeMeta, *f);
  334. } else if (f->is_repeated()) {
  335. RecurseRepeatedScalar(ctx, *maybeMeta, *f);
  336. } else if (maybeMeta->HasType()) {
  337. const auto val = ReadFieldAsDouble(msg, f, ctx.Reflection());
  338. const bool isRate = maybeMeta->GetType() == NMonProto::EMetricType::RATE;
  339. WriteMetric(val, ctx, f->name(), isRate);
  340. }
  341. }
  342. }
  343. void RecurseRepeatedScalar(TDecoderContext ctx, const NMonProto::TMetricMeta& meta, const NProtoBuf::FieldDescriptor& f) const {
  344. auto&& msg = ctx.Message();
  345. auto&& reflection = ctx.Reflection();
  346. const bool isRate = meta.GetType() == NMonProto::EMetricType::RATE;
  347. // this is a repeated scalar field, which makes metric only if it's indexing
  348. for (auto i = 0; i < reflection.FieldSize(msg, &f); ++i) {
  349. auto subCtx = ctx.CreateChildFromRepeatedScalar(meta, i);
  350. subCtx.Init(&msg);
  351. auto val = ReadRepeatedAsDouble(msg, &f, reflection, i);
  352. WriteMetric(val, subCtx, f.name(), isRate);
  353. }
  354. }
  355. void RecurseExtraLabelMetrics(TDecoderContext ctx, const NMonProto::TExtraLabelMetrics& msg, const TString& name, const TMaybeMeta& meta) const {
  356. auto i = 0;
  357. for (const auto& val : msg.Getvalues()) {
  358. auto subCtx = ctx.CreateChildFromEls(name, msg, i++, meta);
  359. subCtx.Init(&val);
  360. const bool isRate = val.Hastype()
  361. ? val.Gettype() == NMonProto::EMetricType::RATE
  362. : meta->GetType() == NMonProto::EMetricType::RATE;
  363. double metricVal{0};
  364. if (isRate) {
  365. metricVal = val.GetlongValue();
  366. } else {
  367. metricVal = val.GetdoubleValue();
  368. }
  369. WriteMetric(metricVal, subCtx, "", isRate);
  370. for (const auto& child : val.Getchildren()) {
  371. RecurseExtraLabelMetrics(subCtx, child, "", meta);
  372. }
  373. }
  374. }
  375. void RecurseMessage(TDecoderContext ctx, const NMonProto::TMetricMeta& metricMeta, const NProtoBuf::FieldDescriptor& f) const {
  376. const auto& msg = ctx.Message();
  377. const auto& reflection = ctx.Reflection();
  378. if (f.is_repeated()) {
  379. TRACE("recurse into repeated message " << f.name());
  380. for (auto i = 0; i < reflection.FieldSize(msg, &f); ++i) {
  381. auto& subMessage = reflection.GetRepeatedMessage(msg, &f, i);
  382. DecodeImpl(subMessage, ctx.CreateChildFromMeta(metricMeta, f.name(), i));
  383. }
  384. } else {
  385. TRACE("recurse into message " << f.name());
  386. auto& subMessage = reflection.GetMessage(msg, &f);
  387. DecodeImpl(subMessage, ctx.CreateChildFromMeta(metricMeta, f.name()));
  388. }
  389. }
  390. inline void WriteValue(ui64 value) const {
  391. Consumer_->OnUint64(Timestamp_, value);
  392. }
  393. inline void WriteValue(double value) const {
  394. Consumer_->OnDouble(Timestamp_, value);
  395. }
  396. void WriteMetric(double value, const TDecoderContext& ctx, const TString& name, bool isRate) const {
  397. if (isRate) {
  398. Consumer_->OnMetricBegin(EMetricType::RATE);
  399. WriteValue(static_cast<ui64>(value));
  400. } else {
  401. Consumer_->OnMetricBegin(EMetricType::GAUGE);
  402. WriteValue(static_cast<double>(value));
  403. }
  404. Consumer_->OnLabelsBegin();
  405. for (const auto& label : ctx.Labels()) {
  406. Consumer_->OnLabel(label.Name(), label.Value());
  407. }
  408. const auto fullPath = name.empty()
  409. ? ctx.Path()
  410. : ctx.Path() + '/' + name;
  411. if (fullPath) {
  412. Consumer_->OnLabel("path", fullPath);
  413. }
  414. Consumer_->OnLabelsEnd();
  415. Consumer_->OnMetricEnd();
  416. }
  417. private:
  418. IMetricConsumer* Consumer_{nullptr};
  419. const NProtoBuf::Message& Message_;
  420. TInstant Timestamp_;
  421. };
  422. }
  423. void DecodeLegacyProto(const NProtoBuf::Message& data, IMetricConsumer* consumer, TInstant ts) {
  424. Y_ENSURE(consumer);
  425. TDecoder(consumer, data, ts).Decode();
  426. }
  427. void DecodeLegacyProtoToStream(const NProtoBuf::Message& data, IMetricConsumer* consumer, TInstant ts) {
  428. Y_ENSURE(consumer);
  429. TDecoder(consumer, data, ts).DecodeToStream();
  430. }
  431. }