The post has been translated automatically. Original language: Russian
Imagine a familiar incident: an application stops writing because its filesystem is full. Someone deletes the largest log. Two gigabytes disappear from the directory listing, yet hardly any free space comes back. The obvious suspicion is that the command failed. It did not: the filename really is gone.
In Linux, a filename and an open reference to a file are different things. An application obtains a file descriptor and can keep using the data after the file's last directory entry has been removed. While a process still holds that file open, its storage may remain allocated. Removing the line from the directory listing was not enough.
In this illustrative scenario, the service keeps writing to its old log. An administrator creates an empty file with the previous name and notices that it never grows. Now there is another misleading diagnosis: logging must be broken. The service simply has not switched to the new file. Reusing a name does not redirect an existing open descriptor.
That also explains one common disagreement between two utilities. df reports filesystem space usage, while du measures files reachable through names in the selected directory tree. An unlinked but open log can still count toward the first and disappear from the second. This is one possible cause of a discrepancy, not an explanation for every difference.
For diagnosis, lsof +L1 selects open files whose hard link count is zero. Look at the process, PID and size to identify what is holding the data. The completeness of the list depends on the user's permissions. The command only reports information; it does not free the space.
The next step depends on the application. If it supports reopening its log, use its documented mechanism. Otherwise, arrange a controlled stop or restart after considering interrupted operations. Rebooting an entire server to deal with one log is an unnecessarily broad intervention.
To prevent a recurrence, configure rotation and test it with the application. Even copytruncate has a trade-off: records can be lost in the interval between copying the log and truncating it.
A useful completion check has three observations: the process no longer holds the old log, free space has returned, and new entries appear in the expected file.
Sources: Linux man-pages — unlink(2), lsof(8); GNU Coreutils FAQ; logrotate(8) manual.
Представьте обычную аварию: приложение перестало записывать данные, потому что раздел заполнен. Самый большой журнал удалили — два гигабайта исчезли из списка файлов. А свободного места почти не прибавилось. Первая мысль: команда не сработала. Но файл действительно удалён.
В Linux имя файла и открытый доступ к нему — разные вещи. Программа получает файловый дескриптор и может продолжать работать с данными, даже когда последнее имя файла уже убрали из каталога. Пока процесс держит такой файл открытым, его место не обязательно освобождается. Удалить строку в списке оказалось недостаточно.
В учебном примере сервис продолжает писать в старый журнал. Новый администратор создаёт пустой файл с прежним именем и видит, что тот не растёт. Возникает ещё одна ложная версия: «сломалось логирование». На самом деле сервис не переключился на новый файл. Совпадение имени не перенаправляет уже открытый дескриптор.
Отсюда и знакомый спор двух утилит. df показывает занятость файловой системы, а du оценивает доступные по именам файлы в выбранном дереве. Удалённый, но открытый журнал может учитываться первой и не находиться второй. Это одна из причин расхождения, а не универсальное объяснение любой разницы.
Для диагностики есть команда lsof +L1. Она выбирает открытые файлы с нулевым числом жёстких ссылок. В выводе важны процесс, PID и размер: нужно найти, кто удерживает данные. Полнота списка зависит от прав пользователя. Сама команда только показывает информацию и место не освобождает.
Дальше решение зависит от приложения. Если оно умеет штатно переоткрывать журнал, используют предусмотренный им способ. Иначе согласуют остановку или перезапуск. Прежде нужно понять, какие операции прервутся. Перезагружать весь сервер ради одного журнала — слишком широкое действие.
Чтобы ситуация не повторялась, настраивают ротацию и проверяют её вместе с приложением. Даже copytruncate не даёт бесплатной гарантии: между копированием и обнулением возможна потеря части записей.
Хороший итог проверки — не исчезнувшее имя файла, а три наблюдения: нужный процесс больше не держит старый журнал, свободное место вернулось, новые записи идут в ожидаемый файл.
Источники: Linux man-pages — unlink(2), lsof(8); GNU Coreutils FAQ; руководство logrotate(8).
Comments 0
Newest Popular