-
Notifications
You must be signed in to change notification settings - Fork 0
Metrics collection #11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
src/metrics-collector.cpp
Outdated
FILE *file = fopen("/proc/stat", "r"); | ||
char cpu_name[32]; | ||
|
||
while (true) { | ||
CPUInfo cpu; | ||
|
||
fscanf(file, "%s %lu %lu %lu %lu %*u %*u %*u %*u %*u %*u", | ||
cpu_name, | ||
&cpu.last_total_user, &cpu.last_total_user_low, | ||
&cpu.last_total_sys, &cpu.last_total_idle | ||
); | ||
|
||
if (strstr(cpu_name, "cpu") != cpu_name) | ||
break; | ||
|
||
cpu.gauge = &cpu_usage_family.Add({{ "cpu", std::string(cpu_name) }}); | ||
cpu_usage.insert({ std::string(cpu_name), cpu }); | ||
} | ||
|
||
fclose(file); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Лучше переписать на cpp стиль, не используя функции на Си
src/metrics-collector.cpp
Outdated
FILE *file = fopen("/proc/self/statm", "r"); | ||
if (file == NULL) { | ||
memory_used_gauge->Set(0); | ||
return; | ||
} | ||
|
||
long mem_pages = 0; | ||
fscanf(file, "%ld", &mem_pages); | ||
fclose(file); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Аналогично
src/metrics-collector.cpp
Outdated
|
||
void MetricsCollector::getCPUUsage() | ||
{ | ||
FILE *file = fopen("/proc/stat", "r"); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Аналогично
src/metrics-collector.cpp
Outdated
thread.join(); | ||
} | ||
|
||
void MetricsCollector::getMemoryUsed() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
выглядит как функиця двойного назначения 1) прочитать статы 2) обновить метрики.
если утащить чтение статов в безымянный неймспейс в этом cpp, тогда для однострочника записи метрики отделдьная функция не понадобится вовсе и не будет загрязнять неймспейс класса.
Если хочется юнит тесты сделать для коллектора, то такой метод для получения чего-то из /proc сделать как реализацию интерфейсного метода. А в тестах делать инъекцию зависимости с фейковыми данными.
src/metrics-collector.cpp
Outdated
if (is_task_running) { | ||
struct timespec time; | ||
clock_gettime(CLOCK_MONOTONIC, &time); | ||
task_processing_time_gauge->Set((time.tv_sec - task_start.tv_sec) + (time.tv_nsec - task_start.tv_nsec) * 1e-9); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ещё одно место где стоит подумать о C++ и в частности о std::chrono
src/metrics-collector.cpp
Outdated
{ | ||
is_task_running = false; | ||
task_processing_time_gauge->Set(0); | ||
gateway.PushAdd(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
обилие разного кодестайла...
src/metrics-collector.hpp
Outdated
prometheus::Gauge *memory_used_gauge; | ||
std::unordered_map<std::string, CPUInfo> cpu_usage; | ||
prometheus::Gauge *task_processing_time_gauge; | ||
bool is_running; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- здесь нужен атомик и может даже вообще передавать его из вне чтоб можно было из посикс сигналов ставить (по sigint например).
- кажется при конструировании у нас не было никакой возможности получить здесь значение отличное от true. Видимо можно было сразу здесь и прописать
std::atomic<bool> is_running{true};
src/metrics-collector.hpp
Outdated
|
||
struct CPUInfo { | ||
prometheus::Gauge *gauge; | ||
uint64_t last_total_user; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
а что там за гигантские значения хранятся что uint64 понадобился?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
а что там за гигантские значения хранятся что uint64 понадобился?
Чтобы переполнения реже происходили. Это время, как в выводе time
. А процент использования вычисляется уже как (user+sys) / total
src/hash.cpp
Outdated
} | ||
std::cout << std::endl; | ||
|
||
EVP_cleanup(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
код писался под какую-то древнюю версию openssl?
в любом случае это выглядит плохим решением что-то глобально клинить когда могут быть ещё таски
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А это не мой код, делал чекаут от #4. Там уже всё переписано и замерджено, подолью мейн сюда и не будет этого
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
если чужой код тоже в бранче может тогда и МР делать поверх того бранча? было бы меньше вопросов.
а стек позже схлопнуть когда будут готовы оба.
src/hash.cpp
Outdated
return 0; | ||
} | ||
|
||
int main_metrics(int argc, char* argv[]) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
неплохо бы определиться называть функции камел кейсом или снейком.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Всё это исчезнет и останется один единственный main, когда сюда прикрутится полноценный воркер (#15)
src/hash.cpp
Outdated
return 1; | ||
} | ||
|
||
MetricsCollector metrics_collector(argv[2], argv[3], argv[4]); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
предлагаю для опций использовать это https://www.boost.org/doc/libs/1_88_0/doc/html/program_options/tutorial.html#id-1.3.29.4.3
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Устанавливать целый буст ради одной фичи?
Может лучше передавать все аргументы через env переменные? Удобно будет при запуске докер контейнера их передавать
src/hash.cpp
Outdated
|
||
MetricsCollector metrics_collector(argv[2], argv[3], argv[4]); | ||
|
||
srand(time(NULL)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это тоже исчезнет, когда здесь будет полноценный воркер, а не sleep(random)
.
src/hash.cpp
Outdated
|
||
// some "work" that requires memory | ||
void *data = malloc(rand() % (1024 * 1024 * 50)); // 0 - 50 megabytes | ||
std::this_thread::sleep_for(std::chrono::seconds(rand() % 5 + 1)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sleep_for не помечен как noexcept, значит это место потециальной утечки
92170c1
to
ea2d3e2
Compare
ea2d3e2
to
0329b73
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Нужно исправить конфликт
src/main.cpp
Outdated
} | ||
|
||
int metrics_main(int argc, char *argv[]) { | ||
signal(SIGTERM, signal_handler); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sigaction ?
src/main.cpp
Outdated
} | ||
|
||
|
||
bool is_running = true; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
а чего их теперь два?
надо второй сделать референсом первого а здесь добавить атомик
src/main.cpp
Outdated
#include <thread> | ||
#include <signal.h> | ||
|
||
void print_usage(const std::string& program_name) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
предлагаю засовывать вообще все ненужные для линковки функции в анониммный неймспейс, а не только в юнитах классов
src/main.cpp
Outdated
|
||
int main(int argc, char *argv[]) | ||
{ | ||
static const char usage[] = "Specify hash/metrics"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
src/main.cpp
Outdated
return 1; | ||
} | ||
|
||
if (strcmp(argv[1], "hash") == 0) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
У всех фломастеры разные конечно, но я бы наверное сделал так
std::string_view cmd{argv[1]};
if (cmd == "hash") {
...
или даже
cmd == "hash"sv
src/md_calculator.cpp
Outdated
MDCalculator::MDCalculator(const std::string& algorithm) | ||
: md_(nullptr), ctx_(nullptr, EVP_MD_CTX_free) { | ||
|
||
OpenSSL_add_all_digests(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
как только появится демон с цикличной обработкой, это штука будет только вносить тормоза, если в ней нет внутренней проверки что уже проинициализировано.
src/metrics-collector.cpp
Outdated
if (total_user < cpu.last_total_user || total_user_low < cpu.last_total_user_low || | ||
total_sys < cpu.last_total_sys || total_idle < cpu.last_total_idle) { | ||
// overflow detection | ||
percent = -1.0; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я сделал небольшие подсчеты для своего железа. Для этого понадобится 1+ млрд лет. Думаю система отключится раньше.
Но респект что переполнение вообще пришло в голову.
А вот с точки зрения пользователя -1 это нонсенс.
No description provided.