// // Created by test on 2022/11/3. // #include "DBPcollector.h" DBPcollector::DBPcollector(const YAML::Node &config, std::shared_ptr dbp_client) : registry_(std::make_shared()), dbp_client_(dbp_client) { buildMetrics(config); } void DBPcollector::clearMetrics() { dbp_read_node_ids.clear(); for (auto &node: nodes) { if (nullptr != node.second.family) { if (nullptr != node.second.data) { node.second.family->Remove(node.second.data); } registry_->Remove(*node.second.family); } } nodes.clear(); metrics_json_.clear(); } void DBPcollector::buildMetrics(const YAML::Node &config) { clearMetrics(); for (auto item: config) { if (item.IsNull() || item["name"].IsNull() || item["nodeid"].IsNull() || item["type"].IsNull()) { continue; } auto node_id = item["nodeid"].as(); auto name = item["name"].as(); auto help = item["help"].as(std::string()); metrics_json_.push_back({ {"node_id", node_id}, {"name", name}, {"help", help} }); dbp_read_node_ids.emplace_back(node_id); spdlog::info("load metrics {}({}).", name, node_id); auto &node_family = prometheus::BuildGauge() .Name(name) .Help(help) .Labels(getNodeLabels(item["labels"])) .Register(*registry_); nodes[node_id] = { name, &node_family, &(node_family.Add({{"data", "data"}})), }; } } bool DBPcollector::updateMetrics() { do { if (dbp_read_node_ids.empty()) { break; } auto values = dbp_client_->readValue(dbp_read_node_ids); if (values.empty()) { // none value return break; } for (auto const &value: values) { auto node_iter = nodes.find(value.first); if (node_iter != nodes.end()) { node_iter->second.setValue(value.second); } } return true; } while (false); return false; } prometheus::Labels DBPcollector::getNodeLabels(const YAML::Node &labels) { return prometheus::Labels(); } std::vector DBPcollector::Collect() const { if (const_cast(this)->updateMetrics()) { return registry_->Collect(); } return {}; } nlohmann::json const &DBPcollector::getMetricsJson() { return metrics_json_; } void DBPcollector::st_node::setValue(double val) { if (nullptr != data) { data->Set(val); } }