bryancall commented on code in PR #13754: URL: https://github.com/apache/trafficserver/pull/13754#discussion_r4332851886
########## plugins/stats_over_http/prometheus_render.cc: ########## @@ -0,0 +1,934 @@ +/** @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; +} + +int +hex_value(char c) +{ + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + return -1; +} + +// Decodes the percent escapes and the plus signs of a query string component. A malformed escape stays as it is. +std::string +query_decode(std::string_view text) +{ + std::string out; + + out.reserve(text.size()); + for (size_t i = 0; i < text.size(); ++i) { + char const c = text[i]; + + if (c == '+') { + out += ' '; + continue; + } + if (c == '%' && i + 2 < text.size()) { + int const high = hex_value(text[i + 1]); + int const low = hex_value(text[i + 2]); + + if (high >= 0 && low >= 0) { + out += static_cast<char>(high * 16 + low); + i += 2; + continue; + } + } + out += c; + } + return out; +} +} // 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 +prometheus_escape_help_text(std::string &out, std::string_view text) +{ + for (char c : text) { + switch (c) { + case '\\': + out += "\\\\"; + break; + case '\n': + out += "\\n"; + break; + default: + out += c; + break; + } + } +} + +std::optional<std::vector<std::string>> +prometheus_record_filter(std::string_view query) +{ + static constexpr std::string_view KEY = "records[]"; + + std::optional<std::vector<std::string>> names; + + while (!query.empty()) { + size_t const amp = query.find('&'); + std::string_view const param = query.substr(0, amp); + + query.remove_prefix(amp == std::string_view::npos ? query.size() : amp + 1); + + size_t const equal = param.find('='); + std::string_view const key = param.substr(0, equal); + + if (key != KEY && (key.find_first_of("%+") == std::string_view::npos || query_decode(key) != KEY)) { + continue; + } + if (!names) { + names.emplace(); + } + names->push_back(equal == std::string_view::npos ? std::string{} : query_decode(param.substr(equal + 1))); Review Comment: A decoded name containing a NUL could be dropped here, before it reaches `record_exists()`. ########## plugins/stats_over_http/stats_over_http.cc: ########## @@ -1001,114 +805,135 @@ csv_out_stats(stats_state *my_state) } static void -prometheus_out_stats(stats_state *my_state) +count_render_stats(const PrometheusRenderStats &stats) { - TSRecordDump((TSRecordType)(TS_RECORDTYPE_PLUGIN | TS_RECORDTYPE_NODE | TS_RECORDTYPE_PROCESS), prometheus_out_stat, my_state); - APPEND_STAT_PROMETHEUS_NUMERIC("current_time_epoch_ms", "%" PRIu64, ms_since_epoch()); - // No version printed, since string stats are not supported by Prometheus. + count(metrics().series, stats.series); + count(metrics().series_dropped, stats.dropped); + count(metrics().series_relabeled, stats.relabeled); + count(metrics().series_duplicates, stats.duplicates); + count(metrics().series_type_conflicts, stats.type_conflicts); } +// Passes every record to the renderer, in the order of TSRecordDump. static void -prometheus_v2_out_stats(stats_state *my_state) +walk_records(PrometheusRenderer &renderer) { - TSRecordDump((TSRecordType)(TS_RECORDTYPE_PLUGIN | TS_RECORDTYPE_NODE | TS_RECORDTYPE_PROCESS), prometheus_v2_out_stat, my_state); - - for (const auto &sanitized_name : my_state->prometheus_v2_family_order) { - const auto &family = my_state->prometheus_v2_families.at(sanitized_name); + renderer.begin(); + TSRecordDump((TSRecordType)(TS_RECORDTYPE_PLUGIN | TS_RECORDTYPE_NODE | TS_RECORDTYPE_PROCESS), prometheus_add_stat, &renderer); +} - APPEND("# HELP "); - APPEND(sanitized_name.c_str()); - APPEND(" "); - APPEND(family.help.c_str()); - APPEND("\n"); +static void +prometheus_out_stats(output_format_t format, PrometheusRenderer &renderer, render_state *my_state) +{ + walk_records(renderer); - const char *type_str = (family.data_type == TS_RECORDDATATYPE_COUNTER) ? "counter" : "gauge"; - APPEND("# TYPE "); - APPEND(sanitized_name.c_str()); - APPEND(" "); - APPEND(type_str); - APPEND("\n"); + std::string &body = renderer.render(); - for (const auto &sample : family.samples) { - APPEND(sample.c_str()); + if (my_state->options->prometheus_epoch) { + if (format == output_format_t::PROMETHEUS_V2_OUTPUT) { + if (renderer.options().help) { + body.append("# HELP current_time_epoch_ms Current time in milliseconds since epoch.\n"); + } + body.append("# TYPE current_time_epoch_ms gauge\n"); } + body.append("current_time_epoch_ms ").append(std::to_string(ms_since_epoch())).append("\n"); } + TSIOBufferWrite(my_state->resp_buffer, body.data(), body.size()); + count_render_stats(renderer.stats()); +} + +// Whether ATS has a record named @a name. TSMgmtDataTypeGet finds a record of librecords, and TSStatFindName a metric. Neither +// finds a string metric, so a request finds one only after a render without records[] has seen it. +static bool +record_exists(const std::string &name) +{ + TSRecordDataType data_type; + int id; + + return TSMgmtDataTypeGet(name.c_str(), &data_type) == TS_SUCCESS || TSStatFindName(name.c_str(), &id) == TS_SUCCESS; Review Comment: This still checks only the part of `name` before an embedded NUL, so `...completed_requests%00a` is treated as a real record and lands in `undumped` with its suffix. -- 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]
