Copilot commented on code in PR #13754: URL: https://github.com/apache/trafficserver/pull/13754#discussion_r4161707674
########## plugins/stats_over_http/prometheus_render.cc: ########## @@ -0,0 +1,739 @@ +/** @file + + Render records in the Prometheus text format from a cache of translated names. + + @section license License + + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#include "prometheus_render.h" + +#include <algorithm> +#include <cerrno> +#include <charconv> +#include <cmath> +#include <cstdio> +#include <cstdlib> +#include <functional> +#include <limits> +#include <numeric> + +#include "prometheus_rules.h" +#include "tsutil/DbgCtl.h" +#include "tsutil/StringCompare.h" + +namespace +{ +DbgCtl dbg_ctl{"stats_over_http"}; + +bool +is_numeric(TSRecordDataType data_type) +{ + return data_type == TS_RECORDDATATYPE_COUNTER || data_type == TS_RECORDDATATYPE_INT || data_type == TS_RECORDDATATYPE_FLOAT; +} + +bool +is_digit(char c) +{ + return c >= '0' && c <= '9'; +} + +// Accepts a decimal number with an optional sign and exponent, Inf or Infinity with an optional sign, or NaN. The case of +// the letters does not matter. Rejects a number too large for a double. +bool +parse_number(const std::string &text, double &value) +{ + std::string_view body{text}; + + if (ts::iequals(body, "nan")) { + value = NAN; + return true; + } + if (!body.empty() && (body[0] == '+' || body[0] == '-')) { + body.remove_prefix(1); + } + if (!ts::iequals(body, "inf") && !ts::iequals(body, "infinity")) { + size_t i = 0; + size_t digits = 0; + + for (; i < body.size() && is_digit(body[i]); ++i) { + ++digits; + } + if (i < body.size() && body[i] == '.') { + for (++i; i < body.size() && is_digit(body[i]); ++i) { + ++digits; + } + } + if (digits == 0) { + return false; + } + if (i < body.size() && (body[i] == 'e' || body[i] == 'E')) { + size_t exponent = 0; + + if (++i < body.size() && (body[i] == '+' || body[i] == '-')) { + ++i; + } + for (; i < body.size() && is_digit(body[i]); ++i) { + ++exponent; + } + if (exponent == 0) { + return false; + } + } + if (i != body.size()) { + return false; + } + } + errno = 0; + value = std::strtod(text.c_str(), nullptr); + return !(errno == ERANGE && std::isinf(value)); +} + +// Appends @a value with the fewest significant digits, from @a min to @a max, that parse back to the same value. With +// @a single, the digits must parse back to the same float. NaN and the infinities get their Prometheus spellings. +void +append_number(std::string &out, double value, int min, int max, bool single) +{ + if (std::isnan(value)) { + out += "NaN"; + return; + } + if (std::isinf(value)) { + out += value > 0 ? "+Inf" : "-Inf"; + return; + } + + char buffer[32]; + int length = 0; + + for (int precision = min; precision <= max; ++precision) { + length = snprintf(buffer, sizeof(buffer), "%.*g", precision, value); + if (single ? std::strtof(buffer, nullptr) == static_cast<float>(value) : std::strtod(buffer, nullptr) == value) { + break; + } + } + out.append(buffer, length); +} + +std::string +join(const std::vector<std::string> &names) +{ + std::string result; + + for (const std::string &name : names) { + if (!result.empty()) { + result += ", "; + } + result += name; + } + return result; +} +} // namespace + +std::string_view +prometheus_type_name(PrometheusType type) +{ + switch (type) { + case PrometheusType::COUNTER: + return "counter"; + case PrometheusType::GAUGE: + return "gauge"; + case PrometheusType::UNTYPED: + break; + } + return "untyped"; +} + +void +prometheus_escape_label_value(std::string &out, std::string_view value) +{ + for (char c : value) { + switch (c) { + case '\\': + out += "\\\\"; + break; + case '"': + out += "\\\""; + break; + case '\n': + out += "\\n"; + break; + default: + out += c; + break; + } + } +} + +void +PrometheusRenderer::begin() +{ + ++_renders; + _position = 0; + _stats = {}; +} + +void +PrometheusRenderer::add(const char *name, TSRecordDataType data_type, const TSRecordData &datum) +{ + uint32_t const position = _position++; + uint32_t index; + + if (position < _slots.size() && _slots[position].name == name && _records[_slots[position].record].data_type == data_type) { + index = _slots[position].record; + } else { + index = find(name, data_type); + if (position < _slots.size()) { + _slots[position] = {name, index}; + } else { + _slots.push_back({name, index}); + } + } + + Record &record = _records[index]; + record.last_render = _renders; + record.datum = datum; + if (record.value == Value::TEXT_LABEL || record.value == Value::TEXT_NUMBER) { + // The string is valid only while TSRecordDump calls back. + _info[index].text.assign(datum.rec_string != nullptr ? datum.rec_string : ""); + } else if (record.value == Value::NONE && _info[index].invalid) { + ++_stats.dropped; + } +} + +uint32_t +PrometheusRenderer::find(const char *name, TSRecordDataType data_type) +{ + if (auto it = _by_pointer.find(name); it != _by_pointer.end() && _records[it->second].data_type == data_type) { + return it->second; + } + + auto [it, added] = _by_name.try_emplace(name, 0); + + if (added || _records[it->second].data_type != data_type) { + it->second = translate(it->first, data_type); + } + _by_pointer[name] = it->second; + return it->second; +} + +uint32_t +PrometheusRenderer::add_record(std::string_view name, TSRecordDataType data_type) +{ + auto const index = static_cast<uint32_t>(_records.size()); + + _records.emplace_back().data_type = data_type; + _info.emplace_back().name = name; + _writers.push_back({index, 0}); + return index; +} + +uint32_t +PrometheusRenderer::add_family(const std::string &name, std::string_view record_name, PrometheusType type, uint32_t record) +{ + auto [it, added] = _family_index.try_emplace(name, static_cast<uint32_t>(_families.size())); + + if (added) { + Family &family = _families.emplace_back(); + + _family_info.push_back({name, record}); + _reorder = true; + family.type = type; + if (_options.help) { + family.header.append("# HELP ").append(name).append(" ").append(record_name).append("\n"); Review Comment: The original record name is inserted into a Prometheus `HELP` line without escaping. ATS metric creation does not restrict names, so a name containing `\` or a newline produces invalid exposition (a newline also injects an extra line). Escape backslashes and newlines in HELP text as required by the Prometheus text format. ########## plugins/stats_over_http/prometheus_render.cc: ########## @@ -0,0 +1,739 @@ +/** @file + + Render records in the Prometheus text format from a cache of translated names. + + @section license License + + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#include "prometheus_render.h" + +#include <algorithm> +#include <cerrno> +#include <charconv> +#include <cmath> +#include <cstdio> +#include <cstdlib> +#include <functional> +#include <limits> +#include <numeric> + +#include "prometheus_rules.h" +#include "tsutil/DbgCtl.h" +#include "tsutil/StringCompare.h" + +namespace +{ +DbgCtl dbg_ctl{"stats_over_http"}; + +bool +is_numeric(TSRecordDataType data_type) +{ + return data_type == TS_RECORDDATATYPE_COUNTER || data_type == TS_RECORDDATATYPE_INT || data_type == TS_RECORDDATATYPE_FLOAT; +} + +bool +is_digit(char c) +{ + return c >= '0' && c <= '9'; +} + +// Accepts a decimal number with an optional sign and exponent, Inf or Infinity with an optional sign, or NaN. The case of +// the letters does not matter. Rejects a number too large for a double. +bool +parse_number(const std::string &text, double &value) +{ + std::string_view body{text}; + + if (ts::iequals(body, "nan")) { + value = NAN; + return true; + } + if (!body.empty() && (body[0] == '+' || body[0] == '-')) { + body.remove_prefix(1); + } + if (!ts::iequals(body, "inf") && !ts::iequals(body, "infinity")) { + size_t i = 0; + size_t digits = 0; + + for (; i < body.size() && is_digit(body[i]); ++i) { + ++digits; + } + if (i < body.size() && body[i] == '.') { + for (++i; i < body.size() && is_digit(body[i]); ++i) { + ++digits; + } + } + if (digits == 0) { + return false; + } + if (i < body.size() && (body[i] == 'e' || body[i] == 'E')) { + size_t exponent = 0; + + if (++i < body.size() && (body[i] == '+' || body[i] == '-')) { + ++i; + } + for (; i < body.size() && is_digit(body[i]); ++i) { + ++exponent; + } + if (exponent == 0) { + return false; + } + } + if (i != body.size()) { + return false; + } + } + errno = 0; + value = std::strtod(text.c_str(), nullptr); + return !(errno == ERANGE && std::isinf(value)); +} + +// Appends @a value with the fewest significant digits, from @a min to @a max, that parse back to the same value. With +// @a single, the digits must parse back to the same float. NaN and the infinities get their Prometheus spellings. +void +append_number(std::string &out, double value, int min, int max, bool single) +{ + if (std::isnan(value)) { + out += "NaN"; + return; + } + if (std::isinf(value)) { + out += value > 0 ? "+Inf" : "-Inf"; + return; + } + + char buffer[32]; + int length = 0; + + for (int precision = min; precision <= max; ++precision) { + length = snprintf(buffer, sizeof(buffer), "%.*g", precision, value); + if (single ? std::strtof(buffer, nullptr) == static_cast<float>(value) : std::strtod(buffer, nullptr) == value) { + break; + } + } + out.append(buffer, length); +} + +std::string +join(const std::vector<std::string> &names) +{ + std::string result; + + for (const std::string &name : names) { + if (!result.empty()) { + result += ", "; + } + result += name; + } + return result; +} +} // namespace + +std::string_view +prometheus_type_name(PrometheusType type) +{ + switch (type) { + case PrometheusType::COUNTER: + return "counter"; + case PrometheusType::GAUGE: + return "gauge"; + case PrometheusType::UNTYPED: + break; + } + return "untyped"; +} + +void +prometheus_escape_label_value(std::string &out, std::string_view value) +{ + for (char c : value) { + switch (c) { + case '\\': + out += "\\\\"; + break; + case '"': + out += "\\\""; + break; + case '\n': + out += "\\n"; + break; + default: + out += c; + break; + } + } +} + +void +PrometheusRenderer::begin() +{ + ++_renders; + _position = 0; + _stats = {}; +} + +void +PrometheusRenderer::add(const char *name, TSRecordDataType data_type, const TSRecordData &datum) +{ + uint32_t const position = _position++; + uint32_t index; + + if (position < _slots.size() && _slots[position].name == name && _records[_slots[position].record].data_type == data_type) { + index = _slots[position].record; + } else { + index = find(name, data_type); + if (position < _slots.size()) { + _slots[position] = {name, index}; + } else { + _slots.push_back({name, index}); + } + } + + Record &record = _records[index]; + record.last_render = _renders; + record.datum = datum; + if (record.value == Value::TEXT_LABEL || record.value == Value::TEXT_NUMBER) { + // The string is valid only while TSRecordDump calls back. + _info[index].text.assign(datum.rec_string != nullptr ? datum.rec_string : ""); + } else if (record.value == Value::NONE && _info[index].invalid) { + ++_stats.dropped; + } +} + +uint32_t +PrometheusRenderer::find(const char *name, TSRecordDataType data_type) +{ + if (auto it = _by_pointer.find(name); it != _by_pointer.end() && _records[it->second].data_type == data_type) { + return it->second; + } + + auto [it, added] = _by_name.try_emplace(name, 0); + + if (added || _records[it->second].data_type != data_type) { + it->second = translate(it->first, data_type); + } + _by_pointer[name] = it->second; + return it->second; +} + +uint32_t +PrometheusRenderer::add_record(std::string_view name, TSRecordDataType data_type) +{ + auto const index = static_cast<uint32_t>(_records.size()); + + _records.emplace_back().data_type = data_type; + _info.emplace_back().name = name; + _writers.push_back({index, 0}); + return index; +} + +uint32_t +PrometheusRenderer::add_family(const std::string &name, std::string_view record_name, PrometheusType type, uint32_t record) +{ + auto [it, added] = _family_index.try_emplace(name, static_cast<uint32_t>(_families.size())); + + if (added) { + Family &family = _families.emplace_back(); + + _family_info.push_back({name, record}); + _reorder = true; + family.type = type; + if (_options.help) { + family.header.append("# HELP ").append(name).append(" ").append(record_name).append("\n"); + } + if (type != PrometheusType::UNTYPED) { + family.header.append("# TYPE ").append(name).append(" ").append(prometheus_type_name(type)).append("\n"); + } + } + return it->second; +} + +uint32_t +PrometheusRenderer::translate(std::string_view name, TSRecordDataType data_type) +{ + if (_options.rules != nullptr) { + return translate_rules(name, data_type); + } + + uint32_t const index = add_record(name, data_type); + + if (!is_numeric(data_type)) { + Dbg(dbg_ctl, "Prometheus supports only numeric values, skipping: %.*s", static_cast<int>(name.size()), name.data()); + } else if (PrometheusName translated = _options.namer(name, data_type); !translated.family.empty()) { + Record &record = _records[index]; + + record.value = Value::NUMBER; + record.type = translated.type; + _info[index].family = add_family(translated.family, name, translated.type, index); + + Family &family = _families[_info[index].family]; + + if (family.type != translated.type) { + Dbg(dbg_ctl, "Inconsistent types for metric family %s: %.*s is %s, the family is %s", translated.family.c_str(), + static_cast<int>(name.size()), name.data(), prometheus_type_name(translated.type).data(), + prometheus_type_name(family.type).data()); + } + record.prefix = std::move(translated.family); + if (!translated.labels.empty()) { + record.prefix.append("{").append(translated.labels).append("}"); + } + record.prefix += ' '; + family.members.push_back(index); + } + return index; +} + +uint32_t +PrometheusRenderer::translate_rules(std::string_view name, TSRecordDataType data_type) +{ + uint32_t const index = add_record(name, data_type); + PrometheusRuleMatch const match = _options.rules->translate(name, data_type); + Record &record = _records[index]; + RecordInfo &info = _info[index]; + + if (match.result == PrometheusRuleMatch::Result::INVALID_NAME) { + info.invalid = true; + if (!_warned_invalid && _options.warn != nullptr) { + _warned_invalid = true; + _options.warn("Leaving out " + std::string{name} + ", because the rules name it " + match.family + + ", which is not a valid metric name. Other such records are left out without a message"); + } + return index; + } + if (match.result == PrometheusRuleMatch::Result::EXCLUDED) { + return index; + } + + if (match.text_label) { + record.value = Value::TEXT_LABEL; + } else { + record.value = data_type == TS_RECORDDATATYPE_STRING ? Value::TEXT_NUMBER : Value::NUMBER; + } + record.type = match.type; + info.rule_index = match.rule_index; + info.label_names = match.label_names; + info.family = add_family(match.family, name, match.type, index); + + Family &family = _families[info.family]; + FamilyInfo &family_info = _family_info[info.family]; + + family.members.push_back(index); + mark_unsorted(info.family); + if (family_info.definer != index && defines_over(index, family_info.definer)) { + family_info.definer = index; + regroup(info.family); + } else { + place(index, match.label_values); + } + return index; +} + +void +PrometheusRenderer::place(uint32_t index, const std::vector<std::string> &label_values) +{ + Record &record = _records[index]; + RecordInfo &info = _info[index]; + FamilyInfo const &family = _family_info[info.family]; + const std::vector<std::string> &own = *info.label_names; + const std::vector<std::string> &defined = *_info[family.definer].label_names; + bool const same = std::is_permutation(own.begin(), own.end(), defined.begin(), defined.end()); + // The same label names in another order keep their values. Other names take the names of the family by position. + const std::vector<std::string> &names = same ? own : defined; + + _writers[index].first = index; + record.dropped = own.size() != defined.size() || other_kind(index); + record.relabeled = !record.dropped && !same; + record.prefix.clear(); + if (record.dropped) { + return; + } + + struct Label { + std::string_view name; + std::string_view value; + bool text; + }; + + std::vector<Label> labels; + // The string value takes the last position. + size_t const text = record.value == Value::TEXT_LABEL ? names.size() - 1 : names.size(); + + for (size_t i = 0; i < names.size(); ++i) { + labels.push_back({names[i], i == text ? std::string_view{} : std::string_view{label_values[i]}, i == text}); + } + for (auto const &[name, value] : _options.rules->const_labels()) { + labels.push_back({name, value, false}); + } + std::sort(labels.begin(), labels.end(), [](const Label &a, const Label &b) { return a.name < b.name; }); + + record.prefix = family.name; + if (!labels.empty()) { + record.prefix += '{'; + for (size_t i = 0; i < labels.size(); ++i) { + if (i > 0) { + record.prefix += ','; + } + record.prefix.append(labels[i].name).append("=\""); + if (labels[i].text) { + info.split = static_cast<uint32_t>(record.prefix.size()); + } else { + prometheus_escape_label_value(record.prefix, labels[i].value); + } + record.prefix += '"'; + } + record.prefix += '}'; + } + record.prefix += ' '; + + size_t const hash = std::hash<std::string>{}(record.prefix); + auto const [first, last] = _series.equal_range(hash); + + for (auto it = first; it != last; ++it) { + if (_records[it->second].prefix == record.prefix) { + _writers[index].first = it->second; + return; + } + } + _series.emplace(hash, index); +} + +void +PrometheusRenderer::forget_series(uint32_t index) +{ + Record const &record = _records[index]; + + if (record.dropped || _writers[index].first != index) { + return; + } + + auto const [first, last] = _series.equal_range(std::hash<std::string>{}(record.prefix)); + + for (auto it = first; it != last; ++it) { + if (it->second == index) { + _series.erase(it); + return; + } + } +} + +// The label names of the family changed, so place each member again. +void +PrometheusRenderer::regroup(uint32_t family) +{ + auto &members = _families[family].members; + + for (uint32_t member : members) { + forget_series(member); + } + std::sort(members.begin(), members.end()); + for (uint32_t member : members) { + place(member, _options.rules->translate(_info[member].name, _records[member].data_type).label_values); Review Comment: `regroup()` retranslates every existing member whenever a later rule becomes the family definer. A configuration with many rules feeding one family can therefore run the regex/rule pipeline repeatedly (quadratic work during the first render or after reload), contrary to the cached-translation design and potentially causing scrape timeouts. Cache each match's `label_values` in `RecordInfo` when the record is first translated and reuse them here. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
