11 Commits
18 changed files with 1873 additions and 89 deletions

No files matched your search

+35 -8
View File
@@ -8,6 +8,15 @@ on:
pull_request:
paths: ['files/**', 'package/**', 'scripts/*openwrt*', 'tests/test_openwrt_package.py', '.github/workflows/openwrt-packages.yml']
workflow_dispatch:
inputs:
publish_release:
description: Attach successful builds to the existing version tag
type: boolean
default: false
release_tag:
description: Existing tag (empty means v plus PKG_VERSION)
type: string
default: ''
permissions:
contents: read
@@ -23,6 +32,7 @@ jobs:
outputs:
builds: ${{ steps.targets.outputs.builds }}
smoke: ${{ steps.targets.outputs.smoke }}
release_tag: ${{ steps.release.outputs.tag }}
steps:
- uses: actions/checkout@v4
- name: Test package tooling and shell syntax
@@ -30,17 +40,28 @@ jobs:
python3 -m unittest discover -s tests -p test_openwrt_package.py -v
sh -n scripts/build-openwrt-package.sh
sh -n package/luci-app-owrt-remote/root/usr/lib/owrt-remote/package.sh
- name: Validate tag against package version
if: startsWith(github.ref, 'refs/tags/')
- id: release
name: Validate release tag and source payload
env:
RELEASE_TAG: ${{ github.ref_name }}
RELEASE_TAG: ${{ github.ref_type == 'tag' && github.ref_name || inputs.release_tag }}
MANUAL_PUBLISH: ${{ github.event_name == 'workflow_dispatch' && inputs.publish_release }}
PUBLISH_REQUESTED: ${{ startsWith(github.ref, 'refs/tags/v') || (github.event_name == 'workflow_dispatch' && inputs.publish_release) }}
run: |
python3 - <<'PY'
import os, sys
import os, subprocess, sys
sys.path.insert(0, 'scripts')
import openwrt_package as p
if os.environ['RELEASE_TAG'] != 'v' + p.versions()[0]:
expected = 'v' + p.versions()[0]
tag = os.environ['RELEASE_TAG'] or expected
if os.environ['PUBLISH_REQUESTED'] == 'true' and tag != expected:
raise SystemExit('Release tag must match PKG_VERSION in package/luci-app-owrt-remote/Makefile')
if os.environ['MANUAL_PUBLISH'] == 'true':
# Retry corrected build tooling without moving an existing tag.
# Runtime files must match; packaging tools/metadata may be fixed.
subprocess.run(['git', 'fetch', '--no-tags', 'origin', 'tag', tag], check=True)
subprocess.run(['git', 'diff', '--exit-code', tag, 'HEAD', '--', 'files', 'package/luci-app-owrt-remote/root'], check=True)
with open(os.environ['GITHUB_OUTPUT'], 'a') as f:
f.write('tag=' + tag + '\n')
PY
- id: targets
name: Resolve latest maintenance versions for each supported series
@@ -71,8 +92,14 @@ jobs:
run: |
sudo apt-get update -qq
sudo apt-get install -y build-essential clang flex bison g++ gawk gcc-multilib gettext git libncurses-dev libssl-dev python3-setuptools rsync swig unzip zlib1g-dev file wget zstd
- name: Restore official SDK archive cache
uses: actions/cache@v4
with:
path: ${{ runner.temp }}/openwrt-sdk-cache
key: openwrt-sdk-v1-${{ runner.os }}-${{ matrix.version }}-${{ matrix.target }}-${{ matrix.subtarget }}
- name: Build and verify the native package
env:
OPENWRT_SDK_CACHE: ${{ runner.temp }}/openwrt-sdk-cache
OPENWRT_APK_SIGNING_KEY: ${{ secrets.OPENWRT_APK_SIGNING_KEY }}
run: |
extra=()
@@ -129,8 +156,8 @@ jobs:
publish:
name: Attach verified packages to GitHub Release
needs: [build, install-test]
if: startsWith(github.ref, 'refs/tags/v') && github.event_name != 'workflow_dispatch'
needs: [matrix, build, install-test]
if: startsWith(github.ref, 'refs/tags/v') || (github.event_name == 'workflow_dispatch' && inputs.publish_release)
runs-on: ubuntu-24.04
permissions:
contents: write
@@ -151,7 +178,7 @@ jobs:
while read -r name; do cp "$name" ../publish-files/; done < ../release-files.txt
- uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
tag_name: ${{ needs.matrix.outputs.release_tag }}
generate_release_notes: true
fail_on_unmatched_files: true
files: |
+12 -5
View File
@@ -19,7 +19,7 @@
<img alt="License" src="https://img.shields.io/badge/License-MIT-22C55E?style=flat-square">
</p>
<h3>Удалённый доступ к OpenWrt через свой VPS</h3> Сайт скрипта : https://hub.freedev.app
<h3>Удалённый доступ к OpenWrt через свой VPS</h3> Сказать спасибо ❤️ : https://donate.zks95.ugnss.ru
<p>
Карточки роутеров · Online/Offline · LuCI · SSH Web Terminal · Xray Reverse · HTTPS через nginx
@@ -45,6 +45,13 @@ Xray и недоступном SSH-туннеле, если агент прод
Нужны обновлённые Hub и агент. <a href="docs/xray-control.md">Описание и проверка</a>.
</p>
<p>
<b>Журналы VPS:</b> ежедневная ротация в 03:20, ограничение journald,
фильтрация успешных частых HTTP-запросов и проверка заполнения диска.
Устанавливается также через кнопку «Обновление панели».
<a href="docs/VPS_LOG_MAINTENANCE.md">Установка, проверка и откат</a>.
</p>
<table>
<tr>
@@ -184,7 +191,7 @@ owrt-remote status
<h3> Готовые пакеты для OpenWrt</h3>
Подготовлена сборка IPK для OpenWrt 23.05/24.10 и APK для 25.12. Пакеты
OpenWrt 23.05/24.10 и APK для 25.12. Пакеты
архитектурно независимые (`all`/`noarch`): содержат тот же агент и LuCI-файлы,
что и `install.sh`, сохраняют `/etc/config/owrtremote` и существующий Xray.
GitHub Actions проверяет SDK разных архитектур, установку/обновление/удаление
@@ -338,15 +345,15 @@ APK ставится через SSH. Инструкция, подпись и л
<br><br>
<a href="https://youtu.be/BCVIQgHkbYA?si=BDRAt2uyqRwz8A2Y" target="_blank">
<img src="https://img.youtube.com/vi/BCVIQgHkbYA/maxresdefault.jpg"
<a href="https://www.youtube.com/watch?v=B8pPh8JvDOY" target="_blank">
<img src="https://img.youtube.com/vi/B8pPh8JvDOY/maxresdefault.jpg"
alt="OpenWrt Remote Hub Demo"
width="720">
</a>
<br><br>
<a href="https://youtu.be/BCVIQgHkbYA?si=BDRAt2uyqRwz8A2Y">
<a href="https://www.youtube.com/watch?v=B8pPh8JvDOY">
<img alt="Watch on YouTube"
src="https://img.shields.io/badge/%20Watch%20Demo%20on-YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white">
</a>
+25 -2
View File
@@ -122,6 +122,11 @@ python3 scripts/openwrt_package.py local-apk --apk /path/to/sdk/staging_dir/host
имя SDK в индексе OpenWrt, проверяет SHA256, использует feeds этого SDK,
собирает пакет и проверяет содержимое, права, владельца, зависимости и conffiles:
Поскольку пакет не содержит ELF, SDK собирает только его (`NO_DEPS=1`),
без повторной компиляции curl/LuCI/криптобиблиотек для каждой архитектуры.
Зависимости остаются в метаданных, а их реальная установка проверяется в VM.
Добавление ELF в такой пакет отклоняется сборщиком.
```sh
sh scripts/build-openwrt-package.sh --release 24.10.3 --target ramips --subtarget mt7621 --arch mipsel_24kc --output artifacts
```
@@ -136,8 +141,14 @@ python3 scripts/openwrt_package.py prepare --output /path/to/sdk/package/luci-ap
## GitHub Actions и подпись APK
Workflow `.github/workflows/openwrt-packages.yml` запускается на тегах `v*`,
публикации Release, изменениях пакета в pull request и вручную. Вручную и в PR
он только собирает и тестирует; в Releases пишет только запуск по тегу.
публикации Release, изменениях пакета в pull request и вручную. В PR и при
обычном ручном запуске он только собирает и тестирует. Для повторной публикации
после исправления сборочного инструмента доступен ручной запуск с
`publish_release=true` и существующим `release_tag`, например `v121`.
Он не перемещает тег и проверяет, что содержимое `files/` и установочные
помощники совпадают с этим тегом. Рецепт и инструменты сборки могут содержать
исправления; точный commit сборки записывается в отчёте. После проверок
пакеты прикладываются к Release.
Тег должен совпадать с `PKG_VERSION`: текущий пример — `v121`.
Следующий выпуск должен получить новую версию или пакетную ревизию в Makefile.
@@ -146,6 +157,18 @@ Workflow `.github/workflows/openwrt-packages.yml` запускается на т
на каждую ветку: A53, A72, generic ARM64, ARM A7/A9, MIPS, MIPSEL, MIPS64,
x86 и x86_64. Сохраняются отчёты всех 30 сборок.
Сжатые архивы SDK сохраняются в GitHub Actions cache отдельно для каждой
версии/платформы. Перед повторным использованием SHA256 снова сверяется
с официальным индексом; повреждённый кэш не используется. Прогресс загрузки
выводится в журнал сборки. Для локальной сборки каталог кэша можно задать
переменной `OPENWRT_SDK_CACHE`.
При обрыве сети загрузка продолжается через HTTP Range, если сервер подтвердил
точное смещение. Если Range не поддерживается, скачивание начинается заново.
Повреждённый или незавершённый архив не заменяет рабочую копию.
Кэш Actions ограничен веткой/тегом: повторный запуск использует свой кэш,
а новый тег может использовать кэш основной ветки, но не другого тега.
Ручная сборка на `main` сохраняет кэш основной ветки для следующих выпусков.
После сборки универсальные пакеты устанавливаются в три изолированные x86_64
OpenWrt VM. Проверяется первичная установка, настоящая смена пакетной ревизии,
работа CGI, BusyBox ash, службы, удаление, сохранность настроек/ключа/Xray и
+25 -12
View File
@@ -1,8 +1,10 @@
# Локальная проверка пакетной установки
# Проверка пакетной установки v121
Дата: 07.11.2026. Версия приложения: v121, ревизия пакета: 1.
Проверки выполнялись локально; push и публикация Release не выполнялись.
Реальные роутеры и VPS не изменялись.
Пакеты проверены локально в изолированных OpenWrt VM и успешно прошли
[GitHub Actions](https://github.com/kzolotarev95/luci-app-owrt-remote/actions/runs/42372264122).
Готовые файлы опубликованы в [Releases v121](https://github.com/kzolotarev95/luci-app-owrt-remote/releases/tag/v121).
Реальные роутеры и VPS в этих тестах не используются.
| Среда | Менеджер | Результат |
| --- | --- | --- |
@@ -23,7 +25,10 @@
Дополнительно:
- 16 автоматических тестов сборочного инструмента прошли.
- 22 локальных автоматических теста сборочного инструмента прошли, включая
проверенный кэш SDK, восстановление загрузки после тайм-аута, отказ от
неправильного HTTP Range и повреждённого архива. Дозагрузка после реального
обрыва HTTP-ответа проверена через локальный HTTP-сервер.
- `actionlint v1.7.12` не обнаружил ошибок workflow.
- Проверены все 30 URL SDK и их записи SHA256 в официальных индексах:
10 целевых архитектур для каждой из трёх веток.
@@ -33,16 +38,24 @@
Тестовый приватный ключ не входит в исходники или установочные артефакты.
- Установка не вызывала скачивание/замену рабочего Xray внутри пакетной транзакции.
Локальные IPK созданы переносимым сборщиком из тех же исходников; APK создан
настоящим `apk-tools 3.0.9 mkpkg` в изолированной VM. Полная компиляция через
30 официальных SDK здесь не запускалась: она подготовлена в GitHub Actions.
Доступность SDK не равнозначна успешной сборке; публикация workflow зависит
от успешного завершения SDK-матрицы и последующих VM-тестов.
Сначала проверены локальные IPK переносимого сборщика и APK настоящего
`apk-tools 3.0.9 mkpkg`. Затем из GitHub Actions скачаны пакеты и тестовые
ревизии, собранные официальными SDK. Все три SDK-пакета повторно прошли
установку, обновление и удаление в указанных VM. В SDK-отчётах записан
исходный commit `5630b64d8166a7c58506c7d479bad37589983b3f`; файлы клиента
и установочного помощника совпадают с тегом `v121`.
В CI успешно завершены 30 SDK-сборок: 10 архитектур для каждой из трёх веток,
а затем три нативные проверки установки, обновления и удаления. Публикация
выполнена только после успешного завершения обоих этапов. Все три пакета
повторно скачаны из публичного Release; их SHA256 совпали с `SHA256SUMS`
и отчётами SDK. Тестовые пакеты ревизии 2 в Release не опубликованы.
Физические ARM/MIPS-устройства, действующий Heartbeat, WAN direct и туннель
Xray с реальным Hub в этой проверке не тестировались. Код этих механизмов
не изменён пакетной доработкой.
Локальные протоколы находятся в `.test-output/vm-23.05/`,
`.test-output/vm-24.10/`, `.test-output/vm-25.12/`. Готовые тестовые пакеты —
в `artifacts/openwrt-packages/`. Эти каталоги исключены из Git.
Локальные протоколы первых проверок находятся в `.test-output/vm-23.05/`,
`.test-output/vm-24.10/`, `.test-output/vm-25.12/`. Проверки SDK-пакетов —
в `.test-output/ci-v121/sdk-vm-23.05/`, `sdk-vm-24.10/`, `sdk-vm-25.12/`.
Все тестовые VM после проверки остановлены. Пакеты и протоколы исключены из Git.
+240
View File
@@ -0,0 +1,240 @@
# Обслуживание журналов VPS
Исправление для v121. Оно меняет только HTTP-логирование Hub,
ротацию журналов и обслуживание диска. API, авторизация, Xray, heartbeat,
база данных и архивы журналов роутеров остаются в прежнем формате.
## Причина
`Handler.log_message()` фильтровал успешные long-poll и чтение SSH-терминала,
но записывал каждый успешный heartbeat и пакет `/api/router-logs`.
При большом количестве роутеров эти записи попадали в journald/syslog и Nginx.
Старая настройка Nginx могла добавлять второй `access_log`, сохраняя первый
без фильтра. Установщик также создавал правило `/etc/logrotate.d/owrt-remote`
для тех же файлов Nginx, которые уже обслуживает пакет Nginx.
Частота SSH-перебора на рабочем VPS этим локальным тестом не установлена:
доступ к серверу и чтение его журналов не выполнялись.
## Что установлено
- Hub и стандартный `/var/log/nginx/access.log` пропускают успешные 2xx/3xx
для `/api/heartbeat`, `/api/router-logs`, `/api/notifications/wait` и
`/api/ssh-session/*/read`. HTTP 4xx/5xx, исключения и остальные действия
продолжают записываться. Содержимое доставленных журналов не фильтруется.
- Единственный планировщик — штатный `logrotate.timer`, ежедневно в **03:20
по часовому поясу VPS**. `Persistent=true` запускает пропущенную задачу после
включения сервера. Отдельного cron или второго таймера нет.
- Штатные правила `/etc/logrotate.conf` и `/etc/logrotate.d/` сохраняют права,
владельцев и команды повторного открытия файлов Nginx/rsyslog. Временная
конфигурация добавляет `daily`, `maxsize 20M`, `rotate 1`, `maxage 1`,
`compress`, `nodelaycompress`. Активные журналы через `rm` не удаляются.
- Старые распознанные архивы настроенных журналов удаляются после 24 часов.
Очистка не представляет собой удаление всех `*.gz` на сервере: проверяются
имена архивов конкретных логов, тип файла, ссылки и открытые дескрипторы.
- journald: `SystemMaxUse=50M`, `SystemKeepFree=500M`, `MaxRetentionSec=7day`,
`Compress=yes`, файлы до 10 МиБ. Для непостоянного журнала задано 16 МиБ.
Ежедневно выполняются `journalctl --rotate` и очистка архивов старше суток
с ограничением 50 МиБ. Поэтому ежедневная политика строже предела 7 дней.
- Проверяются `/` и `/var/log`: предупреждение выше 75%, усиленная очистка
**закрытых архивов** выше 85%, критическое сообщение выше 90%. При усиленной
очистке допустимо удалить также свежие архивы, journald сокращается до 10 МиБ.
- Результат: `/var/lib/owrt-remote-log-maintenance/result.json`; собственный
журнал `/var/log/owrt-remote-maintenance.log` — до 64 КиБ плюс один архив
до 64 КиБ. Права состояния и резервных копий ограничены root.
- `flock` исключает параллельные обслуживание/установку/откат. Используется
также штатная блокировка состояния logrotate. Маркер попытки записывается
до работы; автоматический повтор в тот же день пропускается даже после
ошибки. Явный `Run` нужен для повторной попытки после исправления причины.
`maxsize` проверяется при запуске logrotate, а не непрерывно. Ежедневная
задача не гарантирует, что сторонний сервис не заполнит диск между запусками.
Лимиты journald не ограничивают размер базы Hub или пользовательских файлов.
## Установка подготовленной версии
PowerShell Windows 11:
```powershell
$Fix = "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-log-maintenance.ps1"
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps "root@132.243.19.232" -Action Install
```
Нужны Python 3, systemd, journald и установленный `logrotate`. Если последнего
нет, скрипт сообщит об этом до изменения конфигурации:
```powershell
ssh root@132.243.19.232 'apt-get update && apt-get install -y logrotate'
```
Установка сохраняет исходные файлы, проверяет Python, Nginx, systemd и
`logrotate --debug`. При ошибке применения возвращает конфигурацию из копии.
Hub перезапускается; проверяется SHA256 именно запущенной сборки через `/health`.
Затем выполняется первое обслуживание. Если оно завершилось ошибкой,
изучить её и выполнить `Run` либо `Rollback`; уже удалённые архивы не вернуть.
Повторный `Install` обновляет исправление, сохраняя первую резервную копию.
Основной `install-vps.sh` также подключает этот механизм после настройки HTTPS,
когда конфигурация Nginx уже существует. Для полного обновления существующего
VPS через GitHub с сохранением текущего логина выполнить на самом VPS:
```sh
curl -fsSL "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/vps/install-vps.sh?v=$(date +%s)" | sudo env RESET_LOGIN=0 sh
```
**Кнопка «Обновление панели» также устанавливает обслуживание журналов.**
Скрипт включён в сборку Hub в сжатом виде и проверяется по SHA256; отдельная
загрузка скрипта при нажатии кнопки не требуется. Если отсутствует `logrotate`,
выполняется ограниченная по времени установка пакета через apt-get с имеющимися
индексами. Ошибка зависимости отображается как ошибка обновления.
Для каждой установки создаётся отдельная копия настроек. Проверяются Nginx,
journald, ротация и активность таймера. Успех подтверждается только после
успешного обслуживания за текущие сутки; повторной ротации в те же сутки нет.
При отказе настройки возвращаются из копии текущего обновления. При отказе
новой сборки Hub возвращается и предыдущий файл Hub. Хранятся копии настроек
двух последних обновлений; база и данные роутеров в эти копии не входят.
Первый переход со старой сборки поддерживается: старый обработчик заменяет
файл, а запущенный новый Hub завершает установку обслуживания, прежде чем
подтверждает готовность через проверку сборки. Обычный `/health`, heartbeat и
API роутеров продолжают работать. Нестандартная конфигурация вызывает ошибку
с причиной и откат, а не ложное сообщение об успехе.
Если после нажатия кнопки страница продолжает показывать прежнюю сборку,
обновить её через Ctrl+F5. Номер версии остаётся v121; новая сборка определяется
по SHA256. Отдельные команды установки выше сохраняются для ручного применения.
Нестандартные правила с целями вне `/var/log`, `olddir`, неоднозначным синтаксисом
или пользовательским условием `access_log if=...` требуют ручного рассмотрения.
Установка остановится с причиной, не выполняя опасную очистку. Иные назначения
access_log, например отдельные пользовательские файлы, автоматически не меняются.
## Проверка и ручной запуск
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps "root@132.243.19.232" -Action Status
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps "root@132.243.19.232" -Action Run
ssh root@132.243.19.232 'systemctl list-timers logrotate.timer --no-pager; journalctl -u logrotate.service -n 50 --no-pager; tail -n 20 /var/log/owrt-remote-maintenance.log; journalctl --disk-usage; nginx -t; systemctl is-active owrt-remote nginx rsyslog systemd-journald'
```
`Run` принудительно запускает ротацию повторно; для обычной проверки достаточно
`Status`. Не применять `Run` многократно без необходимости.
Временно включить полный HTTP-лог Hub для диагностики можно через
`systemctl edit owrt-remote`, добавив:
```ini
[Service]
Environment=OWRT_REMOTE_HTTP_DEBUG=1
```
После изменения нужен `systemctl restart owrt-remote`. Для выключения удалить
эту строку из созданного drop-in и перезапустить Hub. На фильтр Nginx эта
переменная не влияет; ошибки Nginx всегда сохраняются.
## SSH
Проверить попытки входа без изменения доступа:
```powershell
ssh root@132.243.19.232 'journalctl -u ssh -u sshd --since yesterday --no-pager | tail -n 100'
```
Возможные меры: ограничение SSH по доверенным адресам в firewall, Fail2ban,
`MaxAuthTries 3`, `LoginGraceTime 30`, `MaxStartups 10:30:30`. Подбирать после
просмотра реальной нагрузки и наличия резервного доступа. Перед применением
проверять `sshd -t`, сохранять текущий SSH-сеанс и проверять второй вход.
Исправление не меняет `PasswordAuthentication`, `PermitRootLogin`, SSH или firewall.
## Откат
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps "root@132.243.19.232" -Action Rollback
```
Копия: `/root/owrt-remote-backup-before-log-maintenance-v121/manifest.json`
и файлы рядом. Откат восстанавливает исходный Hub, Nginx, настройки journald,
таймера и старое правило logrotate; возвращает прежнее состояние таймера.
База, сертификаты, SSH-ключи и данные пользователей не открываются обработчиком
очистки. Удалённые или уже ротированные журналы откат не восстанавливает.
## Изменённые файлы и проверки
- `vps/owrt-remote-hub.py` — фильтрация успешных HTTP-записей и DEBUG.
- `vps/log-maintenance.py` — настройка, обслуживание, проверки и откат.
- `vps/install-vps.sh` — подключение обслуживания вместо старых правил.
- `vps/deploy-log-maintenance.ps1` — установка локальной сборки и откат.
- `tests/test_log_maintenance.py`, `tests/test_notification_load.py` — регрессии.
- `scripts/embed-log-maintenance.py` — сборка встроенного скрипта обслуживания.
- `tests/test_hub_update.py`, `tests/test_hub_update_components.py`,
`tests/test_hub_self_update_local.py` — обновление через кнопку и откат.
- Этот документ — эксплуатация и ограничения.
Тесты Python можно запустить отдельно:
```powershell
python -m unittest discover -s tests -p test_log_maintenance.py -v
python -m unittest discover -s tests -p test_notification_load.py -v
```
Проверки POSIX-блокировок, ссылок и прав запускаются на Linux; на Windows
они явно помечены как пропущенные. Проверка на рабочем VPS выполняется после
установки пользователем; локальная Ubuntu не подтверждает состояние его диска
или фактическую интенсивность SSH-перебора.
### Результаты локальной проверки
На отдельной виртуальной машине Ubuntu 24.04 с настоящими systemd, logrotate,
Nginx, rsyslog и работающим Hub проверены:
- 13 тестов обслуживания и 7 тестов HTTP-логирования — успешно на Linux.
- Установка, расписание 03:20, фактические настройки journald, ручное
обслуживание, повтор в тот же день и блокировка параллельного запуска.
- Успешные запросы к четырём частым API не попадают в access.log;
HTTP 404/503 и обычное действие остаются. Настоящий Hub возвращает и
записывает HTTP 401 при heartbeat без авторизации.
- Удаление старых архивов, сохранение постороннего `.gz`, запись новых событий
Nginx и rsyslog после ротации, ограничение собственного журнала.
- Переход со старого правила проекта и дублирующего access_log без сохранения
второго регистратора; исходные файлы возвращаются при откате.
- Повторная установка, ручной откат и автоматический откат при намеренно
ошибочной конфигурации Nginx.
- SQLite `integrity_check=ok`, тестовая запись в базе и SHA256 тестовых настроек,
токенов, сертификата, SSH-ключей и пользовательских файлов сохранены.
- Дополнительно 19 регрессий архива журналов роутеров и 31 проверка жизненного
цикла ресурсов прошли на Windows; 2 проверки POSIX в последнем наборе пропущены.
- Синтаксис Python, PowerShell, shell-установщика и `git diff --check` проверены.
Пороги 75/85/90% проверяются с подменёнными показаниями диска в тестах:
заполнение настоящего раздела до 100% не выполнялось. Существующее предупреждение
Python `invalid escape sequence '\s'` в другом HTML-шаблоне Hub не относится к
этому исправлению и не мешает запуску; шаблон в рамках этой задачи не менялся.
После установки пользователем на рабочий VPS получен успешный результат:
`ok=true`, удалены 263 архива, освобождены 2 365 938 байт, journald занимает
18,8 МиБ. Hub, Nginx, rsyslog и journald подтвердили состояние `active`.
Эта проверка выполнена по предоставленному выводу; независимое подключение
к рабочему серверу не выполнялось.
### Обновление обслуживания через кнопку
На отдельной Ubuntu 24.04 воспроизведён переход именно со старой опубликованной
сборки `8ff052b21d2b…`, в которой обработчик заменяет только файл Hub. До перехода
`/opt/owrt-remote/log-maintenance.py` отсутствовал. После одного обновления он
установлен, результат очистки имеет `ok=true`, таймер и службы активны.
Затем проверен следующий цикл обновления уже новым обработчиком: успех
подтверждён после обслуживания журналов и проверки таймера. Намеренная ошибка
в конфигурации Nginx останавливает обновление с конкретной причиной;
рабочий файл Hub и установленные настройки журналов сохранены. SHA256
тестовых ключей/настроек и целостность SQLite после обоих циклов не изменились.
Дополнительно конфликтующий параметр journald вызвал ошибку уже после записи
новых настроек: копия текущего обновления успешно вернула исходные файлы,
Hub продолжил работать, а результат обновления содержит причину отказа.
Разработчикам: после изменения `vps/log-maintenance.py` выполнить
`python scripts/embed-log-maintenance.py`; команда с `--check` и тесты проверяют,
что встроенный скрипт совпадает с исходником. Внутренний параметр `--backup`
задаёт отдельную резервную копию текущего обновления; без него ручная установка
и откат используют прежний каталог `/root/owrt-remote-backup-before-log-maintenance-v121`.
+1
View File
@@ -10,6 +10,7 @@ PKGARCH:=all
include $(INCLUDE_DIR)/package.mk
define Package/luci-app-owrt-remote
PKGARCH:=all
SECTION:=luci
CATEGORY:=LuCI
SUBMENU:=3. Applications
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Keep the button's offline maintenance payload identical to its source file."""
import argparse
import base64
import hashlib
from pathlib import Path
import re
import zlib
ROOT = Path(__file__).resolve().parents[1]
START = '# BEGIN EMBEDDED LOG MAINTENANCE'
END = '# END EMBEDDED LOG MAINTENANCE'
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check', action='store_true')
args = parser.parse_args()
payload = (ROOT / 'vps/log-maintenance.py').read_bytes().replace(b'\r\n', b'\n')
encoded = base64.b64encode(zlib.compress(payload, 9)).decode('ascii')
block = (START + '\nHUB_LOG_MAINTENANCE_SHA256 = ' + repr(hashlib.sha256(payload).hexdigest()) +
'\nHUB_LOG_MAINTENANCE_BUNDLE = (\n' +
''.join(' ' + repr(encoded[i:i+100]) + '\n' for i in range(0, len(encoded), 100)) +
')\n' + END)
path = ROOT / 'vps/owrt-remote-hub.py'
source = path.read_text(encoding='utf-8')
updated, count = re.subn(re.escape(START) + r'.*?' + re.escape(END), lambda m: block, source, flags=re.S)
if count != 1:
raise SystemExit('Expected one embedded maintenance block')
if args.check:
if updated != source:
raise SystemExit('Maintenance bundle is stale: run python scripts/embed-log-maintenance.py')
else:
path.write_text(updated, encoding='utf-8', newline='\n')
print('Embedded log maintenance: ' + hashlib.sha256(payload).hexdigest())
if __name__ == '__main__':
main()
+69 -16
View File
@@ -96,28 +96,73 @@ def sha256(path):
def download(url, path, expected):
path = Path(path)
if path.is_file() and sha256(path) == expected:
print("Verified download cache: " + path.name, flush=True)
return
partial = path.with_name(path.name + ".partial")
for attempt in range(3):
try:
digest = hashlib.sha256()
request = urllib.request.Request(url, headers={"User-Agent": "OpenWrt-Remote-package-builder"})
with urllib.request.urlopen(request, timeout=60) as response, partial.open("wb") as output:
size = 0
while data := response.read(1024 * 1024):
size += len(data)
if size > 2 * 1024 ** 3:
raise ValueError("SDK download exceeded 2 GiB")
output.write(data)
digest.update(data)
if partial.is_file() and sha256(partial) == expected:
partial.replace(path)
print("Recovered verified download: " + path.name, flush=True)
return
started = progress = time.monotonic()
offset = partial.stat().st_size if partial.is_file() else 0
if offset > 2 * 1024 ** 3:
raise ValueError("SDK download exceeded 2 GiB")
print(f"Downloading {path.name}; attempt {attempt + 1}/3; resume_bytes={offset}", flush=True)
headers = {"User-Agent": "OpenWrt-Remote-package-builder"}
if offset:
headers["Range"] = f"bytes={offset}-"
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request, timeout=60) as response:
response_headers = getattr(response, "headers", {})
status = getattr(response, "status", 200)
if status == 206 and offset:
span = re.fullmatch(r"bytes ([0-9]+)-([0-9]+)/([0-9]+)", response_headers.get("Content-Range", ""))
if not span or int(span[1]) != offset or not offset <= int(span[2]) < int(span[3]) <= 2 * 1024 ** 3:
raise ValueError("invalid SDK download Content-Range")
total = int(span[3])
elif status == 200:
# A server may ignore Range; replace the partial file.
offset = 0
length = response_headers.get("Content-Length")
total = int(length) if length is not None else None
if total is not None and not 0 <= total <= 2 * 1024 ** 3:
raise ValueError("invalid SDK download Content-Length")
else:
raise ValueError("unexpected SDK download HTTP status: " + str(status))
digest = hashlib.sha256()
if offset:
with partial.open("rb") as existing:
while data := existing.read(1024 * 1024):
digest.update(data)
size = offset
with partial.open("ab" if offset else "wb") as output:
while data := response.read(1024 * 1024):
size += len(data)
if size > 2 * 1024 ** 3 or (total is not None and size > total):
raise ValueError("SDK download exceeded declared size or 2 GiB")
output.write(data)
digest.update(data)
now = time.monotonic()
if now - progress >= 15:
print(f"Download progress: {path.name}: {size / 1024 ** 2:.1f} MiB; elapsed={now - started:.0f}s", flush=True)
progress = now
if total is not None and size != total:
raise OSError("incomplete SDK download")
if digest.hexdigest() != expected:
raise ValueError("SDK SHA256 mismatch: " + url)
partial.replace(path)
print(f"Download SHA256 verified: {path.name}; elapsed={time.monotonic() - started:.1f}s", flush=True)
return
except Exception:
partial.unlink(missing_ok=True)
except Exception as error:
# Preserve bounded partial bytes only for transport failures.
# Invalid range, content, or digest always starts a fresh download.
if isinstance(error, ValueError) or getattr(error, "code", None) == 416 or attempt == 2:
partial.unlink(missing_ok=True)
if attempt == 2:
raise
print(f"Download retry: {path.name}: {type(error).__name__}: {error}", flush=True)
time.sleep(2)
@@ -400,6 +445,8 @@ def build(args):
for value in (args.target, args.subtarget, args.arch):
if not re.fullmatch(r"[A-Za-z0-9_-]+", value):
raise ValueError("invalid target/architecture")
if any(data.startswith(b"\x7fELF") for data, _ in payload().values()):
raise ValueError("noarch script-only build cannot contain ELF binaries")
series = ".".join(args.release.split(".")[:2])
base = DOWNLOADS + f"{args.release}/targets/{args.target}/{args.subtarget}/"
name = sdk_name(get_text(base))
@@ -408,7 +455,9 @@ def build(args):
output.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="owrt-package-") as folder:
work = Path(folder)
archive = work / name
cache = os.environ.get("OPENWRT_SDK_CACHE")
archive = (Path(cache).expanduser() if cache else work) / name
archive.parent.mkdir(parents=True, exist_ok=True)
print("Downloading verified SDK: " + base + name, flush=True)
download(base + name, archive, expected)
subprocess.run(["tar", "-xf", str(archive), "-C", str(work)], check=True)
@@ -418,7 +467,7 @@ def build(args):
sdk = directories[0]
prepare(sdk / "package" / PACKAGE)
# Use feed revisions from THIS SDK, not today's unrelated feed heads.
subprocess.run(["./scripts/feeds", "update", "-a"], cwd=sdk, check=True)
subprocess.run(["./scripts/feeds", "update", "base", "packages", "luci"], cwd=sdk, check=True)
subprocess.run(["./scripts/feeds", "install", "luci-base", "rpcd-mod-file", "uhttpd", "jsonfilter", "curl", "ca-bundle", "etherwake"], cwd=sdk, check=True)
with (sdk / ".config").open("a") as config:
config.write(f"\nCONFIG_PACKAGE_{PACKAGE}=m\nCONFIG_SIGNED_PACKAGES=n\n")
@@ -427,7 +476,10 @@ def build(args):
is_apk = "CONFIG_USE_APK=y" in config
if is_apk != (series == "25.12"):
raise ValueError("SDK package format disagrees with the selected OpenWrt series")
subprocess.run(["make", f"package/{PACKAGE}/compile", "V=s", f"-j{args.jobs}"], cwd=sdk, check=True)
# This package only copies scripts. Keep runtime dependencies declared
# and resolved by Kconfig, but do not rebuild curl/LuCI/crypto libraries
# for each SDK. Real installation tests resolve those from OpenWrt.
subprocess.run(["make", f"package/{PACKAGE}/compile", "NO_DEPS=1", "V=s", f"-j{args.jobs}"], cwd=sdk, check=True)
extension = "apk" if is_apk else "ipk"
packages = list((sdk / "bin/packages").rglob(f"{PACKAGE}*.{extension}"))
if len(packages) != 1:
@@ -451,6 +503,7 @@ def build(args):
print("APK is unsigned: SSH needs --allow-untrusted; LuCI requires a trusted maintainer signing key.", flush=True)
verified["file"] = dest.name
report = {"package": PACKAGE, "version": version, "package_release": release,
"source_commit": os.environ.get("GITHUB_SHA"),
"openwrt": args.release, "series": series, "target": f"{args.target}/{args.subtarget}",
"architecture_test": args.arch, "sdk": {"url": base + name, "sha256": expected},
"package_asset": verified, "signed": bool(signing_key)}
@@ -463,7 +516,7 @@ def build(args):
next_release = str(int(release) + 1)
recipe.write_text(recipe.read_text().replace("PKG_RELEASE:=" + release, "PKG_RELEASE:=" + next_release))
subprocess.run(["make", f"package/{PACKAGE}/clean", "V=s"], cwd=sdk, check=True)
subprocess.run(["make", f"package/{PACKAGE}/compile", "V=s"], cwd=sdk, check=True)
subprocess.run(["make", f"package/{PACKAGE}/compile", "NO_DEPS=1", "V=s"], cwd=sdk, check=True)
candidate = list((sdk / "bin/packages").rglob(f"{PACKAGE}*.{extension}"))
if len(candidate) != 1:
raise ValueError("upgrade fixture was not built")
+2 -1
View File
@@ -99,7 +99,8 @@ class LocalTestTests(unittest.TestCase):
self.start_server()
return SimpleNamespace(returncode=0)
with mock.patch.object(hub, 'hub_update_lock', side_effect=lambda *a, **k: nullcontext()), \
mock.patch.object(hub.subprocess, 'run', side_effect=restart), mock.patch.object(hub.time, 'sleep'):
mock.patch.object(hub.subprocess, 'run', side_effect=restart), mock.patch.object(hub.time, 'sleep'), \
mock.patch.object(hub, 'hub_install_log_maintenance'), mock.patch.object(hub, 'hub_prune_log_maintenance_backups'):
self.assertEqual(hub.run_hub_update_worker(job['id']), 0)
self.assertEqual(self.target.read_bytes(), (self.fixture / 'candidate.py').read_bytes())
new_manager = self.server.app.hub_update
+58
View File
@@ -46,6 +46,9 @@ class UpdateTests(unittest.TestCase):
self.manager = hub.HubUpdateManager(self.target, self.directory)
self.addCleanup(mock.patch.stopall)
mock.patch.object(hub, 'hub_update_lock', side_effect=lambda *a, **k: nullcontext()).start()
self.install_logs = mock.patch.object(hub, 'hub_install_log_maintenance').start()
self.rollback_logs = mock.patch.object(hub, 'hub_rollback_log_maintenance').start()
mock.patch.object(hub, 'hub_prune_log_maintenance_backups').start()
def response(self, data=NEW, url=None):
response = io.BytesIO(data)
@@ -164,6 +167,7 @@ class UpdateTests(unittest.TestCase):
self.assertEqual(manager_after_restart.snapshot()['job']['status'], 'succeeded')
self.assertFalse((self.directory / 'candidate.py').exists())
self.assertEqual(run.call_args.args[0], ['systemctl', 'restart', 'owrt-remote'])
self.install_logs.assert_called_once_with(self.directory, job['id'], source=NEW)
def test_failed_health_restores_previous_bytes_and_restarts(self):
job = self.prepare()
@@ -172,6 +176,7 @@ class UpdateTests(unittest.TestCase):
self.assertEqual(hub.run_hub_update_worker(job['id'], self.directory, self.target), 1)
self.assertEqual(self.target.read_bytes(), SOURCE)
self.assertEqual(run.call_count, 2)
self.rollback_logs.assert_called_once_with(self.directory, job['id'])
self.assertIn('Предыдущий файл восстановлен', hub.hub_update_state(self.directory)['message'])
def test_failure_to_write_rollback_progress_does_not_prevent_restoration(self):
@@ -222,6 +227,53 @@ class UpdateTests(unittest.TestCase):
self.assertEqual(self.target.read_bytes(), SOURCE)
self.assertFalse(list(self.root.glob('.hub.py-*')))
def test_failed_maintenance_does_not_replace_or_restart_hub(self):
job = self.prepare()
self.install_logs.side_effect = RuntimeError('nginx validation failed')
with mock.patch.object(hub.time, 'sleep'), mock.patch.object(hub.subprocess, 'run') as run:
self.assertEqual(hub.run_hub_update_worker(job['id'], self.directory, self.target), 1)
self.assertEqual(self.target.read_bytes(), SOURCE)
self.assertFalse(run.called)
self.assertIn('nginx validation failed', hub.hub_update_state(self.directory)['message'])
def test_embedded_payload_matches_source_and_tampering_is_rejected(self):
actual, digest = hub.hub_log_maintenance_payload(SOURCE)
self.assertEqual(actual, (ROOT / 'vps/log-maintenance.py').read_bytes().replace(b'\r\n', b'\n'))
self.assertEqual(hashlib.sha256(actual).hexdigest(), digest)
with self.assertRaisesRegex(ValueError, 'сумма'):
hub.hub_log_maintenance_payload(SOURCE.replace(digest.encode(), b'0' * 64, 1))
def test_first_update_from_old_worker_waits_for_maintenance(self):
job = {'id': 'a' * 32, 'status': 'restarting', 'revision': hub.HUB_LOADED_REVISION,
'started_at': hub.time.time()}
hub.hub_update_state(self.directory, job)
self.install_logs.side_effect = None
captured = {}
def thread(**kwargs):
captured['install'] = kwargs['target']
return mock.Mock()
with mock.patch.object(hub.threading, 'Thread', side_effect=thread):
self.manager.resume_log_maintenance()
self.assertEqual(self.manager.log_maintenance_status, 'installing')
self.assertEqual(self.manager.snapshot()['job']['status'], 'installing')
captured['install']()
self.assertEqual(self.manager.log_maintenance_status, 'ready')
self.install_logs.assert_called_once_with(self.directory, job['id'], budget=40)
self.install_logs.side_effect = RuntimeError('disk full')
captured['install']()
self.assertEqual(self.manager.snapshot()['job']['status'], 'failed')
self.assertIn('disk full', self.manager.snapshot()['job']['message'])
def test_new_worker_receipt_prevents_duplicate_startup_installation(self):
job = {'id': 'b' * 32, 'status': 'restarting', 'revision': hub.HUB_LOADED_REVISION,
'started_at': hub.time.time()}
hub.hub_update_state(self.directory, job)
with mock.patch.object(hub, 'hub_log_maintenance_receipt', return_value={
'status': 'ready', 'sha256': hub.HUB_LOG_MAINTENANCE_SHA256}), \
mock.patch.object(hub.threading, 'Thread') as thread:
self.manager.resume_log_maintenance()
self.assertFalse(thread.called)
class HttpTests(unittest.TestCase):
def test_owner_csrf_origin_validation_and_revision_health(self):
@@ -257,6 +309,12 @@ class HttpTests(unittest.TestCase):
start.assert_called_once_with('abc')
self.assertEqual(request('/health')[1], {'ok': True})
self.assertEqual(request('/health?panel-update=1')[1]['revision'], hub.HUB_LOADED_REVISION)
app.hub_update.log_maintenance_status = 'installing'
self.assertTrue(request('/health')[1]['ok'], 'normal heartbeat health is independent')
self.assertFalse(request('/health?panel-update=1')[1]['ok'])
app.hub_update.log_maintenance_status = 'failed'
app.hub_update.log_maintenance_error = 'test maintenance failure'
self.assertEqual(request('/health?panel-update=1')[1]['log_maintenance']['error'], 'test maintenance failure')
finally:
server.shutdown()
server.server_close()
+97
View File
@@ -0,0 +1,97 @@
"""The button's maintenance transaction, per-update rollback and bounded backups."""
import datetime
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('component_update_hub', ROOT / 'vps/owrt-remote-hub.py')
hub = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = hub
with mock.patch.dict(os.environ, {'OWRT_REMOTE_STATE_DIR': tempfile.gettempdir()}):
spec.loader.exec_module(hub)
class ComponentTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.directory = Path(self.temp.name)
self.job_id = 'c' * 32
self.result = self.directory / 'result.json'
self.result.write_text(json.dumps({'day': datetime.date.today().isoformat(), 'ok': True}))
self.addCleanup(mock.patch.stopall)
mock.patch.object(hub, 'HUB_LOG_MAINTENANCE_RESULT', self.result).start()
mock.patch.object(hub.shutil, 'which', return_value='/usr/bin/command').start()
def test_success_verifies_cleanup_timer_and_exact_payload(self):
with mock.patch.object(hub, 'hub_log_maintenance_command') as command:
receipt = hub.hub_install_log_maintenance(self.directory, self.job_id)
stage = hub.hub_log_maintenance_directory(self.directory, self.job_id)
self.assertEqual((stage / 'log-maintenance.py').read_bytes(), hub.hub_log_maintenance_payload()[0])
calls = [call.args[0] for call in command.call_args_list]
self.assertEqual(calls[0][-3:], ['install', '--backup', str(stage / 'backup')])
self.assertEqual(calls[1][-1], 'run')
self.assertEqual(calls[-2:], [['systemctl', 'is-active', 'logrotate.timer'], ['systemctl', 'is-enabled', 'logrotate.timer']])
self.assertEqual(receipt['status'], 'ready')
self.assertEqual(hub.hub_log_maintenance_receipt(self.directory, self.job_id)['status'], 'ready')
self.assertFalse(any('owrt-remote' in call for call in calls), 'component installation never stops heartbeat/Hub')
def test_failure_restores_only_this_updates_snapshot_and_records_real_reason(self):
calls = []
def run(args, deadline):
calls.append(args)
if 'install' in args:
backup = Path(args[-1]); backup.mkdir()
(backup / 'manifest.json').write_text('{}')
if args[-1] == 'run':
raise RuntimeError('logrotate failed: disk full')
with mock.patch.object(hub, 'hub_log_maintenance_command', side_effect=run):
with self.assertRaisesRegex(RuntimeError, 'disk full'):
hub.hub_install_log_maintenance(self.directory, self.job_id)
self.assertIn('rollback', calls[-1])
self.assertIn(self.job_id, calls[-1][-1])
receipt = hub.hub_log_maintenance_receipt(self.directory, self.job_id)
self.assertEqual(receipt['status'], 'failed')
self.assertIn('disk full', receipt['error'])
def test_failed_or_old_cleanup_result_cannot_be_reported_as_success(self):
for result in ({'ok': False, 'error': 'UBIFS error'}, {'ok': True, 'day': '2000-01-01'}):
self.result.write_text(json.dumps(result))
with self.subTest(result=result), mock.patch.object(hub, 'hub_log_maintenance_command'):
with self.assertRaisesRegex(RuntimeError, 'не подтверждено'):
hub.hub_install_log_maintenance(self.directory, self.job_id)
def test_missing_logrotate_uses_bounded_package_installation(self):
with mock.patch.object(hub.shutil, 'which', side_effect=lambda name: None if name == 'logrotate' else '/usr/bin/apt-get'), \
mock.patch.object(hub, 'hub_log_maintenance_command') as command:
hub.hub_install_log_maintenance(self.directory, self.job_id)
args = command.call_args_list[0].args[0]
self.assertEqual(args, ['apt-get', '-o', 'DPkg::Lock::Timeout=5', 'install', '-y', 'logrotate'])
def test_command_errors_include_stderr_and_timeouts_are_bounded(self):
with mock.patch.object(hub.subprocess, 'run', return_value=subprocess.CompletedProcess([], 1, '', 'nginx configuration invalid')) as run:
with self.assertRaisesRegex(RuntimeError, 'nginx configuration invalid'):
hub.hub_log_maintenance_command(['test'], hub.time.monotonic() + 5)
self.assertLessEqual(run.call_args.kwargs['timeout'], 5)
def test_retention_keeps_latest_two_snapshots_and_ignores_other_data(self):
for number, char in enumerate('abc'):
stage = hub.hub_log_maintenance_directory(self.directory, char * 32)
stage.mkdir(); (stage / 'keep').write_text(char)
os.utime(stage, (100 + number, 100 + number))
other = self.directory / 'router-data'; other.mkdir()
hub.hub_prune_log_maintenance_backups(self.directory, 'c' * 32)
self.assertFalse(hub.hub_log_maintenance_directory(self.directory, 'a' * 32).exists())
self.assertTrue(hub.hub_log_maintenance_directory(self.directory, 'b' * 32).exists())
self.assertTrue(other.exists())
if __name__ == '__main__':
unittest.main()
+189
View File
@@ -0,0 +1,189 @@
"""Retention policy, safe archive selection, disk levels and HTTP diagnostics."""
import importlib.util
import io
import os
from pathlib import Path
import tempfile
import unittest
import subprocess
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("log_maintenance", ROOT / "vps/log-maintenance.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
class MaintenanceTests(unittest.TestCase):
def test_only_exact_old_project_rule_can_be_removed(self):
with tempfile.TemporaryDirectory() as temp:
path = Path(temp) / 'owrt-remote'
rule = '/var/log/nginx/*.log {\n daily\n rotate 7\n size 50M\n missingok\n notifempty\n compress\n delaycompress\n copytruncate\n}\n'
path.write_text(rule)
self.assertTrue(m.legacy_policy(path))
path.write_text(rule.replace('rotate 7', 'rotate 30'))
self.assertFalse(m.legacy_policy(path))
path.write_text(rule.replace('copytruncate', 'postrotate\n echo custom hook\n endscript'))
self.assertFalse(m.legacy_policy(path))
def test_retention_preserves_native_reopen_hooks(self):
text = '''weekly
/var/log/syslog
/var/log/auth.log
{
rotate 7
weekly
delaycompress
postrotate
if true; then
echo "{ brace inside shell }"
fi
endscript
}
'''
result, patterns = m.retention_config(text)
self.assertEqual(patterns, ["/var/log/syslog", "/var/log/auth.log"])
self.assertIn('echo "{ brace inside shell }"', result)
self.assertGreater(result.index("daily"), result.index("endscript"))
self.assertIn("maxsize 20M", result)
self.assertIn("nodelaycompress", result)
def test_non_log_paths_and_ambiguous_rules_fail_before_rotation(self):
for source in ("/var/lib/owrt-remote/hub.db {\n}\n", "/var/log/../lib/data {\n}\n",
"/var/log/a { rotate 1 }\n", "/var/log/a {\nolddir /home/user\n}\n"):
with self.subTest(source=source), self.assertRaises(RuntimeError):
m.retention_config(source)
def test_archive_names_do_not_match_active_or_user_files(self):
for suffix in (".1", ".20.gz", ".old", "-20261119.gz", ".20261119-032000.xz"):
self.assertTrue(m.archive_name("syslog", "syslog" + suffix), suffix)
for name in ("syslog", "syslog.db", "syslog.backup.tar.gz", "user.gz", "syslog.log", "syslog.old.key"):
self.assertFalse(m.archive_name("syslog", name), name)
def test_prune_only_old_closed_archives_and_keep_active_inode(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp).resolve()
active = root / "access.log"
active.write_bytes(b"active")
old, fresh, opened, unrelated = [root / x for x in ("access.log.2.gz", "access.log.1", "access.log.old", "notes.gz")]
for p in (old, fresh, opened, unrelated):
p.write_bytes(b"archive")
for p in (old, opened, unrelated):
os.utime(p, (100, 100))
st = opened.stat()
inode = active.stat().st_ino
removed, size = m.prune_archives([active], now=100000, opened={(st.st_dev, st.st_ino)})
self.assertEqual((removed, size), (1, 7))
self.assertFalse(old.exists())
self.assertTrue(all(p.exists() for p in (active, fresh, opened, unrelated)))
self.assertEqual(active.stat().st_ino, inode)
self.assertEqual(m.prune_archives([active], emergency=True, opened={(st.st_dev, st.st_ino)})[0], 1)
self.assertTrue(opened.exists())
@unittest.skipIf(os.name == "nt", "Requires Unix link semantics")
def test_symlinks_and_hardlinks_are_not_deleted(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp).resolve(); active = root / "a.log"; active.write_text("active")
user = root / "user"; user.write_text("private")
(root / "a.log.1").symlink_to(user)
os.link(user, root / "a.log.2")
self.assertEqual(m.prune_archives([active], emergency=True, opened=set()), (0, 0))
self.assertEqual(user.read_text(), "private")
def test_disk_checks_root_and_separate_log_mount(self):
usage = type("Usage", (), {"total": 110, "used": 91, "free": 9})()
with mock.patch.object(m.shutil, "disk_usage", return_value=usage) as get:
levels = m.disk_levels()
self.assertEqual([x[0] for x in levels], ["/", "/var/log"])
self.assertTrue(all(x[2] == "CRITICAL" for x in levels))
self.assertTrue(all(x[1] == 91 for x in levels))
self.assertEqual(get.call_count, 2)
for used, expected in ((75, 'OK'), (75.1, 'WARN'), (85, 'WARN'), (90, 'WARN'), (90.1, 'CRITICAL')):
usage = type('Usage', (), {'used': used, 'free': 100 - used})()
with self.subTest(used=used), mock.patch.object(m.shutil, 'disk_usage', return_value=usage):
self.assertEqual(m.disk_levels()[0][2], expected)
@unittest.skipIf(os.name == 'nt', 'Requires fcntl lock')
def test_disk_pressure_selects_aggressive_archives_and_smaller_journal_budget(self):
for percent, emergency in ((84.9, False), (85, False), (85.1, True)):
with self.subTest(percent=percent), tempfile.TemporaryDirectory() as temp:
with mock.patch.object(m, 'STATE', Path(temp) / 'state'), \
mock.patch.object(m, 'RUN', Path(temp) / 'run'), \
mock.patch.object(m, 'flatten_config', return_value=''), \
mock.patch.object(m, 'disk_levels', return_value=[('/', percent, 'WARN'), ('/var/log', 20, 'OK')]), \
mock.patch.object(m, 'prune_archives', return_value=(0, 0)) as prune, \
mock.patch.object(m, 'record'), mock.patch('sys.stdout', new=io.StringIO()), \
mock.patch.object(m, 'command', return_value=subprocess.CompletedProcess([], 0, '')) as command:
m.run()
self.assertTrue(all(call.kwargs['emergency'] == emergency for call in prune.call_args_list))
self.assertTrue(any('--vacuum-size=' + ('10M' if emergency else '50M') in call.args[0] for call in command.call_args_list))
def test_later_journald_override_cannot_silently_disable_limit(self):
text = '[Journal]\nSystemMaxUse=50M\nSystemKeepFree=500M\nMaxRetentionSec=7day\nCompress=yes\n'
with mock.patch.object(m, 'command', return_value=subprocess.CompletedProcess([], 0, text)):
m.validate_journal_config()
with mock.patch.object(m, 'command', return_value=subprocess.CompletedProcess([], 0, text + '\n[Journal]\nSystemMaxUse=1G\n')):
with self.assertRaisesRegex(RuntimeError, 'overrides SystemMaxUse'):
m.validate_journal_config()
@unittest.skipIf(os.name == 'nt', 'Requires POSIX nginx paths')
def test_nginx_modifies_existing_logger_without_adding_duplicate(self):
text = 'http {\n access_log /var/log/nginx/access.log;\n access_log /var/log/nginx/custom.log;\n}\n'
path = Path('/etc/nginx/nginx.conf')
with mock.patch.object(m, 'command', return_value=subprocess.CompletedProcess([], 0, '# configuration file /etc/nginx/nginx.conf:\n')), \
mock.patch.object(Path, 'resolve', return_value=path), \
mock.patch.object(Path, 'is_file', return_value=True), \
mock.patch.object(Path, 'read_text', return_value=text):
configs = m.nginx_policies()
changed = configs[str(path)]
self.assertEqual(changed.count('access_log '), 2)
self.assertIn('access.log combined if=$owrt_remote_access_log;', changed)
self.assertIn('access_log /var/log/nginx/custom.log;', changed)
@unittest.skipIf(os.name == 'nt', 'Requires POSIX nginx paths')
def test_existing_custom_nginx_condition_is_not_silently_overwritten(self):
with mock.patch.object(m, 'command', return_value=subprocess.CompletedProcess([], 0, '# configuration file /etc/nginx/nginx.conf:\n')), \
mock.patch.object(Path, 'resolve', return_value=Path('/etc/nginx/nginx.conf')), \
mock.patch.object(Path, 'is_file', return_value=True), \
mock.patch.object(Path, 'read_text', return_value='access_log /var/log/nginx/access.log combined if=$custom;'):
with self.assertRaisesRegex(RuntimeError, 'manual review'):
m.nginx_policies()
@unittest.skipIf(os.name == 'nt', 'Requires POSIX file permissions')
def test_result_log_rollover_is_bounded(self):
with tempfile.TemporaryDirectory() as temp:
path = Path(temp) / 'maintenance.log'
path.write_bytes(b'x' * 100000)
with mock.patch.object(m, 'RESULT', path), mock.patch('sys.stdout', new=io.StringIO()):
m.record('OK', 'done')
self.assertLess(path.stat().st_size, 200)
self.assertEqual(path.with_suffix('.log.1').stat().st_size, 65536)
@unittest.skipIf(os.name == 'nt', 'Requires fcntl lock')
def test_daily_guard_parallel_lock_and_failed_run_are_explicit(self):
import datetime
import fcntl
with tempfile.TemporaryDirectory() as temp:
state, runtime = Path(temp) / 'state', Path(temp) / 'run'
state.mkdir(); runtime.mkdir()
with mock.patch.object(m, 'STATE', state), mock.patch.object(m, 'RUN', runtime), \
mock.patch.object(m, 'record'), mock.patch('sys.stdout', new=io.StringIO()) as output, \
mock.patch.object(m, 'flatten_config', side_effect=RuntimeError('invalid policy')) as parse:
with (runtime / 'lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
m.run()
self.assertFalse(parse.called)
with self.assertRaisesRegex(RuntimeError, 'invalid policy'):
m.run()
self.assertIn('"ok": false', (state / 'result.json').read_text())
self.assertEqual((state / 'last-attempt').read_text().strip(), datetime.date.today().isoformat())
parse.reset_mock()
m.run()
self.assertFalse(parse.called)
self.assertIn('already', output.getvalue())
with self.assertRaisesRegex(RuntimeError, 'invalid policy'):
m.run(force=True)
if __name__ == "__main__":
unittest.main()
+34
View File
@@ -94,6 +94,40 @@ class NotificationLoadTests(unittest.TestCase):
self.assertIn("500", output.getvalue())
self.assertNotIn("200", output.getvalue())
def test_heartbeat_and_log_upload_keep_errors_debug_and_application_messages(self):
class Handler:
path = "/api/heartbeat?unused=1"
def address_string(self): return "127.0.0.1"
def log_date_time_string(self): return "now"
handler = Handler()
for path in ("/api/heartbeat", "/api/router-logs", "/api/ssh-session/test/read"):
handler.path = path + "?test=1"
with self.subTest(path=path), mock.patch.dict(os.environ, {"OWRT_REMOTE_HTTP_DEBUG": "0"}):
output = io.StringIO()
with mock.patch.object(self.hub.sys, "stderr", output):
for status in (200, 201, 204, 301, 304):
self.hub.Handler.log_message(handler, '"%s" %s %s', "POST /test HTTP/1.1", str(status), "0")
for status in (400, 401, 403, 429, 500, 503, 599):
self.hub.Handler.log_message(handler, '"%s" %s %s', "POST /test HTTP/1.1", str(status), "0")
self.hub.Handler.log_message(handler, "database failed: %s", "disk full")
self.hub.Handler.log_message(handler, "custom numeric error: %s %s", "bad", 200)
lines = output.getvalue().splitlines()
self.assertEqual(len(lines), 9)
self.assertIn("database failed", output.getvalue())
with mock.patch.dict(os.environ, {"OWRT_REMOTE_HTTP_DEBUG": "1"}), mock.patch.object(self.hub.sys, "stderr", output):
self.hub.Handler.log_message(handler, '"%s" %s %s', "POST /test HTTP/1.1", "200", "0")
self.assertEqual(len(output.getvalue().splitlines()), 10)
def test_malformed_http_request_without_path_is_still_logged(self):
class Handler:
def address_string(self): return '127.0.0.1'
def log_date_time_string(self): return 'now'
output = io.StringIO()
with mock.patch.object(self.hub.sys, 'stderr', output):
self.hub.Handler.log_message(Handler(), 'code %d, message %s', 400, 'Bad request syntax')
self.assertIn('400', output.getvalue())
self.assertIn('Bad request syntax', output.getvalue())
if __name__ == "__main__":
unittest.main()
+119 -1
View File
@@ -1,14 +1,17 @@
"""Native package contents, release discovery, and safe target setup."""
import importlib.util
import gzip
import http.server
import io
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import threading
import unittest
from unittest import mock
@@ -106,7 +109,9 @@ class PackageTests(unittest.TestCase):
helper = (p.RECIPE / "root/usr/lib/owrt-remote/package.sh").read_text()
# Redirect target paths in the harness. The production hook never
# honors arbitrary ROOT/host variables supplied to a package manager.
helper = helper.replace("/etc/", target.as_posix() + "/etc/").replace("/tmp/", target.as_posix() + "/tmp/")
# One pass is essential on Linux: a temporary target itself starts
# with /tmp/, so sequential replacements would rewrite inserted paths.
helper = re.sub(r"/(?:etc|tmp)/", lambda match: target.as_posix() + match.group(0), helper)
result = subprocess.run([SH, "-s", "--", "configure"], input=helper, capture_output=True, text=True, env=self.env)
return result, key, config
@@ -162,6 +167,119 @@ class PackageTests(unittest.TestCase):
self.assertEqual(destination.read_bytes(), b"previous download")
self.assertFalse(destination.with_name(destination.name + ".partial").exists())
def test_verified_sdk_cache_needs_no_network(self):
destination = self.root / "sdk.tar.xz"
destination.write_bytes(b"verified SDK archive")
with mock.patch.object(p.urllib.request, "urlopen") as network:
p.download("https://downloads.openwrt.org/example", destination, p.sha256(destination))
network.assert_not_called()
def test_invalid_sdk_cache_is_replaced_only_by_verified_download(self):
destination = self.root / "sdk.tar.xz"
destination.write_bytes(b"invalid cache")
expected = self.root / "expected.tar.xz"
expected.write_bytes(b"verified SDK archive")
with mock.patch.object(p.urllib.request, "urlopen", return_value=io.BytesIO(expected.read_bytes())) as network:
p.download("https://downloads.openwrt.org/example", destination, p.sha256(expected))
network.assert_called_once()
self.assertEqual(destination.read_bytes(), expected.read_bytes())
self.assertFalse(destination.with_name(destination.name + ".partial").exists())
def test_interrupted_sdk_download_resumes_only_with_matching_content_range(self):
class Interrupted(io.BytesIO):
status = 200
headers = {"Content-Length": "12"}
def read(self, size=-1):
data = super().read(size)
if not data:
raise TimeoutError("network interrupted")
return data
class Remaining(io.BytesIO):
status = 206
headers = {"Content-Range": "bytes 5-11/12"}
destination = self.root / "sdk.tar.xz"
destination.write_bytes(b"working old archive")
expected = self.root / "expected"
expected.write_bytes(b"first second")
seen = []
def network(request, **kwargs):
self.assertEqual(destination.read_bytes(), b"working old archive")
seen.append(request.get_header("Range"))
return Interrupted(b"first") if len(seen) == 1 else Remaining(b" second")
with mock.patch.object(p.urllib.request, "urlopen", side_effect=network), mock.patch.object(p.time, "sleep"):
p.download("https://downloads.openwrt.org/example", destination, p.sha256(expected))
self.assertEqual(seen, [None, "bytes=5-"])
self.assertEqual(destination.read_bytes(), expected.read_bytes())
def test_download_ignoring_range_restarts_without_appending(self):
destination = self.root / "sdk.tar.xz"
destination.with_name(destination.name + ".partial").write_bytes(b"first")
expected = self.root / "expected"
expected.write_bytes(b"first second")
with mock.patch.object(p.urllib.request, "urlopen", return_value=io.BytesIO(expected.read_bytes())) as network:
p.download("https://downloads.openwrt.org/example", destination, p.sha256(expected))
self.assertEqual(network.call_args.args[0].get_header("Range"), "bytes=5-")
self.assertEqual(destination.read_bytes(), expected.read_bytes())
def test_download_rejects_mismatched_range_without_replacing_working_file(self):
class WrongRange(io.BytesIO):
status = 206
headers = {"Content-Range": "bytes 4-11/12"}
destination = self.root / "sdk.tar.xz"
destination.write_bytes(b"working old archive")
destination.with_name(destination.name + ".partial").write_bytes(b"first")
with mock.patch.object(p.urllib.request, "urlopen", side_effect=lambda *a, **k: WrongRange(b" second")), mock.patch.object(p.time, "sleep"):
with self.assertRaises(ValueError):
p.download("https://downloads.openwrt.org/example", destination, "a" * 64)
self.assertEqual(destination.read_bytes(), b"working old archive")
self.assertFalse(destination.with_name(destination.name + ".partial").exists())
def test_sdk_download_recovers_after_real_http_connection_closes_early(self):
body = b"first second"
destination, expected = self.root / "sdk.tar.xz", self.root / "expected"
destination.write_bytes(b"working old archive")
expected.write_bytes(body)
requests, working_copies = [], []
class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
requests.append(self.headers.get("Range"))
working_copies.append(destination.read_bytes())
if len(requests) == 1:
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body[:5])
self.close_connection = True
else:
self.send_response(206)
self.send_header("Content-Range", "bytes 5-11/12")
self.send_header("Content-Length", "7")
self.end_headers()
self.wfile.write(body[5:])
with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server:
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
try:
with mock.patch.object(p.time, "sleep"):
p.download(f"http://127.0.0.1:{server.server_port}/sdk.tar.xz", destination, p.sha256(expected))
finally:
server.shutdown()
worker.join(timeout=5)
self.assertEqual(requests, [None, "bytes=5-"])
self.assertEqual(working_copies, [b"working old archive"] * 2)
self.assertEqual(destination.read_bytes(), body)
def test_openwrt_disk_image_accepts_fwtool_footer_and_rejects_truncation(self):
source, destination = self.root / "image.gz", self.root / "image.raw"
body = b"OpenWrt disk sectors" * 10000
+54
View File
@@ -0,0 +1,54 @@
param(
[string]$Vps = 'root@132.243.19.232',
[ValidateSet('Install', 'Rollback', 'Status', 'Run')][string]$Action = 'Install'
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-log-maintenance-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$RemoteScript = @'
#!/bin/sh
set -eu
umask 077
stage=/tmp/__UPLOAD_NAME__
trap 'rm -rf "$stage"' EXIT
trap 'exit 1' INT TERM
case '__ACTION__' in
Install)
command -v logrotate >/dev/null || { echo 'Install prerequisite first: apt-get install logrotate' >&2; exit 1; }
python3 "$stage/log-maintenance.py" install --hub-candidate "$stage/hub.py"
if ! systemctl start logrotate.service; then
journalctl -u logrotate.service -n 40 --no-pager >&2
exit 1
fi
python3 /opt/owrt-remote/log-maintenance.py status
;;
Rollback) python3 "$stage/log-maintenance.py" rollback ;;
Status) python3 /opt/owrt-remote/log-maintenance.py status ;;
Run) python3 /opt/owrt-remote/log-maintenance.py run --force ;;
esac
echo 'LOG_MAINTENANCE___ACTION___OK'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
foreach ($Pair in @(@('vps\log-maintenance.py', 'log-maintenance.py'), @('vps\owrt-remote-hub.py', 'hub.py'))) {
if ($Pair[1] -eq 'hub.py' -and $Action -ne 'Install') { continue }
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Pair[0])).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Pair[1]), $Content, $Utf8)
}
& scp -O -r -- $StageRoot "${Vps}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. VPS was not changed.' }
& ssh -T -o ConnectTimeout=15 $Vps "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed; success was not confirmed. See the error above." }
Write-Host "Log maintenance $Action finished successfully."
}
finally {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) { throw 'Unsafe staging cleanup path.' }
if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
}
+15 -36
View File
@@ -153,41 +153,20 @@ PY
}
install_log_limits() {
$SUDO mkdir -p /etc/systemd/journald.conf.d /etc/nginx/conf.d
$SUDO tee /etc/systemd/journald.conf.d/owrt-remote-limits.conf >/dev/null <<'EOF'
[Journal]
SystemMaxUse=256M
SystemKeepFree=512M
MaxRetentionSec=7day
RateLimitIntervalSec=30s
RateLimitBurst=2000
Compress=yes
EOF
$SUDO tee /etc/nginx/conf.d/owrt-remote-log-policy.conf >/dev/null <<'EOF'
# Successful long-poll and terminal reads are expected traffic.
# Keep 4xx/5xx responses in access.log for diagnostics.
map "$request_uri:$status" $owrt_remote_access_log {
default 1;
~^/api/notifications/wait[^:]*:2[0-9][0-9]$ 0;
~^/api/ssh-session/[^/]+/read[^:]*:2[0-9][0-9]$ 0;
}
access_log /var/log/nginx/access.log combined if=$owrt_remote_access_log;
EOF
$SUDO tee /etc/logrotate.d/owrt-remote >/dev/null <<'EOF'
/var/log/nginx/*.log {
daily
rotate 7
size 50M
missingok
notifempty
compress
delaycompress
copytruncate
}
EOF
$SUDO systemctl daemon-reload >/dev/null 2>&1 || true
$SUDO systemctl reload-or-restart systemd-journald >/dev/null 2>&1 || true
$SUDO journalctl --vacuum-size=256M --vacuum-time=7d >/dev/null 2>&1 || true
info "Настраиваю ежедневную ротацию журналов и защиту диска..."
if ! command -v logrotate >/dev/null 2>&1; then
apt_get install -y logrotate || die "не удалось установить logrotate"
fi
maintenance_candidate="$(mktemp /tmp/owrt-log-maintenance.XXXXXX.py)" || die "не удалось создать временный файл"
if ! curl -fsSL --max-time 120 -o "$maintenance_candidate" "$RAW_BASE/vps/log-maintenance.py?v=$(date +%s)"; then
rm -f "$maintenance_candidate"
die "не удалось загрузить обслуживание журналов"
fi
if ! $SUDO python3 "$maintenance_candidate" install; then
rm -f "$maintenance_candidate"
die "не удалось настроить обслуживание журналов; смотри причину выше"
fi
rm -f "$maintenance_candidate"
}
install_xray_service() {
@@ -329,12 +308,12 @@ main() {
install_xray_binary
install_files
install_python_deps_v2
install_log_limits
install_xray_service
open_firewall
start_hub
check_hub || die "Hub установлен, но сервис не поднялся. Лог выше."
enable_https "$host"
install_log_limits
print_result "$host"
}
+565
View File
@@ -0,0 +1,565 @@
#!/usr/bin/env python3
"""Bounded VPS log maintenance. Never opens the Hub database or router archives.
Uses the distribution's logrotate rules and reopen hooks, with retention
overrides in a temporary configuration. One owner: system logrotate.timer.
"""
import argparse
import ast
import datetime as dt
import glob
import hashlib
import json
import os
from pathlib import Path
import re
import shlex
import shutil
import stat
import subprocess
import sys
import tempfile
import time
MARKER = "# Managed by OpenWrt Remote log maintenance"
INSTALL_PATH = Path("/opt/owrt-remote/log-maintenance.py")
BACKUP = Path("/root/owrt-remote-backup-before-log-maintenance-v121")
STATE = Path("/var/lib/owrt-remote-log-maintenance")
RUN = Path("/run/owrt-remote-log-maintenance")
RESULT = Path("/var/log/owrt-remote-maintenance.log")
HUB = Path("/opt/owrt-remote/owrt-remote-hub.py")
LEGACY = Path("/etc/logrotate.d/owrt-remote")
POLICY = "\n daily\n maxsize 20M\n rotate 1\n maxage 1\n compress\n nodelaycompress\n"
CONFIGS = {
"/etc/systemd/journald.conf.d/owrt-remote-limits.conf": MARKER + """
[Journal]
SystemMaxUse=50M
SystemKeepFree=500M
SystemMaxFileSize=10M
RuntimeMaxUse=16M
RuntimeKeepFree=64M
MaxRetentionSec=7day
Compress=yes
""",
"/etc/systemd/system/logrotate.timer.d/owrt-remote.conf": MARKER + """
[Timer]
OnCalendar=
OnCalendar=*-*-* 03:20:00
AccuracySec=1min
RandomizedDelaySec=0
Persistent=true
""",
"/etc/systemd/system/logrotate.service.d/owrt-remote.conf": MARKER + """
[Service]
ExecStart=
ExecStart=/usr/bin/python3 /opt/owrt-remote/log-maintenance.py run
Nice=10
IOSchedulingClass=idle
TimeoutStartSec=30min
""",
"/etc/nginx/conf.d/owrt-remote-log-policy.conf": MARKER + """
# Only routine successful traffic is quiet; errors and other actions remain.
map "$uri:$status" $owrt_remote_access_log {
default 1;
~^/api/notifications/wait:[23][0-9][0-9]$ 0;
~^/api/ssh-session/[^/]+/read:[23][0-9][0-9]$ 0;
~^/api/heartbeat:[23][0-9][0-9]$ 0;
~^/api/router-logs:[23][0-9][0-9]$ 0;
}
""",
}
def atomic(path, data, mode=0o600):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
if path.is_symlink():
raise RuntimeError("Refusing symlink: " + str(path))
fd, name = tempfile.mkstemp(prefix="." + path.name + ".", dir=path.parent)
try:
with os.fdopen(fd, "wb") as stream:
os.fchmod(stream.fileno(), mode)
stream.write(data if isinstance(data, bytes) else data.encode())
stream.flush()
os.fsync(stream.fileno())
os.replace(name, path)
finally:
if os.path.exists(name):
os.unlink(name)
def command(args, timeout=120, check=True):
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
timeout=timeout, text=True, errors="replace")
if check and result.returncode:
raise RuntimeError(f"{shlex.join(args)}: rc={result.returncode}; {result.stdout[-6000:]}")
return result
def record(level, message):
"""One small result file, at most 64 KiB plus one 64 KiB previous file."""
line = (dt.datetime.now().astimezone().isoformat(timespec="seconds") +
f" [{level}] " + str(message).replace("\n", " ")[:4000] + "\n").encode()
print(line.decode().rstrip(), flush=True)
if RESULT.is_symlink() or RESULT.with_suffix(".log.1").is_symlink():
raise RuntimeError("Unsafe maintenance log path")
if RESULT.exists() and RESULT.stat().st_size + len(line) > 65536:
with RESULT.open("rb") as stream:
stream.seek(max(0, os.fstat(stream.fileno()).st_size - 65536))
previous = stream.read(65536)
atomic(RESULT.with_suffix(".log.1"), previous)
# Keep the active inode available to readers.
with RESULT.open("r+b") as stream:
stream.truncate(0)
fd = os.open(RESULT, os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "ab") as stream:
stream.write(line)
def legacy_policy(path=LEGACY):
if not path.exists():
return False
if path.is_symlink():
return False
lines = [line.strip() for line in path.read_text().splitlines()
if line.strip() and not line.lstrip().startswith("#")]
expected = {"daily", "rotate 7", "size 50M", "missingok", "notifempty",
"compress", "delaycompress", "copytruncate"}
return (len(lines) == 10 and lines[0] == "/var/log/nginx/*.log {"
and lines[-1] == "}" and set(lines[1:-1]) == expected)
def nginx_policies():
"""Patch existing standard destinations; never add a second access logger.
sites-enabled entries are commonly symlinks: backup/edit their resolved
targets in /etc/nginx, leaving the symlinks themselves intact.
"""
rendered = command(["nginx", "-T"]).stdout
configs = {}
for filename in re.findall(r"^# configuration file ([^\n]+):$", rendered, re.M):
path = Path(filename).resolve()
if str(path) == "/etc/nginx/conf.d/owrt-remote-log-policy.conf":
continue
if not str(path).startswith("/etc/nginx/") or not path.is_file():
raise RuntimeError("Unexpected nginx configuration: " + str(path))
text = path.read_text()
def add_condition(match):
directive = match.group(0)
if "$owrt_remote_access_log" in directive:
return directive
if re.search(r"\bif=", directive):
raise RuntimeError("Custom nginx log condition requires manual review: " + str(path))
# nginx needs an explicit format before optional parameters. Ubuntu's
# default is simply `access_log /var/log/nginx/access.log;`.
prefix = directive[:-1]
if len(shlex.split(prefix)) == 2:
prefix += " combined"
return prefix + " if=$owrt_remote_access_log;"
updated = re.sub(r"(?m)^\s*access_log\s+/var/log/nginx/access\.log(?:\s+[^;\n]+)?;", add_condition, text)
if updated != text:
configs[str(path)] = updated
return configs
def flatten_config(path, seen=None):
"""Read trusted distribution configs; never execute hooks during parsing."""
path = Path(path)
seen = set() if seen is None else seen
if path in seen or len(seen) > 128:
raise RuntimeError("Recursive or oversized logrotate include: " + str(path))
info = path.lstat()
if path.is_symlink() or not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
raise RuntimeError("Untrusted logrotate config: " + str(path))
if info.st_size > 262144:
raise RuntimeError("Oversized logrotate config: " + str(path))
seen.add(path)
lines, script = [], False
for line in path.read_text().splitlines(keepends=True):
word = line.strip().split(" ", 1)[0]
if word in ("firstaction", "prerotate", "postrotate", "lastaction", "preremove"):
script = True
elif word == "endscript":
script = False
if not script and re.match(r"^\s*include\s+", line):
parts = shlex.split(line, comments=True)
if len(parts) != 2 or not (parts[1] == "/etc/logrotate.conf" or parts[1] == "/etc/logrotate.d" or parts[1].startswith("/etc/logrotate.d/")):
raise RuntimeError("Unsupported logrotate include: " + line.strip())
include = Path(parts[1])
children = sorted(include.iterdir()) if include.is_dir() else [include]
for child in children:
if child.is_dir() or re.search(r"(?:~|\.(?:bak|old|disabled|dpkg-.+|rpmnew|rpmsave))$", child.name):
continue
if child == LEGACY and legacy_policy():
continue
lines.append(flatten_config(child, seen))
else:
lines.append(line)
seen.remove(path)
result = "".join(lines)
if len(result) > 1048576:
raise RuntimeError("Logrotate config exceeds 1 MiB")
return result + "\n"
def retention_config(source):
"""Keep native create/su/reopen hooks, override only retention per stanza.
Refuse ambiguous syntax and targets outside /var/log before any rotation.
In particular, no arbitrary service file in /var/lib can enter cleanup.
"""
output, patterns, header, block = [], [], [], []
script, inside = False, False
for line in source.splitlines(keepends=True):
stripped = line.strip()
if inside:
word = stripped.split(" ", 1)[0]
if not script and word in ("firstaction", "prerotate", "postrotate", "lastaction", "preremove"):
script = True
elif script and word == "endscript":
script = False
if not script and stripped == "}":
# olddir may put archives outside /var/log: refuse to clean there.
check_script = False
for item in block:
word = item.strip().split(" ", 1)[0]
if word in ("firstaction", "prerotate", "postrotate", "lastaction", "preremove"):
check_script = True
elif word == "endscript":
check_script = False
if check_script:
continue
if re.match(r"\s*(?:olddir|include)\s+", item):
raise RuntimeError("olddir/include inside log stanza requires administrator review")
output.extend(block)
output.append(POLICY + "}\n")
inside, block = False, []
elif not script and ("{" in stripped or stripped.startswith("}")):
raise RuntimeError("Unsupported logrotate block syntax: " + stripped)
else:
block.append(line)
continue
if header or stripped.startswith(("/", '"', "'")):
header.append(line)
if "{" in line:
combined = "".join(header)
if combined.count("{") != 1 or combined.split("{", 1)[1].strip():
raise RuntimeError("Unsupported inline logrotate stanza")
targets = shlex.split(combined.split("{", 1)[0], comments=True)
for target in targets:
if not target.startswith("/var/log/") or ".." in Path(target).parts:
raise RuntimeError("Refusing log target outside /var/log: " + target)
patterns.extend(targets)
output.extend(header)
header, inside = [], True
else:
output.append(line)
if header or inside or script:
raise RuntimeError("Incomplete logrotate configuration")
return "".join(output), patterns
def archive_name(active, candidate):
if not candidate.startswith(active):
return False
suffix = candidate[len(active):]
return bool(re.fullmatch(r"(?:\.\d+|\.old|[-.]\d{8}(?:[-.]\d{4,6})?)(?:\.(?:gz|xz|bz2|zst))?", suffix))
def open_inodes():
opened = set()
for directory in Path("/proc").iterdir():
if not directory.name.isdigit():
continue
try:
for fd in (directory / "fd").iterdir():
try:
info = fd.stat()
opened.add((info.st_dev, info.st_ino))
except FileNotFoundError:
pass
except FileNotFoundError:
pass
return opened
def prune_archives(active_paths, emergency=False, now=None, opened=None):
now = time.time() if now is None else now
opened = open_inodes() if opened is None else opened
removed, freed = 0, 0
for active in sorted(set(Path(p) for p in active_paths)):
if not active.is_file() or active.is_symlink() or active.resolve() != active:
continue
for candidate in active.parent.iterdir():
if not archive_name(active.name, candidate.name):
continue
info = candidate.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
continue
if not emergency and now - info.st_mtime <= 86400:
continue
if (info.st_dev, info.st_ino) in opened:
continue
latest = candidate.lstat()
if (latest.st_dev, latest.st_ino, latest.st_mtime_ns) != (info.st_dev, info.st_ino, info.st_mtime_ns):
continue
candidate.unlink() # Only verified closed archives, never active logs.
removed += 1
freed += info.st_size
return removed, freed
def disk_levels():
result = []
for path in ("/", "/var/log"):
usage = shutil.disk_usage(path)
# Match df: blocks reserved for root are not available to log writers.
available_total = usage.used + usage.free
percent = 100 * usage.used / available_total if available_total else 100
level = "CRITICAL" if percent > 90 else "WARN" if percent > 75 else "OK"
result.append((path, percent, level))
return result
def service_status():
for name in ("owrt-remote", "nginx", "rsyslog", "systemd-journald"):
result = command(["systemctl", "is-active", name], check=False)
print(f"{name}: {result.stdout.strip()}")
def validate_journal_config():
effective, section = {}, ""
for line in command(["systemd-analyze", "cat-config", "systemd/journald.conf"]).stdout.splitlines():
text = line.strip()
if text.startswith("["):
section = text
elif section == "[Journal]" and not text.startswith(("#", ";")) and "=" in text:
key, value = text.split("=", 1)
effective[key.strip()] = value.strip()
for key, value in {"SystemMaxUse": "50M", "SystemKeepFree": "500M",
"MaxRetentionSec": "7day", "Compress": "yes"}.items():
if effective.get(key) != value:
raise RuntimeError("Another journald configuration overrides " + key + "; administrator review required")
def run(force=False):
import fcntl
STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
RUN.mkdir(mode=0o700, parents=True, exist_ok=True)
with (RUN / "lock").open("a") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
print("Maintenance already running; skipped")
return
today = dt.date.today().isoformat()
stamp = STATE / "last-attempt"
if not force and stamp.exists() and stamp.read_text().strip() == today:
print("Daily attempt already made; use run --force to retry an error")
return
# Write before work: even a process crash cannot cause a second daily run.
atomic(stamp, today + "\n")
try:
config, patterns = retention_config(flatten_config("/etc/logrotate.conf"))
active = [Path(p) for pattern in patterns for p in glob.glob(pattern)]
emergency = any(percent > 85 for _, percent, _ in disk_levels())
before = disk_levels()
for path, percent, level in before:
record(level, f"before {path}: {percent:.1f}% used")
atomic(RUN / "logrotate.conf", config)
command(["logrotate", "--debug", str(RUN / "logrotate.conf")])
removed, freed = prune_archives(active, emergency=emergency)
# Same state/lock as distro logrotate, not a private competing state.
command(["logrotate", "--wait-for-state-lock", "--force", str(RUN / "logrotate.conf")], timeout=1500)
command(["journalctl", "--rotate"], timeout=60)
vacuum = command(["journalctl", "--vacuum-time=1d", "--vacuum-size=" + ("10M" if emergency else "50M")])
more, size = prune_archives(active, emergency=emergency)
removed += more
freed += size
after = disk_levels()
result = {"day": today, "ok": True, "archives_removed": removed,
"bytes_removed": freed, "emergency": emergency,
"disk_after": after, "finished_at": time.time()}
atomic(STATE / "result.json", json.dumps(result) + "\n")
record("OK", f"completed; archives_removed={removed}; bytes_removed={freed}; emergency={emergency}; {vacuum.stdout[-500:]}")
for path, percent, level in after:
record(level, f"after {path}: {percent:.1f}% used; database and user data excluded")
print(command(["journalctl", "--disk-usage"]).stdout.strip())
except Exception as exc:
atomic(STATE / "result.json", json.dumps({"day": today, "ok": False, "error": str(exc)[-6000:]}) + "\n")
record("ERROR", exc)
raise
finally:
(RUN / "logrotate.conf").unlink(missing_ok=True)
def snapshot(paths, backup):
backup.mkdir(mode=0o700, parents=True, exist_ok=True)
manifest_path = backup / "manifest.json"
if manifest_path.exists():
manifest = json.loads(manifest_path.read_text())
else:
manifest = {"files": [], "timer_enabled": command(["systemctl", "is-enabled", "logrotate.timer"], check=False).stdout.strip(),
"timer_active": command(["systemctl", "is-active", "logrotate.timer"], check=False).stdout.strip()}
known = {item["path"] for item in manifest["files"]}
for path in paths:
path = Path(path)
if str(path) in known:
continue
if path.is_symlink():
raise RuntimeError("Refusing to replace symlink: " + str(path))
item = {"path": str(path), "exists": path.exists(), "copy": str(len(manifest["files"]))}
if path.exists():
info = path.stat()
item.update(mode=stat.S_IMODE(info.st_mode), uid=info.st_uid, gid=info.st_gid)
atomic(backup / item["copy"], path.read_bytes())
manifest["files"].append(item)
atomic(manifest_path, json.dumps(manifest))
def restore(backup):
manifest = json.loads((backup / "manifest.json").read_text())
command(["systemctl", "stop", "logrotate.timer"])
for item in manifest["files"]:
path = Path(item["path"])
if item["exists"]:
atomic(path, (backup / item["copy"]).read_bytes(), item["mode"])
os.chown(path, item["uid"], item["gid"])
else:
path.unlink(missing_ok=True)
command(["systemctl", "daemon-reload"])
command(["systemctl", "restart", "systemd-journald"])
if shutil.which("nginx"):
command(["nginx", "-t"])
if command(["systemctl", "is-active", "nginx"], check=False).returncode == 0:
command(["systemctl", "reload", "nginx"])
if manifest["timer_enabled"] == "enabled":
command(["systemctl", "enable", "logrotate.timer"])
else:
command(["systemctl", "disable", "logrotate.timer"])
if manifest["timer_active"] == "active":
command(["systemctl", "start", "logrotate.timer"])
if any(item["path"] == str(HUB) for item in manifest["files"]):
command(["systemctl", "restart", "owrt-remote"])
print("Configuration restored. Already rotated/deleted archives cannot be restored.")
def install(hub_candidate=None, backup=BACKUP):
for executable in ("logrotate", "journalctl", "systemctl", "systemd-analyze"):
if not shutil.which(executable):
raise RuntimeError("Missing prerequisite: " + executable)
if command(["systemctl", "is-active", "logrotate.service"], check=False).stdout.strip() in ("active", "activating"):
raise RuntimeError("Wait for the running system logrotate.service to finish")
if LEGACY.exists() and not legacy_policy():
raise RuntimeError("Custom /etc/logrotate.d/owrt-remote found; manual review required")
retention_config(flatten_config("/etc/logrotate.conf"))
if hub_candidate:
text = Path(hub_candidate).read_text()
ast.parse(text)
if "OWRT_REMOTE_HTTP_DEBUG" not in text:
raise RuntimeError("Hub candidate does not contain the HTTP log fix")
configs = dict(CONFIGS)
if not shutil.which("nginx"):
configs.pop("/etc/nginx/conf.d/owrt-remote-log-policy.conf")
else:
configs.update(nginx_policies())
paths = [*configs, str(INSTALL_PATH), str(LEGACY)] + ([str(HUB)] if hub_candidate else [])
snapshot(paths, backup)
try:
command(["systemctl", "stop", "logrotate.timer"])
for path, content in configs.items():
atomic(path, content, 0o644)
atomic(INSTALL_PATH, Path(__file__).read_bytes(), 0o755)
if legacy_policy():
LEGACY.unlink() # Old duplicate configuration, not a log file.
if hub_candidate:
atomic(HUB, Path(hub_candidate).read_bytes(), 0o755)
config, _ = retention_config(flatten_config("/etc/logrotate.conf"))
RUN.mkdir(mode=0o700, parents=True, exist_ok=True)
atomic(RUN / "validate.conf", config)
try:
command(["logrotate", "--debug", str(RUN / "validate.conf")])
finally:
(RUN / "validate.conf").unlink(missing_ok=True)
command(["systemctl", "daemon-reload"])
command(["systemd-analyze", "verify", "logrotate.service", "logrotate.timer"])
validate_journal_config()
if shutil.which("nginx"):
command(["nginx", "-t"])
if command(["systemctl", "is-active", "nginx"], check=False).returncode == 0:
command(["systemctl", "reload", "nginx"])
command(["systemctl", "restart", "systemd-journald"])
if hub_candidate:
command(["systemctl", "restart", "owrt-remote"])
check_health(hashlib.sha256(HUB.read_bytes()).hexdigest())
# Start the persistent timer only after main releases our lock. A missed
# calendar event can otherwise immediately run and be skipped as busy.
command(["systemctl", "enable", "logrotate.timer"])
print("Backup: " + str(backup))
print("LOG_MAINTENANCE_INSTALL_OK")
except Exception:
restore(backup)
raise
def check_health(revision):
import urllib.request
# No proxy environment / shell wildcard expansion. Retry startup quietly.
client = urllib.request.build_opener(urllib.request.ProxyHandler({}))
for attempt in range(15):
try:
with client.open("http://127.0.0.1:8088/health?panel-update=1", timeout=3) as response:
data = json.load(response)
if data.get("ok") and data.get("revision") == revision:
return
except (OSError, ValueError):
pass
time.sleep(1)
raise RuntimeError("Hub health check failed after restart")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("install", "rollback", "run", "status"))
parser.add_argument("--hub-candidate")
parser.add_argument("--backup", type=Path, default=BACKUP,
help="Configuration snapshot for this installation/rollback")
parser.add_argument("--force", action="store_true", help="Explicit manual retry; daily timer never uses this")
args = parser.parse_args()
if os.geteuid() != 0:
parser.error("Run as root")
if args.action in ("install", "rollback"):
import fcntl
RUN.mkdir(mode=0o700, parents=True, exist_ok=True)
with (RUN / "lock").open("a") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise RuntimeError("Log maintenance/install already running; retry after completion")
if args.action == "install":
install(args.hub_candidate, backup=args.backup)
else:
restore(args.backup)
if args.action == "install":
try:
command(["systemctl", "start", "logrotate.timer"])
except Exception:
restore(args.backup)
raise
elif args.action == "run":
run(args.force)
else:
print(command(["systemctl", "list-timers", "logrotate.timer", "--no-pager"]).stdout)
print(command(["journalctl", "--disk-usage"]).stdout)
print((STATE / "result.json").read_text() if (STATE / "result.json").exists() else "No maintenance result yet")
for path, percent, level in disk_levels():
print(level, path, f"{percent:.1f}%")
service_status()
if __name__ == "__main__":
try:
main()
except Exception as error:
print("ERROR: " + str(error), file=sys.stderr)
sys.exit(1)
+294 -8
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
import argparse
import ast
import base64
import datetime as dt
import dataclasses
@@ -37,6 +38,7 @@ import urllib.parse
import urllib.request
import uuid
import warnings
import zlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
@@ -15979,6 +15981,115 @@ class RouterUpdateManager:
HUB_UPDATE_LIMIT = 4 * 1024 * 1024
HUB_UPDATE_ACTIVE = {'starting', 'installing', 'restarting', 'rollback'}
HUB_LOG_MAINTENANCE_RESULT = Path('/var/lib/owrt-remote-log-maintenance/result.json')
# BEGIN EMBEDDED LOG MAINTENANCE
HUB_LOG_MAINTENANCE_SHA256 = '03c6a6843ed2e0b287502f165f716cb56305acc8f8798afd51f57d394862455d'
HUB_LOG_MAINTENANCE_BUNDLE = (
'eNq1PGt32zaW3/UrsEx3SzYSJbtJmpFX0+Okbptt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rc26qkps/uZDSpz8MtvBA/iMO8qoWH'
'du6Qd+3yI4tpRkku/V1idz+9LJCm3tMbO5Bctg/7nM3nQeKD+WKMxDLquaeGsKNDSQV/mYAWyWa2pVxJ/iJSFCFL0O8iVh42fgDT'
'2QJzhF+2HZXy0tralTkOqWOzlrP3/H1J/k6I8lj7P8kHHLSeNfxpbYYqTyzMtGtMr8fljrYuSidtGTszi4TDHD+/ag3VrAf6cyil'
'FwX8sqcKIlj6crFnwZ+3DjM1JX7Ij2KvNDP9wbmz6ssQSYbEK4sw4LrniRn8o1FSRZ4LSh9hUWXlRSIslxfOvmzXeZoue7Pk6E+a'
'cF9YQdR7PeCrK4keW0205Sq2+em9scJfu9RIFdoQy6pUaXXdxZBQ5olgMEsfyLTrrh5FcWhEzegoozj0qqmm+i/HacXWOezRa+s8'
'oK8MwfUlQr9w7e2kJNVONveDUstQ8+q7oC4xeJcn3Uzy1rYWAcFTqUSadW2QPI04Ga29S9quiiw5gz+TQW6O7k4K18InVCbf060M'
'LnEBB9gm5lcmVXnERuZWl9fdzsV3VJjXl6vS8Tx+YdXT8MYkzbpm0HywizndxJjP6Sjnc1zqfK7Os0aTrCEHvQn2Ovcre5ES3ZVZ'
'SZ3wc5+giWdw7i5/I9ZY4wbv7oU5Kvb/A/M9qWg='
)
# END EMBEDDED LOG MAINTENANCE
def hub_update_write(path, data, mode=0o600):
@@ -15997,6 +16108,115 @@ def hub_update_write(path, data, mode=0o600):
Path(name).unlink(missing_ok=True)
def hub_log_maintenance_payload(source=None):
"""The confirmed Hub includes its exact maintenance script: no second URL."""
digest, bundle = HUB_LOG_MAINTENANCE_SHA256, HUB_LOG_MAINTENANCE_BUNDLE
if source is not None:
values = {}
with warnings.catch_warnings():
warnings.simplefilter('ignore', SyntaxWarning)
tree = ast.parse(source)
for node in tree.body:
if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
name = node.targets[0].id
if name in {'HUB_LOG_MAINTENANCE_SHA256', 'HUB_LOG_MAINTENANCE_BUNDLE'}:
values[name] = ast.literal_eval(node.value)
digest, bundle = values.get('HUB_LOG_MAINTENANCE_SHA256'), values.get('HUB_LOG_MAINTENANCE_BUNDLE')
if not isinstance(digest, str) or not re.fullmatch('[a-f0-9]{64}', digest) or not isinstance(bundle, str):
raise ValueError('В обновлении нет проверяемого скрипта обслуживания журналов.')
unpack = zlib.decompressobj()
data = unpack.decompress(base64.b64decode(bundle, validate=True), 131073)
if not unpack.eof or unpack.unused_data or not 5000 <= len(data) <= 131072:
raise ValueError('Некорректный размер скрипта обслуживания журналов.')
if hashlib.sha256(data).hexdigest() != digest:
raise ValueError('Контрольная сумма скрипта обслуживания журналов не совпала.')
compile(data, 'log-maintenance.py', 'exec', dont_inherit=True)
return data, digest
def hub_log_maintenance_directory(directory, job_id):
if not re.fullmatch('[a-f0-9]{32}', str(job_id)):
raise ValueError('Некорректный идентификатор обновления.')
return Path(directory) / ('log-maintenance-' + job_id)
def hub_log_maintenance_receipt(directory, job_id):
try:
path = hub_log_maintenance_directory(directory, job_id) / 'receipt.json'
with path.open('rb') as stream:
data = json.loads(stream.read(8193))
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
return {}
def hub_log_maintenance_command(args, deadline):
remaining = deadline - time.monotonic()
if remaining <= 0:
raise RuntimeError('Истекло время настройки обслуживания журналов.')
result = subprocess.run(args, capture_output=True, text=True, errors='replace',
timeout=remaining, env={**os.environ, 'DEBIAN_FRONTEND': 'noninteractive'})
if result.returncode:
detail = ((result.stdout or '') + '\n' + (result.stderr or '')).strip()[-2000:]
raise RuntimeError('Обслуживание журналов: rc=' + str(result.returncode) + '; ' + detail)
return result
def hub_rollback_log_maintenance(directory, job_id):
stage = hub_log_maintenance_directory(directory, job_id)
if (stage / 'backup/manifest.json').is_file():
hub_log_maintenance_command([sys.executable, str(stage / 'log-maintenance.py'), 'rollback',
'--backup', str(stage / 'backup')], time.monotonic() + 45)
def hub_install_log_maintenance(directory, job_id, source=None, budget=120):
data, digest = hub_log_maintenance_payload(source)
stage = hub_log_maintenance_directory(directory, job_id)
stage.mkdir(mode=0o700, parents=True, exist_ok=True)
script, backup = stage / 'log-maintenance.py', stage / 'backup'
receipt = {'job_id': job_id, 'sha256': digest, 'status': 'installing'}
def save(status, error=''):
receipt.update(status=status, error=error[:2000], updated_at=time.time())
hub_update_write(stage / 'receipt.json', json.dumps(receipt, ensure_ascii=False).encode())
hub_update_write(script, data, 0o700)
save('installing')
deadline = time.monotonic() + budget
try:
if not shutil.which('logrotate'):
if not shutil.which('apt-get'):
raise RuntimeError('Не найден logrotate и пакетный менеджер apt-get.')
# Existing Ubuntu/Debian package indexes; never an unbounded apt update.
hub_log_maintenance_command(['apt-get', '-o', 'DPkg::Lock::Timeout=5', 'install', '-y', 'logrotate'],
min(deadline, time.monotonic() + 25))
hub_log_maintenance_command([sys.executable, str(script), 'install', '--backup', str(backup)], deadline)
hub_log_maintenance_command([sys.executable, str(script), 'run'], deadline)
result = json.loads(HUB_LOG_MAINTENANCE_RESULT.read_text())
if not result.get('ok') or result.get('day') != dt.date.today().isoformat():
raise RuntimeError('Успешное обслуживание журналов за текущие сутки не подтверждено: ' + str(result.get('error', 'нет результата'))[:500])
hub_log_maintenance_command(['systemctl', 'is-active', 'logrotate.timer'], deadline)
hub_log_maintenance_command(['systemctl', 'is-enabled', 'logrotate.timer'], deadline)
save('ready')
except Exception as exc:
reason = str(exc)
try:
hub_rollback_log_maintenance(directory, job_id)
except Exception as rollback:
reason += '; ошибка отката настроек журналов: ' + str(rollback)
save('failed', reason)
raise RuntimeError(reason) from exc
return receipt
def hub_prune_log_maintenance_backups(directory, job_id):
"""Keep this update's snapshot and one prior snapshot, never router data."""
current = hub_log_maintenance_directory(directory, job_id)
old = sorted((p for p in Path(directory).iterdir() if p != current and not p.is_symlink()
and p.is_dir() and re.fullmatch('log-maintenance-[a-f0-9]{32}', p.name)),
key=lambda p: p.stat().st_mtime, reverse=True)
for path in old[1:]:
shutil.rmtree(path)
def hub_update_state(directory, value=None):
path = Path(directory) / 'job.json'
if value is not None:
@@ -16075,6 +16295,7 @@ def run_hub_update_worker(job_id, directory=None, target=None):
if job.get('id') != job_id or job.get('status') != 'starting':
raise RuntimeError('Задача обновления устарела или уже запущена.')
changed = False
maintenance_installed = False
previous = None
candidate = directory / 'candidate.py'
def report(status, message):
@@ -16090,6 +16311,9 @@ def run_hub_update_worker(job_id, directory=None, target=None):
raise RuntimeError('Файл Hub изменился после подтверждения; обнови страницу.')
hub_update_require_version(data, hub_update_version(previous))
hub_update_write(directory / 'previous.py', previous, 0o700)
report('installing', 'Устанавливается обслуживание журналов; проверяется очистка и таймер…')
hub_install_log_maintenance(directory, job_id, source=data)
maintenance_installed = True
report('installing', 'Устанавливается новая сборка панели…')
hub_update_write(target, data, 0o755)
changed = True
@@ -16097,10 +16321,19 @@ def run_hub_update_worker(job_id, directory=None, target=None):
subprocess.run(['systemctl', 'restart', 'owrt-remote'], check=True, capture_output=True, timeout=35)
if not hub_update_health(job['health_url'], job['revision']):
raise RuntimeError('Новая сборка не прошла проверку работоспособности.')
report('succeeded', 'Панель успешно обновлена. Страница будет перезагружена.')
report('succeeded', 'Панель обновлена. Обслуживание журналов и таймер проверены. Страница будет перезагружена.')
try:
hub_prune_log_maintenance_backups(directory, job_id)
except OSError as cleanup_error:
print('Не удалось убрать старую резервную копию обслуживания журналов: ' + str(cleanup_error), file=sys.stderr)
return 0
except Exception as exc:
reason = str(exc)[:500]
if maintenance_installed:
try:
hub_rollback_log_maintenance(directory, job_id)
except Exception as rollback_exc:
reason += ' Ошибка отката настроек журналов: ' + str(rollback_exc)[:300]
if changed and previous is not None:
try:
report('rollback', 'Ошибка обновления; восстанавливается предыдущая сборка…')
@@ -16135,6 +16368,45 @@ class HubUpdateManager:
self.remote_revision = ''
self.remote_version = ''
self.health_url = 'http://127.0.0.1:8088/health'
self.log_maintenance_status = ''
self.log_maintenance_error = ''
def resume_log_maintenance(self):
"""Bridge the first update, whose still-running worker is from old Hub.
That worker waits for the new Hub's revision health. Hold only that
health confirmation until installation finishes; heartbeat stays live.
New workers install the component beforehand and already have a receipt.
"""
if self.log_maintenance_status:
return
job = hub_update_state(self.directory)
if (job.get('status') not in {'restarting', 'succeeded'} or job.get('revision') != HUB_LOADED_REVISION
or time.time() - job.get('started_at', 0) > 420):
return
receipt = hub_log_maintenance_receipt(self.directory, job.get('id'))
if receipt.get('status') == 'ready' and receipt.get('sha256') == HUB_LOG_MAINTENANCE_SHA256:
return
self.log_maintenance_status = 'installing'
def install():
try:
# The old worker's health wait is about a minute. Fail/restore
# within that budget rather than install after its rollback.
hub_install_log_maintenance(self.directory, job['id'], budget=40)
self.log_maintenance_status = 'ready'
try:
hub_prune_log_maintenance_backups(self.directory, job['id'])
except OSError as cleanup_error:
print('Не удалось убрать старую резервную копию обслуживания журналов: ' + str(cleanup_error), file=sys.stderr)
except Exception as exc:
self.log_maintenance_error = str(exc)[:2000]
self.log_maintenance_status = 'failed'
print('Ошибка установки обслуживания журналов при обновлении: ' + str(exc), file=sys.stderr)
try:
threading.Thread(target=install, name='owrt-log-maintenance-bootstrap', daemon=True).start()
except Exception as exc:
self.log_maintenance_error = str(exc)[:2000]
self.log_maintenance_status = 'failed'
def check(self, force=False):
with self.lock:
@@ -16166,6 +16438,7 @@ class HubUpdateManager:
try:
data = self.fetch_candidate()
hub_update_validate(data)
hub_log_maintenance_payload(data)
except Exception as exc:
error = 'Не удалось проверить обновление: ' + str(exc)[:300]
with self.lock:
@@ -16179,6 +16452,11 @@ class HubUpdateManager:
def snapshot(self):
with self.lock:
job = hub_update_state(self.directory)
if job.get('revision') == HUB_LOADED_REVISION:
if self.log_maintenance_status == 'installing':
job = {**job, 'status': 'installing', 'message': 'Настраивается обслуживание журналов; ожидается проверка очистки и таймера…'}
elif self.log_maintenance_status == 'failed':
job = {**job, 'status': 'failed', 'message': 'Обслуживание журналов не установлено: ' + self.log_maintenance_error}
if job.get('status') in HUB_UPDATE_ACTIVE and time.time() - job.get('started_at', 0) > 420:
job.update(status='failed', message='Процесс обновления прерван. Итог не подтверждён; проверь сервис owrt-remote на VPS.')
hub_update_state(self.directory, job)
@@ -16197,6 +16475,8 @@ class HubUpdateManager:
job = hub_update_state(self.directory)
if job.get('status') in HUB_UPDATE_ACTIVE:
raise RuntimeError('Обновление панели уже выполняется.')
if self.log_maintenance_status == 'installing':
raise RuntimeError('Ещё устанавливается обслуживание журналов.')
if not revision or revision != self.remote_revision or not self.candidate or self.error or self.checking:
raise ValueError('Результат проверки устарел. Проверь обновление ещё раз.')
if revision == HUB_LOADED_REVISION:
@@ -16314,22 +16594,22 @@ class Handler(BaseHTTPRequestHandler):
return self.server.app
def log_message(self, fmt, *args):
# Successful long-poll and terminal-read responses are expected to be
# frequent. Nginx and journald already retain their failures; avoid
# writing a line for every normal 200 response while keeping 4xx/5xx
# diagnostics visible.
path = urllib.parse.urlsplit(str(self.path or "")).path
# Only suppress ordinary successful access records. Application errors,
# audit events and 4xx/5xx responses must still reach stderr/journald.
path = urllib.parse.urlsplit(str(getattr(self, "path", "") or "")).path
status = 0
if len(args) > 1:
if fmt == '"%s" %s %s' and len(args) == 3:
try:
status = int(str(args[1]))
except (TypeError, ValueError):
status = 0
quiet = (
path == "/api/notifications/wait"
or path in ("/api/heartbeat", "/api/router-logs")
or re.fullmatch(r"/api/ssh-session/[^/]+/read", path or "")
)
if quiet and 200 <= status < 400:
debug = os.environ.get("OWRT_REMOTE_HTTP_DEBUG", "").lower() in ("1", "true", "yes")
if quiet and 200 <= status < 400 and not debug:
return
sys.stderr.write("%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), fmt % args))
@@ -19412,6 +19692,11 @@ exit 127
result = {"ok": True}
if self.query().get('panel-update') == ['1']:
result['revision'] = HUB_LOADED_REVISION
maintenance = self.app.hub_update
if maintenance.log_maintenance_status in {'installing', 'failed'}:
result['ok'] = False
result['log_maintenance'] = {'status': maintenance.log_maintenance_status,
'error': maintenance.log_maintenance_error}
if self.query().get("request-load-fix") == ["1"]:
result["notification_wait"] = notification_wait_metrics()
self.send_json(200, result)
@@ -21064,6 +21349,7 @@ def cmd_serve(args):
extra_servers.append((extra, thread))
try:
app.hub_update.resume_log_maintenance()
app.start_router_state_monitor()
tls_ports = parse_extra_ports(args.tls_ports) if args.tls_cert and args.tls_key else []
tls_port_set = set(tls_ports)