feat(monitor): add memory metrics

This commit is contained in:
eeff
2022-12-28 15:19:42 +08:00
parent 297fa37bf5
commit bbb6b1f800
3 changed files with 48 additions and 0 deletions
+2
View File
@@ -140,6 +140,8 @@ typedef struct {
typedef struct {
char distro[32];
char kernel[32];
size_t mem_total_bytes;
size_t mem_used_bytes;
bool core_dumped;
uint64_t uptime_seconds;
size_t north_nodes;
+7
View File
@@ -35,6 +35,12 @@
"distro %s\n" \
"# HELP kernel OS kernel version\n" \
"kernel %s\n" \
"# HELP mem_total_bytes Total installed memory in bytes\n" \
"# TYPE mem_total_bytes counter\n" \
"mem_total_bytes %zu\n" \
"# HELP mem_used_bytes Used memory in bytes\n" \
"# TYPE mem_used_bytes gauge\n" \
"mem_used_bytes %zu\n" \
"# HELP core_dumped Whether there is any core dump\n" \
"# TYPE core_dumped gauge\n" \
"core_dumped %d\n" \
@@ -119,6 +125,7 @@ static inline void gen_global_metrics(const neu_metrics_t *metrics,
FILE * stream)
{
fprintf(stream, METRIC_GLOBAL_TMPL, metrics->distro, metrics->kernel,
metrics->mem_total_bytes, metrics->mem_used_bytes,
metrics->core_dumped, metrics->uptime_seconds, metrics->north_nodes,
metrics->north_running_nodes, metrics->north_disconnected_nodes,
metrics->south_nodes, metrics->south_running_nodes,
+39
View File
@@ -46,6 +46,7 @@ static void find_os_info()
if (NULL == fgets(buf, sizeof(buf), f)) {
nlog_error("no command output");
fclose(f);
return;
}
buf[strcspn(buf, "\n")] = 0;
@@ -54,6 +55,7 @@ static void find_os_info()
if (NULL == fgets(buf, sizeof(buf), f)) {
nlog_error("no command output");
fclose(f);
return;
}
buf[strcspn(buf, "\n")] = 0;
@@ -63,6 +65,40 @@ static void find_os_info()
fclose(f);
}
static size_t parse_memory_fields(int col)
{
FILE * f = NULL;
char buf[64] = {};
size_t val = 0;
sprintf(buf, "free -b | awk 'NR==2 {print $%i}'", col);
f = popen(buf, "r");
if (NULL == f) {
nlog_error("popen command fail");
return 0;
}
if (NULL != fgets(buf, sizeof(buf), f)) {
val = atoll(buf);
} else {
nlog_error("no command output");
}
fclose(f);
return val;
}
static inline size_t memory_total()
{
return parse_memory_fields(2);
}
static inline size_t memory_used()
{
return parse_memory_fields(3);
}
static bool has_core_dumps()
{
DIR *dp = opendir("core");
@@ -127,6 +163,7 @@ void neu_metrics_init()
if (0 == g_start_ts_) {
g_start_ts_ = neu_time_ms();
find_os_info();
g_metrics_.mem_total_bytes = memory_total();
}
pthread_rwlock_unlock(&g_metrics_mtx_);
}
@@ -177,9 +214,11 @@ void neu_metrics_unregister_entry(const char *name)
void neu_metrics_visist(neu_metrics_cb_t cb, void *data)
{
size_t mem_used = memory_used();
bool core_dumped = has_core_dumps();
uint64_t uptime_seconds = (neu_time_ms() - g_start_ts_) / 1000;
pthread_rwlock_rdlock(&g_metrics_mtx_);
g_metrics_.mem_used_bytes = mem_used;
g_metrics_.core_dumped = core_dumped;
g_metrics_.uptime_seconds = uptime_seconds;