A set of bash scripts and a simple Cockpit plugin for monitoring the md0 array, reading logs, cleaning old log files, and running maintenance actions manually from a web UI.
Russian version: jump to the Russian section
This project contains two parts:
- A script bundle for monitoring and maintaining
md0 - A Cockpit plugin for viewing status, logs, and launching actions
It is designed for a simple home or small NAS setup based on mdadm, with minimal moving parts and without requiring a full systemd-based workflow.
Files:
check_raid.shraid_scrub.shraid_scrub_bg.shscrub_stop.shcleanup_raid_logs.sh
Main daily check script.
What it does:
- checks the state of the
md0array withmdadm - discovers current member disks
- reads key SMART attributes from array disks
- writes daily logs
- launches scrub when needed
- tracks incomplete scrub state using a flag file
Logs:
md0_YYYY-MM-DD.log— RAID array statesmart_YYYY-MM-DD.log— SMART checksscrub_YYYY-MM-DD.log— scrub decisions and actions
State files:
.last_smart— last saved SMART state.scrub_incomplete— incomplete scrub flag.last_scrub_ym— last successfully completed monthly scrub marker
Starts check on md0 and monitors progress until completion.
What it does:
- checks whether the array is active
- prevents parallel scrub execution
- logs scrub progress
- preserves the incomplete scrub flag if interrupted
- clears the flag and updates the monthly stamp after a successful finish
Background wrapper for raid_scrub.sh.
What it does:
- avoids nearly simultaneous duplicate launches
- starts
raid_scrub.shvianohup - writes launch information into the log
Graceful manual scrub stop helper.
What it does:
- shows current progress
- waits for the current chunk to finish when possible
- switches
sync_actiontoidle - preserves the incomplete scrub flag for later continuation
Simple log cleanup helper for the date-based log scheme.
What it does:
- compresses plain
*.logfiles older than 7 days - removes compressed
*.log.gzfiles older than 90 days - ignores hidden state files such as:
.last_smart.scrub_incomplete.last_scrub_ym
Why it is compatible with the current setup:
- your logs already rotate naturally by date in the filename
- this script only handles stale log files
- it does not touch the current day's files or the state/flag files
Recommended location:
/usr/local/sbin/cleanup_raid_logs.shExample content:
#!/bin/bash
set -euo pipefail
LOG_DIR="/var/log/raid"
[ -d "$LOG_DIR" ] || exit 0
find "$LOG_DIR" -maxdepth 1 -type f -name '*.log' -mtime +7 -exec gzip -f {} \;
find "$LOG_DIR" -maxdepth 1 -type f -name '*.log.gz' -mtime +90 -deleteOptional daily cron entry:
/etc/cron.daily/cleanup-raid-logswith:
#!/bin/sh
/usr/local/sbin/cleanup_raid_logs.shThe plugin adds a RAID Tools page to Cockpit.
It shows:
mdadm --detail /dev/md0- contents of
.last_smart - latest lines from the
md0log - latest lines from the
smartlog - latest lines from the
scrublog
It can launch:
check_raid.shraid_scrub_bg.shscrub_stop.shcleanup_raid_logs.sh
Features:
- if today's log does not exist yet, the plugin falls back to the latest available log
- long log lines are shown without forced wrapping
- existing host scripts are called directly, without requiring a systemd service/unit migration
- Linux
bashmdadmsmartctl- an
md0RAID array - root privileges
- installed and working
cockpit - administrative access for running commands as root
- scripts available in
/usr/local/sbin/
/usr/local/sbin/check_raid.sh
/usr/local/sbin/raid_scrub.sh
/usr/local/sbin/raid_scrub_bg.sh
/usr/local/sbin/scrub_stop.sh
/usr/local/sbin/cleanup_raid_logs.shPermissions:
chmod +x /usr/local/sbin/check_raid.sh
chmod +x /usr/local/sbin/raid_scrub.sh
chmod +x /usr/local/sbin/raid_scrub_bg.sh
chmod +x /usr/local/sbin/scrub_stop.sh
chmod +x /usr/local/sbin/cleanup_raid_logs.sh# check raid health
0 0 * * * root /usr/local/sbin/check_raid.sh
@reboot root sleep 60 && /usr/local/sbin/check_raid.shOptional cleanup:
# /etc/cron.daily/cleanup-raid-logs
/usr/local/sbin/cleanup_raid_logs.shBy default, logs are written to:
/var/log/raid/Typical files:
md0_YYYY-MM-DD.logsmart_YYYY-MM-DD.logscrub_YYYY-MM-DD.log
State files:
/var/log/raid/.last_smart/var/log/raid/.scrub_incomplete/var/log/raid/.last_scrub_ym
If you already have the raidtools/ plugin directory:
sudo rm -rf /usr/local/share/cockpit/raidtools
sudo mkdir -p /usr/local/share/cockpit/raidtools
sudo cp -r raidtools/* /usr/local/share/cockpit/raidtools/Then reload the Cockpit page in your browser.
The project is intentionally lightweight and practical.
Main goals:
- see RAID state every day
- keep a simple SMART history
- control monthly scrub behavior
- run or stop checks manually
- clean old logs safely
- view everything from Cockpit without extra complexity
Initial implementation and iterative refinement were created with ChatGPT assistance.
MIT License. See LICENSE.
Набор bash-скриптов и простой плагин для Cockpit для контроля массива md0, просмотра логов, очистки старых лог-файлов и ручного запуска обслуживания из веб-интерфейса.
Проект состоит из двух частей:
- Комплект скриптов для контроля и обслуживания
md0 - Плагин Cockpit для просмотра состояния, логов и запуска действий
Проект задуман как лёгкий набор инструментов для домашнего или небольшого NAS на mdadm, без лишней обвязки и без обязательного перевода всего в systemd.
Файлы:
check_raid.shraid_scrub.shraid_scrub_bg.shscrub_stop.shcleanup_raid_logs.sh
Основной ежедневный скрипт проверки.
Что делает:
- проверяет состояние массива
md0черезmdadm - определяет текущие диски массива
- читает ключевые SMART-атрибуты дисков
- пишет ежедневные логи
- при необходимости запускает scrub
- отслеживает незавершённый scrub через флаг
Логи:
md0_YYYY-MM-DD.log— состояние массиваsmart_YYYY-MM-DD.log— SMART-проверкаscrub_YYYY-MM-DD.log— решения и действия по scrub
Служебные файлы:
.last_smart— последнее сохранённое состояние SMART.scrub_incomplete— флаг незавершённого scrub.last_scrub_ym— отметка последнего успешно завершённого ежемесячного scrub
Запускает check для массива md0 и отслеживает прогресс до завершения.
Что делает:
- проверяет, активен ли массив
- не допускает параллельный запуск второго scrub
- пишет прогресс в лог
- сохраняет флаг незавершённого scrub при прерывании
- снимает флаг и обновляет месячную отметку после успешного завершения
Обёртка для фонового запуска raid_scrub.sh.
Что делает:
- защищает от почти одновременного повторного старта
- запускает
raid_scrub.shчерезnohup - пишет запуск в лог
Аккуратная ручная остановка scrub.
Что делает:
- показывает текущий прогресс
- по возможности ждёт завершения текущего chunk
- переводит
sync_actionвidle - сохраняет флаг незавершённого scrub для последующего продолжения
Простой скрипт очистки логов для схемы с датой в имени файла.
Что делает:
- сжимает обычные
*.logстарше 7 дней - удаляет сжатые
*.log.gzстарше 90 дней - не трогает скрытые служебные файлы, такие как:
.last_smart.scrub_incomplete.last_scrub_ym
Почему он совместим с текущей схемой:
- у тебя логи уже естественно “ротируются” по дате в имени файла
- этот скрипт работает только со старыми логами
- он не трогает текущие дневные файлы и не затрагивает служебные state/flag файлы
Рекомендуемое размещение:
/usr/local/sbin/cleanup_raid_logs.shПример содержимого:
#!/bin/bash
set -euo pipefail
LOG_DIR="/var/log/raid"
[ -d "$LOG_DIR" ] || exit 0
find "$LOG_DIR" -maxdepth 1 -type f -name '*.log' -mtime +7 -exec gzip -f {} \;
find "$LOG_DIR" -maxdepth 1 -type f -name '*.log.gz' -mtime +90 -deleteНеобязательный ежедневный запуск:
/etc/cron.daily/cleanup-raid-logsс содержимым:
#!/bin/sh
/usr/local/sbin/cleanup_raid_logs.shПлагин добавляет страницу RAID Tools в Cockpit.
Что показывает:
mdadm --detail /dev/md0- содержимое
.last_smart - последние строки
md0-лога - последние строки
smart-лога - последние строки
scrub-лога
Что умеет запускать:
check_raid.shraid_scrub_bg.shscrub_stop.shcleanup_raid_logs.sh
Особенности:
- если лог за текущий день ещё не создан, подхватывается последний доступный
- длинные строки в логах показываются без принудительного переноса
- существующие скрипты вызываются напрямую, без обязательного перехода на systemd unit/service
- Linux
bashmdadmsmartctl- RAID-массив
md0 - права root
- установленный и работающий
cockpit - административный доступ для запуска команд от root
- наличие скриптов в
/usr/local/sbin/
/usr/local/sbin/check_raid.sh
/usr/local/sbin/raid_scrub.sh
/usr/local/sbin/raid_scrub_bg.sh
/usr/local/sbin/scrub_stop.sh
/usr/local/sbin/cleanup_raid_logs.shПрава:
chmod +x /usr/local/sbin/check_raid.sh
chmod +x /usr/local/sbin/raid_scrub.sh
chmod +x /usr/local/sbin/raid_scrub_bg.sh
chmod +x /usr/local/sbin/scrub_stop.sh
chmod +x /usr/local/sbin/cleanup_raid_logs.sh# check raid health
0 0 * * * root /usr/local/sbin/check_raid.sh
@reboot root sleep 60 && /usr/local/sbin/check_raid.shНеобязательная очистка логов:
# /etc/cron.daily/cleanup-raid-logs
/usr/local/sbin/cleanup_raid_logs.shПо умолчанию логи пишутся в:
/var/log/raid/Типовые файлы:
md0_YYYY-MM-DD.logsmart_YYYY-MM-DD.logscrub_YYYY-MM-DD.log
Служебные файлы:
/var/log/raid/.last_smart/var/log/raid/.scrub_incomplete/var/log/raid/.last_scrub_ym
Если у тебя уже есть директория raidtools/:
sudo rm -rf /usr/local/share/cockpit/raidtools
sudo mkdir -p /usr/local/share/cockpit/raidtools
sudo cp -r raidtools/* /usr/local/share/cockpit/raidtools/После этого обнови страницу Cockpit в браузере.
Проект намеренно сделан лёгким и практичным.
Главные цели:
- ежедневно видеть состояние массива
- иметь простую историю SMART
- контролировать ежемесячный scrub
- запускать и останавливать проверки вручную
- безопасно очищать старые логи
- смотреть всё это из Cockpit без лишней сложности
Initial implementation and iterative refinement were created with ChatGPT assistance.
MIT License. См. файл LICENSE.