]> git.proxmox.com Git - ceph.git/blame - ceph/src/exporter/DaemonMetricCollector.cc
import ceph quincy 17.2.6
[ceph.git] / ceph / src / exporter / DaemonMetricCollector.cc
CommitLineData
2a845540 1#include "DaemonMetricCollector.h"
2a845540
TL
2
3#include <boost/json/src.hpp>
4#include <chrono>
5#include <filesystem>
6#include <iostream>
7#include <map>
8#include <memory>
9#include <regex>
10#include <string>
11#include <utility>
12
39ae355f
TL
13#include "common/admin_socket_client.h"
14#include "common/debug.h"
15#include "common/hostname.h"
16#include "common/perf_counters.h"
17#include "common/split.h"
18#include "global/global_context.h"
19#include "global/global_init.h"
20#include "include/common_fwd.h"
21#include "util.h"
22
2a845540
TL
23#define dout_context g_ceph_context
24#define dout_subsys ceph_subsys_ceph_exporter
25
26using json_object = boost::json::object;
27using json_value = boost::json::value;
28using json_array = boost::json::array;
29
30void DaemonMetricCollector::request_loop(boost::asio::steady_timer &timer) {
31 timer.async_wait([&](const boost::system::error_code &e) {
32 std::cerr << e << std::endl;
33 update_sockets();
34 dump_asok_metrics();
35 auto stats_period = g_conf().get_val<int64_t>("exporter_stats_period");
36 // time to wait before sending requests again
37 timer.expires_from_now(std::chrono::seconds(stats_period));
38 request_loop(timer);
39 });
40}
41
42void DaemonMetricCollector::main() {
43 // time to wait before sending requests again
44
45 boost::asio::io_service io;
46 boost::asio::steady_timer timer{io, std::chrono::seconds(0)};
47 request_loop(timer);
48 io.run();
49}
50
51std::string DaemonMetricCollector::get_metrics() {
52 const std::lock_guard<std::mutex> lock(metrics_mutex);
53 return metrics;
54}
55
56template <class T>
57void add_metric(std::unique_ptr<MetricsBuilder> &builder, T value,
58 std::string name, std::string description, std::string mtype,
59 labels_t labels) {
60 builder->add(std::to_string(value), name, description, mtype, labels);
61}
62
63void add_double_or_int_metric(std::unique_ptr<MetricsBuilder> &builder,
64 json_value value, std::string name,
65 std::string description, std::string mtype,
66 labels_t labels) {
67 if (value.is_int64()) {
68 int64_t v = value.as_int64();
69 add_metric(builder, v, name, description, mtype, labels);
70 } else if (value.is_double()) {
71 double v = value.as_double();
72 add_metric(builder, v, name, description, mtype, labels);
73 }
74}
75
76std::string boost_string_to_std(boost::json::string js) {
77 std::string res(js.data());
78 return res;
79}
80
81std::string quote(std::string value) { return "\"" + value + "\""; }
82
83bool is_hyphen(char ch) { return ch == '-'; }
84
85void DaemonMetricCollector::dump_asok_metrics() {
86 BlockTimer timer(__FILE__, __FUNCTION__);
87
88 std::vector<std::pair<std::string, int>> daemon_pids;
89
39ae355f 90 int failures = 0;
2a845540
TL
91 bool sort = g_conf().get_val<bool>("exporter_sort_metrics");
92 if (sort) {
39ae355f
TL
93 builder =
94 std::unique_ptr<OrderedMetricsBuilder>(new OrderedMetricsBuilder());
2a845540 95 } else {
39ae355f
TL
96 builder =
97 std::unique_ptr<UnorderedMetricsBuilder>(new UnorderedMetricsBuilder());
2a845540
TL
98 }
99 for (auto &[daemon_name, sock_client] : clients) {
100 bool ok;
101 sock_client.ping(&ok);
102 if (!ok) {
39ae355f 103 failures++;
2a845540
TL
104 continue;
105 }
39ae355f
TL
106 std::string perf_dump_response =
107 asok_request(sock_client, "perf dump", daemon_name);
2a845540 108 if (perf_dump_response.size() == 0) {
39ae355f 109 failures++;
2a845540
TL
110 continue;
111 }
39ae355f
TL
112 std::string perf_schema_response =
113 asok_request(sock_client, "perf schema", daemon_name);
2a845540 114 if (perf_schema_response.size() == 0) {
39ae355f
TL
115 failures++;
116 continue;
117 }
118 std::string config_show =
119 asok_request(sock_client, "config show", daemon_name);
120 if (config_show.size() == 0) {
121 failures++;
2a845540
TL
122 continue;
123 }
2a845540
TL
124 json_object pid_file_json = boost::json::parse(config_show).as_object();
125 std::string pid_path =
39ae355f 126 boost_string_to_std(pid_file_json["pid_file"].as_string());
2a845540
TL
127 std::string pid_str = read_file_to_string(pid_path);
128 if (!pid_path.size()) {
39ae355f
TL
129 dout(1) << "pid path is empty; process metrics won't be fetched for: "
130 << daemon_name << dendl;
131 }
132 if (!pid_str.empty()) {
133 daemon_pids.push_back({daemon_name, std::stoi(pid_str)});
2a845540 134 }
2a845540
TL
135 json_object dump = boost::json::parse(perf_dump_response).as_object();
136 json_object schema = boost::json::parse(perf_schema_response).as_object();
137 for (auto &perf : schema) {
39ae355f 138 std::string perf_group = {perf.key().begin(), perf.key().end()};
2a845540
TL
139 json_object perf_group_object = perf.value().as_object();
140 for (auto &perf_counter : perf_group_object) {
39ae355f
TL
141 std::string perf_name = {perf_counter.key().begin(),
142 perf_counter.key().end()};
2a845540
TL
143 json_object perf_info = perf_counter.value().as_object();
144 auto prio_limit = g_conf().get_val<int64_t>("exporter_prio_limit");
39ae355f 145 if (perf_info["priority"].as_int64() < prio_limit) {
2a845540
TL
146 continue;
147 }
148 std::string name = "ceph_" + perf_group + "_" + perf_name;
149 std::replace_if(name.begin(), name.end(), is_hyphen, '_');
150
151 // FIXME: test this, based on mgr_module perfpath_to_path_labels
152 auto labels_and_name = get_labels_and_metric_name(daemon_name, name);
153 labels_t labels = labels_and_name.first;
154 name = labels_and_name.second;
155
156 json_value perf_values = dump[perf_group].as_object()[perf_name];
157 dump_asok_metric(perf_info, perf_values, name, labels);
158 }
159 }
160 }
39ae355f
TL
161 dout(10) << "Perf counters retrieved for " << clients.size() - failures << "/"
162 << clients.size() << " daemons." << dendl;
2a845540
TL
163 // get time spent on this function
164 timer.stop();
39ae355f
TL
165 std::string scrap_desc(
166 "Time spent scraping and transforming perf counters to metrics");
2a845540
TL
167 labels_t scrap_labels;
168 scrap_labels["host"] = quote(ceph_get_hostname());
169 scrap_labels["function"] = quote(__FUNCTION__);
170 add_metric(builder, timer.get_ms(), "ceph_exporter_scrape_time", scrap_desc,
171 "gauge", scrap_labels);
172
173 const std::lock_guard<std::mutex> lock(metrics_mutex);
39ae355f
TL
174 // only get metrics if there's pid path for some or all daemons isn't empty
175 if (daemon_pids.size() != 0) {
176 get_process_metrics(daemon_pids);
177 }
2a845540
TL
178 metrics = builder->dump();
179}
180
181std::vector<std::string> read_proc_stat_file(std::string path) {
182 std::string stat = read_file_to_string(path);
183 std::vector<std::string> strings;
184 auto parts = ceph::split(stat);
185 strings.assign(parts.begin(), parts.end());
186 return strings;
187}
188
189struct pstat read_pid_stat(int pid) {
190 std::string stat_path("/proc/" + std::to_string(pid) + "/stat");
191 std::vector<std::string> stats = read_proc_stat_file(stat_path);
192 struct pstat stat;
193 stat.minflt = std::stoul(stats[9]);
194 stat.majflt = std::stoul(stats[11]);
195 stat.utime = std::stoul(stats[13]);
196 stat.stime = std::stoul(stats[14]);
197 stat.num_threads = std::stoul(stats[19]);
198 stat.start_time = std::stoul(stats[21]);
199 stat.vm_size = std::stoul(stats[22]);
200 stat.resident_size = std::stoi(stats[23]);
201 return stat;
202}
203
39ae355f
TL
204void DaemonMetricCollector::get_process_metrics(
205 std::vector<std::pair<std::string, int>> daemon_pids) {
2a845540
TL
206 std::string path("/proc");
207 std::stringstream ss;
208 for (auto &[daemon_name, pid] : daemon_pids) {
209 std::vector<std::string> uptimes = read_proc_stat_file("/proc/uptime");
210 struct pstat stat = read_pid_stat(pid);
211 int clk_tck = sysconf(_SC_CLK_TCK);
212 double start_time_seconds = stat.start_time / (double)clk_tck;
213 double user_time = stat.utime / (double)clk_tck;
214 double kernel_time = stat.stime / (double)clk_tck;
215 double total_time_seconds = user_time + kernel_time;
216 double uptime = std::stod(uptimes[0]);
217 double elapsed_time = uptime - start_time_seconds;
39ae355f 218 double idle_time = elapsed_time - total_time_seconds;
2a845540
TL
219 double usage = total_time_seconds * 100 / elapsed_time;
220
221 labels_t labels;
222 labels["ceph_daemon"] = quote(daemon_name);
223 add_metric(builder, stat.minflt, "ceph_exporter_minflt_total",
224 "Number of minor page faults of daemon", "counter", labels);
225 add_metric(builder, stat.majflt, "ceph_exporter_majflt_total",
226 "Number of major page faults of daemon", "counter", labels);
227 add_metric(builder, stat.num_threads, "ceph_exporter_num_threads",
228 "Number of threads used by daemon", "gauge", labels);
39ae355f
TL
229 add_metric(builder, usage, "ceph_exporter_cpu_usage",
230 "CPU usage of a daemon", "gauge", labels);
2a845540
TL
231
232 std::string cpu_time_desc = "Process time in kernel/user/idle mode";
233 labels_t cpu_total_labels;
234 cpu_total_labels["ceph_daemon"] = quote(daemon_name);
235 cpu_total_labels["mode"] = quote("kernel");
236 add_metric(builder, kernel_time, "ceph_exporter_cpu_total", cpu_time_desc,
237 "counter", cpu_total_labels);
238 cpu_total_labels["mode"] = quote("user");
239 add_metric(builder, user_time, "ceph_exporter_cpu_total", cpu_time_desc,
240 "counter", cpu_total_labels);
241 cpu_total_labels["mode"] = quote("idle");
242 add_metric(builder, idle_time, "ceph_exporter_cpu_total", cpu_time_desc,
243 "counter", cpu_total_labels);
39ae355f
TL
244 add_metric(builder, stat.vm_size, "ceph_exporter_vm_size",
245 "Virtual memory used in a daemon", "gauge", labels);
2a845540
TL
246 add_metric(builder, stat.resident_size, "ceph_exporter_resident_size",
247 "Resident memory in a daemon", "gauge", labels);
248 }
249}
250
251std::string DaemonMetricCollector::asok_request(AdminSocketClient &asok,
39ae355f
TL
252 std::string command,
253 std::string daemon_name) {
2a845540
TL
254 std::string request("{\"prefix\": \"" + command + "\"}");
255 std::string response;
256 std::string err = asok.do_request(request, &response);
257 if (err.length() > 0 || response.substr(0, 5) == "ERROR") {
39ae355f
TL
258 dout(1) << "command " << command << "failed for daemon " << daemon_name
259 << "with error: " << err << dendl;
2a845540
TL
260 return "";
261 }
262 return response;
263}
264
265std::pair<labels_t, std::string>
266DaemonMetricCollector::get_labels_and_metric_name(std::string daemon_name,
267 std::string metric_name) {
268 std::string new_metric_name;
269 labels_t labels;
270 new_metric_name = metric_name;
271 if (daemon_name.find("rgw") != std::string::npos) {
272 std::string tmp = daemon_name.substr(16, std::string::npos);
273 std::string::size_type pos = tmp.find('.');
274 labels["instance_id"] = quote("rgw." + tmp.substr(0, pos));
275 } else {
276 labels["ceph_daemon"] = quote(daemon_name);
277 if (daemon_name.find("rbd-mirror") != std::string::npos) {
39ae355f
TL
278 std::regex re(
279 "^rbd_mirror_image_([^/]+)/(?:(?:([^/]+)/"
280 ")?)(.*)\\.(replay(?:_bytes|_latency)?)$");
2a845540
TL
281 std::smatch match;
282 if (std::regex_search(daemon_name, match, re) == true) {
283 new_metric_name = "ceph_rbd_mirror_image_" + match.str(4);
284 labels["pool"] = quote(match.str(1));
285 labels["namespace"] = quote(match.str(2));
286 labels["image"] = quote(match.str(3));
287 }
288 }
289 }
290 return {labels, new_metric_name};
291}
292
293/*
294perf_values can be either a int/double or a json_object. Since
295 json_value is a wrapper of both we use that class.
296 */
297void DaemonMetricCollector::dump_asok_metric(json_object perf_info,
298 json_value perf_values,
299 std::string name,
300 labels_t labels) {
301 int64_t type = perf_info["type"].as_int64();
302 std::string metric_type =
39ae355f 303 boost_string_to_std(perf_info["metric_type"].as_string());
2a845540 304 std::string description =
39ae355f 305 boost_string_to_std(perf_info["description"].as_string());
2a845540
TL
306
307 if (type & PERFCOUNTER_LONGRUNAVG) {
308 int64_t count = perf_values.as_object()["avgcount"].as_int64();
309 add_metric(builder, count, name + "_count", description, metric_type,
310 labels);
311 json_value sum_value = perf_values.as_object()["sum"];
312 add_double_or_int_metric(builder, sum_value, name + "_sum", description,
313 metric_type, labels);
314 } else if (type & PERFCOUNTER_TIME) {
315 if (perf_values.is_int64()) {
316 double value = perf_values.as_int64() / 1000000000.0f;
317 add_metric(builder, value, name, description, metric_type, labels);
318 } else if (perf_values.is_double()) {
319 double value = perf_values.as_double() / 1000000000.0f;
320 add_metric(builder, value, name, description, metric_type, labels);
321 }
322 } else {
323 add_double_or_int_metric(builder, perf_values, name, description,
324 metric_type, labels);
325 }
326}
327
328void DaemonMetricCollector::update_sockets() {
329 std::string sock_dir = g_conf().get_val<std::string>("exporter_sock_dir");
330 clients.clear();
331 std::filesystem::path sock_path = sock_dir;
39ae355f 332 if (!std::filesystem::is_directory(sock_path.parent_path())) {
2a845540
TL
333 dout(1) << "ERROR: No such directory exist" << sock_dir << dendl;
334 return;
335 }
39ae355f 336 for (const auto &entry : std::filesystem::directory_iterator(sock_dir)) {
2a845540
TL
337 if (entry.path().extension() == ".asok") {
338 std::string daemon_socket_name = entry.path().filename().string();
339 std::string daemon_name =
39ae355f 340 daemon_socket_name.substr(0, daemon_socket_name.size() - 5);
2a845540
TL
341 if (clients.find(daemon_name) == clients.end() &&
342 !(daemon_name.find("mgr") != std::string::npos) &&
343 !(daemon_name.find("ceph-exporter") != std::string::npos)) {
344 AdminSocketClient sock(entry.path().string());
345 clients.insert({daemon_name, std::move(sock)});
346 }
347 }
348 }
349}
350
351void OrderedMetricsBuilder::add(std::string value, std::string name,
352 std::string description, std::string mtype,
353 labels_t labels) {
2a845540
TL
354 if (metrics.find(name) == metrics.end()) {
355 Metric metric(name, mtype, description);
356 metrics[name] = std::move(metric);
357 }
358 Metric &metric = metrics[name];
359 metric.add(labels, value);
360}
361
362std::string OrderedMetricsBuilder::dump() {
363 for (auto &[name, metric] : metrics) {
364 out += metric.dump() + "\n";
365 }
366 return out;
367}
368
369void UnorderedMetricsBuilder::add(std::string value, std::string name,
370 std::string description, std::string mtype,
371 labels_t labels) {
2a845540
TL
372 Metric metric(name, mtype, description);
373 metric.add(labels, value);
374 out += metric.dump() + "\n\n";
375}
376
377std::string UnorderedMetricsBuilder::dump() { return out; }
378
379void Metric::add(labels_t labels, std::string value) {
380 metric_entry entry;
381 entry.labels = labels;
382 entry.value = value;
383 entries.push_back(entry);
384}
385
386std::string Metric::dump() {
387 std::stringstream metric_ss;
388 metric_ss << "# HELP " << name << " " << description << "\n";
389 metric_ss << "# TYPE " << name << " " << mtype << "\n";
390 for (auto &entry : entries) {
391 std::stringstream labels_ss;
392 size_t i = 0;
393 for (auto &[label_name, label_value] : entry.labels) {
394 labels_ss << label_name << "=" << label_value;
395 if (i < entry.labels.size() - 1) {
396 labels_ss << ",";
397 }
398 i++;
399 }
400 metric_ss << name << "{" << labels_ss.str() << "} " << entry.value;
401 if (&entry != &entries.back()) {
402 metric_ss << "\n";
403 }
404 }
405 return metric_ss.str();
406}
407
408DaemonMetricCollector &collector_instance() {
409 static DaemonMetricCollector instance;
410 return instance;
411}