From 9a69238a773e55bb0d18f7da04ced4c8a7d17a86 Mon Sep 17 00:00:00 2001 From: evgeny Date: Thu, 29 Oct 2026 11:23:36 +0100 Subject: [PATCH] Add desktop log rotation on startup and size limit --- doc/tasks.md | 5 +- lib/debug_config.c | 225 +++++++++++++++++++++++--- lib/debug_config.h | 15 +- tests/Makefile.am | 4 + tests/test_log_rotation.c | 197 ++++++++++++++++++++++ tools/chatgui/CMakeLists.txt | 3 + tools/chatgui/chatgui_doc.md | 9 ++ tools/chatgui/src/main.cpp | 7 +- tools/chatgui/transport/utun_node.cpp | 1 + 9 files changed, 440 insertions(+), 26 deletions(-) create mode 100644 tests/test_log_rotation.c diff --git a/doc/tasks.md b/doc/tasks.md index e2b430100..f529d74e0 100644 --- a/doc/tasks.md +++ b/doc/tasks.md @@ -4,9 +4,10 @@ ## Текущие задачи -[ ] **Windows: единые UTF-8 пути конфигурации и раннего журнала** — 29.10.2026. - GUI передаёт toUtf8, а config_parser/config_updater/debug_config используют fopen и ANSI Win32 API. +[ ] **Windows: единые UTF-8 пути конфигурации** — 29.10.2026. + GUI передаёт toUtf8, а config_parser/config_updater используют fopen и ANSI Win32 API. Перевести эти операции на существующий file_io с wide-путями, проверить профиль в каталоге с кириллицей. + Пути журнала исправлены при добавлении ротации: wide open/rename/remove, проверены Windows-тестом через Wine. Это отдельный риск; причиной отказа присланного 2.log на Windows он не подтверждён. [+] **Вложения: отправка независимо от лимита автозагрузки, метаданные фото/видео и результат GUI** — 28.10.2026. diff --git a/lib/debug_config.c b/lib/debug_config.c index 0374964e5..15cd77da1 100644 --- a/lib/debug_config.c +++ b/lib/debug_config.c @@ -12,6 +12,10 @@ #include #include #include +#include +#ifndef _WIN32 +#include +#endif void log_dump(int level, int category, const char* prefix, const uint8_t* data, size_t len) { if (!debug_should_output(level, category)) return; @@ -219,8 +223,151 @@ const char* debug_get_category_name(debug_category_t category_idx) { debug_config_t g_debug_config; static debug_log_hook_fn g_log_hook = NULL; +/* Запись/смена FILE и ротация сериализованы: fclose не пересекается с чужим fwrite. + * Файловый код logger-а не вызывает file_io/DEBUG_* под lock: они сами логируют ошибки. */ +#ifdef _WIN32 +static SRWLOCK log_mutex = SRWLOCK_INIT; +#define LOG_LOCK() AcquireSRWLockExclusive(&log_mutex) +#define LOG_UNLOCK() ReleaseSRWLockExclusive(&log_mutex) +#else +static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER; +#define LOG_LOCK() pthread_mutex_lock(&log_mutex) +#define LOG_UNLOCK() pthread_mutex_unlock(&log_mutex) +#endif +#define LOG_PATH_MAX 4096 +static uint64_t log_bytes, log_limit, log_rotate_at; +static unsigned log_files; + +#ifdef _WIN32 +static int log_wide_path(const char* path, wchar_t wide[LOG_PATH_MAX]) { + if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, path, -1, wide, LOG_PATH_MAX)) return 0; + errno = EINVAL; + return -1; +} +#endif + +static FILE* log_open(const char* path, int truncate, uint64_t* bytes) { + if (!path || !*path || strlen(path) >= LOG_PATH_MAX - 4) { errno = ENAMETOOLONG; return NULL; } +#ifdef _WIN32 + wchar_t wide[LOG_PATH_MAX]; + if (log_wide_path(path, wide)) return NULL; + FILE* file = _wfopen(wide, truncate ? L"wb" : L"ab"); + struct _stat64 info; + int result = file ? _fstat64(_fileno(file), &info) : -1; +#else + FILE* file = fopen(path, truncate ? "wb" : "ab"); + struct stat info; + int result = file ? fstat(fileno(file), &info) : -1; +#endif + if (!file) return NULL; + if (result) { int error = errno; fclose(file); errno = error; return NULL; } + *bytes = info.st_size > 0 ? (uint64_t)info.st_size : 0; + return file; +} + +static int log_remove(const char* path) { +#ifdef _WIN32 + wchar_t wide[LOG_PATH_MAX]; + if (log_wide_path(path, wide)) return -1; + return _wremove(wide); +#else + return remove(path); +#endif +} + +static int log_rename(const char* from, const char* to) { +#ifdef _WIN32 + wchar_t source[LOG_PATH_MAX], destination[LOG_PATH_MAX]; + if (log_wide_path(from, source) || log_wide_path(to, destination)) return -1; + return _wrename(source, destination); +#else + return rename(from, to); +#endif +} + +/* Ошибку logger-а пишем напрямую, без рекурсии, в stderr и доступный текущий лог. */ +static void log_io_error(const char* phase, const char* path, int error) { + char message[1024]; + snprintf(message, sizeof(message), "[ERROR] [sys] log %s failed: path=%s errno=%d (%s)\n", phase, path, error, strerror(error)); + fputs(message, stderr); fflush(stderr); + if (g_debug_config.file_output) { + log_bytes += fwrite(message, 1, strlen(message), g_debug_config.file_output); + fflush(g_debug_config.file_output); + } +} + +/* Под lock, без проверок размера на диске. Пустые файлы не занимают поколения. */ +static int log_rotate(const char* trigger) { + if (!log_bytes) return 0; + uint64_t previous_size = log_bytes; + const char* path = g_debug_config.output_file; + char from[LOG_PATH_MAX], to[LOG_PATH_MAX]; + const char* phase = "rotate close"; + int error = 0; + FILE* old = g_debug_config.file_output; + g_debug_config.file_output = NULL; + if (fclose(old)) { error = errno; goto reopen; } + if (log_files > 1) { + snprintf(to, sizeof(to), "%s.%u", path, log_files - 1); + phase = "rotate remove oldest"; + if (log_remove(to) && errno != ENOENT) { error = errno; goto reopen; } + for (unsigned i = log_files - 1; i > 1; --i) { + snprintf(from, sizeof(from), "%s.%u", path, i - 1); + snprintf(to, sizeof(to), "%s.%u", path, i); + phase = "rotate rename generation"; + if (log_rename(from, to) && errno != ENOENT) { error = errno; goto reopen; } + } + snprintf(to, sizeof(to), "%s.1", path); + phase = "rotate rename current"; + if (log_rename(path, to)) { error = errno; goto reopen; } + } +reopen: + g_debug_config.file_output = log_open(path, !error && log_files == 1, &log_bytes); + if (!g_debug_config.file_output) { + log_io_error("rotate reopen", path, errno); + g_debug_config.console_enabled = 1; + return -1; + } + if (error) log_io_error(phase, path, error); + else if (debug_should_output(DEBUG_LEVEL_INFO, DEBUG_CATEGORY_SYS)) { + char message[192]; + int size = snprintf(message, sizeof(message), "[INFO] [sys] Log rotated: trigger=%s previous_bytes=%llu files=%u\n", + trigger, (unsigned long long)previous_size, log_files); + log_bytes += fwrite(message, 1, (size_t)size, g_debug_config.file_output); + if (fflush(g_debug_config.file_output)) log_io_error("flush rotation notice", path, errno); + } + /* При ошибке не повторяем файловые операции на каждой строке: ещё limit байтов до попытки. */ + log_rotate_at = error ? log_bytes + log_limit : log_limit; + return error ? -1 : 0; +} + +int debug_set_file_rotation(uint64_t max_bytes, unsigned file_count) { + if (max_bytes && (max_bytes < 4096 || max_bytes > UINT64_MAX / 2 || !file_count || file_count > 99)) { + DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Invalid log rotation: bytes=%llu files=%u", (unsigned long long)max_bytes, file_count); + return -1; + } + LOG_LOCK(); + log_limit = max_bytes; log_files = file_count; log_rotate_at = max_bytes; + LOG_UNLOCK(); + return 0; +} + +int debug_rotate_log(void) { + LOG_LOCK(); + if (!log_limit || !g_debug_config.file_output) { + LOG_UNLOCK(); + DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Cannot rotate log: file output or rotation is disabled"); + return -1; + } + int result = log_rotate("startup/manual"); + LOG_UNLOCK(); + return result; +} + /* Initialize debug system with default settings */ void debug_config_init(void) { + LOG_LOCK(); + log_bytes = log_limit = log_rotate_at = 0; log_files = 0; g_debug_config.level = DEBUG_LEVEL_ERROR; // Global level: errors only by default for (int i = 0; i < DEBUG_CATEGORY_COUNT; i++) { g_debug_config.category_levels[i] = DEBUG_LEVEL_NONE; // 0 = disabled per category @@ -234,6 +381,7 @@ void debug_config_init(void) { g_debug_config.file_output = NULL; // No file by default g_debug_config.console_enabled = 1; // Console enabled g_debug_config.thread_marker = 0; // No thread marker by default + LOG_UNLOCK(); } /* Set debug level */ @@ -285,12 +433,18 @@ void debug_enable_file_line(int enable) { } void debug_set_output_file(const char* file_path) { - if (g_debug_config.file_output) return;// уже установлен, кто первый того и тапки - FILE* new_file = fopen(file_path, "a"); + if (!file_path) return; + LOG_LOCK(); + if (g_debug_config.file_output) { LOG_UNLOCK(); return; } + FILE* new_file = log_open(file_path, 0, &log_bytes); if (new_file) { g_debug_config.file_output = new_file; g_debug_config.output_file = file_path; + log_rotate_at = log_limit; } + int error = errno; + LOG_UNLOCK(); + if (!new_file) DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Cannot open log '%s': %s", file_path, strerror(error)); } /* Set console log level */ @@ -301,50 +455,61 @@ void debug_enable_console(int enable) { /* Enable file output with optional truncation */ void debug_enable_file_output(const char* file_path, int truncate) { if (!file_path) return; - - // Close existing file if open - if (g_debug_config.file_output) { - fclose(g_debug_config.file_output); - g_debug_config.file_output = NULL; - } - - // Open new file - const char* mode = truncate ? "w" : "a"; - FILE* new_file = fopen(file_path, mode); + LOG_LOCK(); + uint64_t bytes; + FILE* new_file = log_open(file_path, truncate, &bytes); + int error = errno; if (new_file) { + FILE* old = g_debug_config.file_output; g_debug_config.file_output = new_file; g_debug_config.output_file = file_path; g_debug_config.console_enabled = 0; + log_bytes = bytes; log_rotate_at = log_limit; + if (old && fclose(old)) log_io_error("close previous", file_path, errno); } + LOG_UNLOCK(); + if (!new_file) DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Cannot open log '%s': %s", file_path, strerror(error)); } /* Disable file output */ void debug_disable_file_output(void) { + LOG_LOCK(); if (g_debug_config.file_output) { - fclose(g_debug_config.file_output); + FILE* old = g_debug_config.file_output; g_debug_config.file_output = NULL; - g_debug_config.output_file = NULL; + if (fclose(old)) log_io_error("close", g_debug_config.output_file, errno); } + g_debug_config.output_file = NULL; log_bytes = 0; + LOG_UNLOCK(); } /* Переоткрыть лог в append-режиме; при ошибке открытия сохранить прежний поток. */ int debug_reopen_log(void) { + LOG_LOCK(); if (!g_debug_config.output_file) { + LOG_UNLOCK(); DEBUG_WARN(DEBUG_CATEGORY_CONFIG, "No log path for reopen"); return -1; } const char* path = g_debug_config.output_file; - FILE* new_file = fopen(path, "a"); + uint64_t bytes; + FILE* new_file = log_open(path, 0, &bytes); if (!new_file) { - DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Cannot reopen log '%s': %s", path, strerror(errno)); + int error = errno; + LOG_UNLOCK(); + DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Cannot reopen log '%s': %s", path, strerror(error)); return -1; } FILE* old_file = g_debug_config.file_output; g_debug_config.file_output = new_file; + log_bytes = bytes; log_rotate_at = log_limit; if (old_file && fclose(old_file) != 0) { - DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Cannot close previous log '%s': %s", path, strerror(errno)); + int error = errno; + LOG_UNLOCK(); + DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Cannot close previous log '%s': %s", path, strerror(error)); return -1; } + LOG_UNLOCK(); DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Log reopened: %s", path); return 0; } @@ -408,9 +573,14 @@ void debug_output(debug_level_t level, debug_category_t category_idx, struct timeval tv; utun_gettimeofday(&tv, NULL); time_t tv_sec = (time_t)tv.tv_sec; - struct tm* tm_info = localtime(&tv_sec); + struct tm tm_info; +#ifdef _WIN32 + localtime_s(&tm_info, &tv_sec); +#else + localtime_r(&tv_sec, &tm_info); +#endif char time_str[32]; - strftime(time_str, sizeof(time_str), "%H:%M:%S", tm_info); + strftime(time_str, sizeof(time_str), "%H:%M:%S", &tm_info); BUF_ADVANCE(snprintf(buffer + offset, remaining, "[%s-%03ld.%03ld] ", time_str, tv.tv_usec / 1000, tv.tv_usec % 1000)); } @@ -461,13 +631,26 @@ void debug_output(debug_level_t level, debug_category_t category_idx, } /* Output to console if enabled and level is sufficient */ + LOG_LOCK(); + if (g_debug_config.file_output && log_limit && log_bytes >= log_rotate_at) log_rotate("size"); if (g_debug_config.file_output) { - fprintf(g_debug_config.file_output, "%s", buffer); - fflush(g_debug_config.file_output); + size_t size = strlen(buffer); + size_t written = fwrite(buffer, 1, size, g_debug_config.file_output); + log_bytes += written; + if (fflush(g_debug_config.file_output) || written != size) { + /* Не пытаемся снова писать в неисправный FILE и не теряем диагностику следующей строки. */ + int error = errno; + FILE* broken = g_debug_config.file_output; g_debug_config.file_output = NULL; + log_io_error("write", g_debug_config.output_file, error); + if (fclose(broken)) log_io_error("close after write error", g_debug_config.output_file, errno); + g_debug_config.console_enabled = 1; + fputs(buffer, stderr); fflush(stderr); + } } else if (g_debug_config.console_enabled) { fprintf(stdout, "%s", buffer); fflush(stdout); } + LOG_UNLOCK(); #undef BUFFER_SIZE } diff --git a/lib/debug_config.h b/lib/debug_config.h index 0191f571f..d8fe25bdb 100644 --- a/lib/debug_config.h +++ b/lib/debug_config.h @@ -6,7 +6,7 @@ * Пример: debug_config_init(); debug_set_level(DEBUG_LEVEL_INFO); debug_parse_config("etcp=trace,config=info"). * DEBUG_* фильтруют до форматирования; прямой debug_output фильтр не проверяет. * Строка с префиксами ограничена буфером 4096 байт и обрезается; каждый вывод fflush. - * Модуль и смена глобальных настроек/файлов не синхронизированы; параллельный доступ согласует владелец. + * Запись/смена файла и ротация синхронизированы; уровни/настройки форматирования согласует владелец. */ #ifndef DEBUG_CONFIG_H @@ -132,8 +132,19 @@ void debug_enable_file_line(int enable); void debug_set_output_file(const char* file_path); /* Заменить файл: truncate != 0 → обрезать, иначе append. NULL ничего не меняет. - * Путь заимствован; успешное открытие также выключает console_enabled. */ + * Путь UTF-8 заимствован; успешное открытие выключает console_enabled; при отказе прежний FILE сохраняется. */ void debug_enable_file_output(const char* file_path, int truncate); +/* Ротация выключена после init. max_bytes=0 выключает; иначе >=4096, file_count=1..99 + * включая текущий файл. После примерно max_bytes: path → path.1 → ...; последний удаляется. + * Только rename/remove, без сжатия. Строки не разрываются: превышение до одной строки. + * Размер читается только при открытии; далее счётчик записанных байтов. Один процесс владеет путём. + * 0/-1; повторная настройка и reopen сами по себе не ротируют. */ +int debug_set_file_rotation(uint64_t max_bytes, unsigned file_count); +/* Начать новый лог немедленно (например, при запуске приложения); 0/-1. + * Нужны открытый файл и включённая ротация; пустой файл не создаёт пустое поколение. + * Ошибка ротации логируется; по возможности продолжается append, повтор через max_bytes. */ +int debug_rotate_log(void); + /* Закрыть файл; прежнее значение console_enabled не восстанавливается. */ void debug_disable_file_output(void); /* Переоткрыть текущий путь в append-режиме: 0 — успех, -1 — ошибка с диагностикой. diff --git a/tests/Makefile.am b/tests/Makefile.am index c73e7f3dd..7f255cd73 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -28,6 +28,7 @@ check_PROGRAMS = \ bench_timeout_heap \ test_config_debug \ test_debug_categories \ + test_log_rotation \ test_etcp_bbr \ test_packet_dump \ test_radio_vad \ @@ -838,6 +839,9 @@ test_debug_categories_SOURCES = test_debug_categories.c test_debug_categories_CFLAGS = -I$(top_srcdir)/src -I$(top_srcdir)/lib test_debug_categories_LDADD = $(COMMON_LIBS) +test_log_rotation_SOURCES = test_log_rotation.c +test_log_rotation_LDADD = $(COMMON_LIBS) + test_config_debug_SOURCES = test_config_debug.c test_config_debug_CFLAGS = -I$(top_srcdir)/src -I$(top_srcdir)/lib test_config_debug_LDADD = $(LIBUTUN) $(COMMON_LIBS) diff --git a/tests/test_log_rotation.c b/tests/test_log_rotation.c new file mode 100644 index 000000000..dcaaf70e7 --- /dev/null +++ b/tests/test_log_rotation.c @@ -0,0 +1,197 @@ +/* Реальные файлы: лимит/поколения, новый запуск, reopen, UTF-8 пути, потоки и отказ rename/remove. */ +#ifdef NDEBUG +#undef NDEBUG +#endif +#include "test_utils.h" +#include "../lib/debug_config.h" +#include +#include +#include +#include + +static char directory[512] = "/tmp/utun-log-XXXXXX"; +static char path[1024]; + +static FILE* open_file(const char* name, const char* mode) { +#ifdef _WIN32 + wchar_t wide[2048], wide_mode[16]; + assert(MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, name, -1, wide, 2048)); + assert(MultiByteToWideChar(CP_UTF8, 0, mode, -1, wide_mode, 16)); + return _wfopen(wide, wide_mode); +#else + return fopen(name, mode); +#endif +} + +static void remove_file(const char* name) { +#ifdef _WIN32 + wchar_t wide[2048]; + assert(MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, name, -1, wide, 2048)); + int result = _wremove(wide); +#else + int result = remove(name); +#endif + assert(!result || errno == ENOENT); +} + +static void filename(char* name, size_t size, unsigned generation) { + if (generation) snprintf(name, size, "%s.%u", path, generation); + else snprintf(name, size, "%s", path); +} + +static size_t contents(unsigned generation, char* text, size_t capacity) { + char name[1100]; filename(name, sizeof(name), generation); + FILE* file = open_file(name, "rb"); + if (!file) { assert(errno == ENOENT); text[0] = 0; return 0; } + size_t size = fread(text, 1, capacity - 1, file); + assert(!ferror(file) && feof(file)); assert(!fclose(file)); text[size] = 0; + return size; +} + +static void setup(const char* name, unsigned files) { + snprintf(path, sizeof(path), "%s/%s", directory, name); + debug_config_init(); debug_set_level(DEBUG_LEVEL_INFO); + debug_enable_timestamp(0); debug_enable_file_line(0); debug_enable_function_name(0); + assert(!debug_set_file_rotation(4096, files)); + debug_enable_file_output(path, 0); assert(g_debug_config.file_output); +} + +static void cleanup(void) { + debug_disable_file_output(); + for (unsigned i = 0; i < 100; ++i) { char name[1100]; filename(name, sizeof(name), i); remove_file(name); } +} + +static void retention(void) { + setup("журнал.log", 5); + char payload[3501]; memset(payload, 'x', sizeof(payload) - 1); payload[sizeof(payload) - 1] = 0; + for (int i = 0; i < 20; ++i) DEBUG_INFO(DEBUG_CATEGORY_SYS, "record=%02d %s", i, payload); + debug_disable_file_output(); + int expected = 10; + for (int generation = 4; generation >= 0; --generation) { + char text[9000]; size_t size = contents(generation, text, sizeof(text)); + assert(size >= 4096 && size <= 4096 + 4095); + char* line = text; + if (strstr(line, "Log rotated:") == line + strlen("[INFO] [sys] ")) line = strchr(line, '\n') + 1; + for (int n = 0; n < 2; ++n) { + int number = -1; assert(sscanf(line, "[INFO] [sys] record=%d", &number) == 1 && number == expected++); + char* end = strchr(line, '\n'); assert(end); line = end + 1; + } + assert(!*line); + } + char text[9000]; assert(!contents(5, text, sizeof(text))); + cleanup(); +} + +static void startup_and_reopen(void) { + for (int run = 0; run < 8; ++run) { + setup("startup.log", 5); + assert(!debug_rotate_log()); + DEBUG_INFO(DEBUG_CATEGORY_SYS, "launch=%d", run); + debug_disable_file_output(); + } + for (unsigned i = 0; i < 5; ++i) { + char text[9000], marker[32]; assert(contents(i, text, sizeof(text))); + snprintf(marker, sizeof(marker), "launch=%u", 7 - i); assert(strstr(text, marker)); + } + cleanup(); + setup("reopen.log", 5); + DEBUG_INFO(DEBUG_CATEGORY_SYS, "first"); + debug_enable_file_output(path, 0); assert(!debug_reopen_log()); + DEBUG_INFO(DEBUG_CATEGORY_SYS, "second"); + char text[9000]; assert(contents(0, text, sizeof(text)) && strstr(text, "first") && strstr(text, "second")); + assert(!contents(1, text, sizeof(text))); + cleanup(); +} + +static void* writer(void* arg) { + int thread = (int)(intptr_t)arg; + char payload[801]; memset(payload, 'a' + thread, sizeof(payload) - 1); payload[sizeof(payload) - 1] = 0; + for (int n = 0; n < 20; ++n) DEBUG_INFO(DEBUG_CATEGORY_SYS, "thread=%d record=%d %s", thread, n, payload); + return NULL; +} + +static void* reopener(void* arg) { + (void)arg; + for (int n = 0; n < 20; ++n) assert(!debug_reopen_log()); + return NULL; +} + +static void concurrent_writes(void) { + setup("threads.log", 99); + pthread_t threads[5]; + for (int i = 0; i < 4; ++i) assert(!pthread_create(&threads[i], NULL, writer, (void*)(intptr_t)i)); + assert(!pthread_create(&threads[4], NULL, reopener, NULL)); + for (int i = 0; i < 5; ++i) assert(!pthread_join(threads[i], NULL)); + debug_disable_file_output(); + int seen[4][20] = {{0}}, count = 0; + for (unsigned generation = 0; generation < 99; ++generation) { + char text[10000]; if (!contents(generation, text, sizeof(text))) continue; + for (char* line = text; *line;) { + char* end = strchr(line, '\n'); assert(end); *end = 0; + if (strstr(line, "thread=")) { + int thread, record, offset = 0; + assert(sscanf(line, "[INFO] [sys] thread=%d record=%d %n", &thread, &record, &offset) == 2); + assert(thread >= 0 && thread < 4 && record >= 0 && record < 20 && !seen[thread][record]++); + assert(strlen(line + offset) == 800); + for (char* p = line + offset; *p; ++p) assert(*p == 'a' + thread); + ++count; + } + line = end + 1; + } + } + assert(count == 80); + cleanup(); +} + +static void rotation_failure(void) { + setup("failure.log", 5); + char blocked[1100], child[1200]; filename(blocked, sizeof(blocked), 4); +#ifdef _WIN32 + assert(!_mkdir(blocked)); +#else + assert(!mkdir(blocked, 0700)); +#endif + snprintf(child, sizeof(child), "%s/keep", blocked); + FILE* file = open_file(child, "wb"); assert(file && !fclose(file)); + DEBUG_INFO(DEBUG_CATEGORY_SYS, "before failure"); + assert(debug_rotate_log() == -1); + DEBUG_INFO(DEBUG_CATEGORY_SYS, "after failure"); + char text[9000]; assert(contents(0, text, sizeof(text))); + assert(strstr(text, "before failure") && strstr(text, "after failure") && strstr(text, "rotate remove oldest failed")); + remove_file(child); assert(!test_rmdir(blocked)); + assert(!debug_rotate_log()); + DEBUG_INFO(DEBUG_CATEGORY_SYS, "recovered"); + assert(contents(1, text, sizeof(text)) && strstr(text, "before failure")); + assert(contents(0, text, sizeof(text)) && strstr(text, "recovered")); + cleanup(); +} + +#ifdef _WIN32 +static void windows_reader_blocks_rename(void) { + setup("held.log", 5); + DEBUG_INFO(DEBUG_CATEGORY_SYS, "before locked rename"); + wchar_t wide[2048]; + assert(MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, path, -1, wide, 2048)); + HANDLE reader = CreateFileW(wide, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + assert(reader != INVALID_HANDLE_VALUE); + assert(debug_rotate_log() == -1); + DEBUG_INFO(DEBUG_CATEGORY_SYS, "after locked rename"); + char text[9000]; assert(contents(0, text, sizeof(text))); + assert(strstr(text, "before locked rename") && strstr(text, "after locked rename") && strstr(text, "rotate rename current failed")); + assert(CloseHandle(reader)); + assert(!debug_rotate_log()); + assert(contents(1, text, sizeof(text)) && strstr(text, "after locked rename")); + cleanup(); +} +#endif + +int main(void) { + assert(!test_mkdtemp(directory)); + retention(); startup_and_reopen(); concurrent_writes(); rotation_failure(); +#ifdef _WIN32 + windows_reader_blocks_rename(); +#endif + assert(!test_rmdir(directory)); + puts("PASS log rotation: size, five files, startup, reopen, UTF-8, concurrent writers, failure recovery"); + return 0; +} diff --git a/tools/chatgui/CMakeLists.txt b/tools/chatgui/CMakeLists.txt index 233d83cec..81333153e 100644 --- a/tools/chatgui/CMakeLists.txt +++ b/tools/chatgui/CMakeLists.txt @@ -488,6 +488,9 @@ endif() # ============================================================================ enable_testing() +add_executable(test_log_rotation ../../tests/test_log_rotation.c) +target_link_libraries(test_log_rotation PRIVATE uasync pthread) +add_test(NAME test_log_rotation COMMAND test_log_rotation) add_executable(test_channel_delegate tests/test_channel_delegate.cpp src/channeldelegate.cpp) target_link_libraries(test_channel_delegate PRIVATE ${QT_LIBS} ${QT_TEST_LIB} utun pthread ${CMAKE_DL_LIBS}) diff --git a/tools/chatgui/chatgui_doc.md b/tools/chatgui/chatgui_doc.md index 37f0a93ae..b4b364d3b 100644 --- a/tools/chatgui/chatgui_doc.md +++ b/tools/chatgui/chatgui_doc.md @@ -148,3 +148,12 @@ Linux-тесты команд используют allocation hooks и null audi Это позволяет проверить очередь, native trampolines, SQLite и QWidget без физических audio devices. Категории диагностики определяются `lib/debug_config.h`; используйте уровни config/chat/dm/media/radio/sys для ошибок, при проверке состояний повышайте нужную категорию до debug. + +Desktop Linux/Windows хранит текущий лог и четыре предыдущих файла (`chatgui.log.1`–`.4`; +для собственного `debug_file` используются такие же суффиксы). При запуске приложения +предыдущий непустой лог переименовывается; внутренний restart ядра и reopen не создают поколение. +Во время работы ротация происходит примерно через 10 MiB, без разрыва строк, с удалением самого старого файла. +Сжатия нет. Размер читается только при открытии, затем учитываются записанные байты. +Запись/ротация сериализованы между потоками. На Windows используются Unicode-пути. +При ошибке переименования продолжается append, повтор — через следующие 10 MiB; причина пишется в лог/stderr. +Проверка: `ctest --test-dir tools/chatgui/build -R '^test_log_rotation$' --output-on-failure`. diff --git a/tools/chatgui/src/main.cpp b/tools/chatgui/src/main.cpp index 2865662da..f9beb08a7 100644 --- a/tools/chatgui/src/main.cpp +++ b/tools/chatgui/src/main.cpp @@ -170,8 +170,11 @@ int main(int argc, char *argv[]) { } /* Ошибка подготовки INI возможна ещё до чтения debug_file из профиля. */ - const QByteArray startupLogPath = (cfgDir + "/chatgui.log").toUtf8(); + const QString startupLogFile = cfgDir + "/chatgui.log"; + const QByteArray startupLogPath = startupLogFile.toUtf8(); + debug_set_file_rotation(10 * 1024 * 1024, 5); debug_enable_file_output(startupLogPath.constData(), 0); + if (g_debug_config.file_output) debug_rotate_log(); DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "GUI startup: version=%s config_directory=%s", qPrintable(app.applicationVersion()), qPrintable(cfgDir)); #ifdef _WIN32 DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Windows storage selection: %s", qPrintable(storageReason)); @@ -344,6 +347,8 @@ int main(int argc, char *argv[]) { debug_enable_function_name(0); const QByteArray debugFilePath = debugFile.toUtf8(); // Logger заимствует путь до закрытия/замены файла. debug_enable_file_output(debugFilePath.constData(), 0); + if (g_debug_config.output_file == debugFilePath.constData() && + QFileInfo(debugFile).canonicalFilePath() != QFileInfo(startupLogFile).canonicalFilePath()) debug_rotate_log(); QString lvl = cfg.debugLevel().trimmed(); if (lvl.isEmpty()) lvl = QStringLiteral("info"); debug_apply_global_level(lvl.toUtf8().constData()); diff --git a/tools/chatgui/transport/utun_node.cpp b/tools/chatgui/transport/utun_node.cpp index b4c380e04..a9e8de2a0 100644 --- a/tools/chatgui/transport/utun_node.cpp +++ b/tools/chatgui/transport/utun_node.cpp @@ -210,6 +210,7 @@ void UtunNode::runLoop(std::promise startup) { // Повторный init не закрывает прежний FILE; путь прошлого запуска пока ещё жив. debug_disable_file_output(); debug_config_init(); + debug_set_file_rotation(10 * 1024 * 1024, 5); debug_enable_function_name(0); /* ── debug level from config ── */