]> git.sesse.net Git - nageru/blobdiff - metrics.h
Fix a problem where Prometheus cannot handle negative NaNs.
[nageru] / metrics.h
index bd506a97c6c11dfdbc19247706acae5cb995b497..603abb09630623c163d155952346d0fdb6a6865f 100644 (file)
--- a/metrics.h
+++ b/metrics.h
@@ -48,19 +48,43 @@ public:
        void add(const std::string &name, const std::vector<std::pair<std::string, std::string>> &labels, std::atomic<double> *location, Type type = TYPE_COUNTER);
        void add(const std::string &name, const std::vector<std::pair<std::string, std::string>> &labels, Histogram *location);
 
+       void remove(const std::string &name)
+       {
+               remove(name, {});
+       }
+
+       void remove(const std::string &name, const std::vector<std::pair<std::string, std::string>> &labels);
+
        std::string serialize() const;
 
 private:
+       static std::string serialize_name(const std::string &name, const std::vector<std::pair<std::string, std::string>> &labels);
+       static std::string serialize_labels(const std::vector<std::pair<std::string, std::string>> &labels);
+
        enum DataType {
                DATA_TYPE_INT64,
                DATA_TYPE_DOUBLE,
                DATA_TYPE_HISTOGRAM,
        };
-
+       struct MetricKey {
+               MetricKey(const std::string &name, const std::vector<std::pair<std::string, std::string>> labels)
+                       : name(name), labels(labels), serialized_labels(serialize_labels(labels))
+               {
+               }
+
+               bool operator< (const MetricKey &other) const
+               {
+                       if (name != other.name)
+                               return name < other.name;
+                       return serialized_labels < other.serialized_labels;
+               }
+
+               const std::string name;
+               const std::vector<std::pair<std::string, std::string>> labels;
+               const std::string serialized_labels;
+       };
        struct Metric {
                DataType data_type;
-               std::string name;
-               std::vector<std::pair<std::string, std::string>> labels;
                union {
                        std::atomic<int64_t> *location_int64;
                        std::atomic<double> *location_double;
@@ -69,9 +93,11 @@ private:
        };
 
        mutable std::mutex mu;
-       std::map<std::string, Type> types;
-       std::vector<Metric> metrics;
+       std::map<std::string, Type> types;  // Ordered the same as metrics.
+       std::map<MetricKey, Metric> metrics;
        std::vector<Histogram> histograms;
+
+       friend class Histogram;
 };
 
 class Histogram {