deploy fix
This commit is contained in:
parent
1ea2d31d77
commit
4f502c5cec
12 changed files with 394 additions and 1224 deletions
|
|
@ -171,6 +171,25 @@ jobs:
|
|||
cd ~/mnemo_cards/tools/deploy
|
||||
./generate-nginx-configs.sh
|
||||
|
||||
echo "🧹 Checking for potential conflicts..."
|
||||
|
||||
# Check if nginx.conf includes generated_configs directly (this would cause duplication)
|
||||
if grep -q "generated_configs" /etc/nginx/nginx.conf; then
|
||||
echo "⚠️ WARNING: nginx.conf includes generated_configs directly!"
|
||||
echo "This may cause server_name conflicts. Please remove the include line:"
|
||||
grep -n "generated_configs" /etc/nginx/nginx.conf
|
||||
echo "For now, proceeding with sites-enabled approach..."
|
||||
fi
|
||||
|
||||
# Check for existing conflicting server blocks
|
||||
echo "📊 Checking for existing server_name conflicts..."
|
||||
for domain in "mnemo-cards.online" "code.mnemo-cards.online" "vscode.mnemo-cards.online"; do
|
||||
if grep -r "server_name $domain" /etc/nginx/sites-enabled/ 2>/dev/null | grep -v "$domain.conf:"; then
|
||||
echo "⚠️ Found conflicting server_name $domain in other files:"
|
||||
grep -r "server_name $domain" /etc/nginx/sites-enabled/ 2>/dev/null
|
||||
fi
|
||||
done
|
||||
|
||||
echo "🧹 Cleaning up old configuration files..."
|
||||
# Remove old files without .conf extension that might cause conflicts
|
||||
rm -f /etc/nginx/sites-available/forgejo
|
||||
|
|
@ -178,9 +197,14 @@ jobs:
|
|||
rm -f /etc/nginx/sites-available/vscode.mnemo-cards.online
|
||||
rm -f /etc/nginx/sites-available/mnemo_cards
|
||||
rm -f /etc/nginx/sites-available/mnemo_cards_main
|
||||
|
||||
# Remove any existing .conf files that we're about to replace
|
||||
rm -f /etc/nginx/sites-enabled/vscode.mnemo-cards.online.conf
|
||||
rm -f /etc/nginx/sites-enabled/code.mnemo-cards.online.conf
|
||||
rm -f /etc/nginx/sites-enabled/mnemo-cards.online.conf
|
||||
rm -f /etc/nginx/sites-available/vscode.mnemo-cards.online.conf
|
||||
rm -f /etc/nginx/sites-available/code.mnemo-cards.online.conf
|
||||
rm -f /etc/nginx/sites-available/mnemo-cards.online.conf
|
||||
|
||||
echo "📋 Deploying new configurations..."
|
||||
cp generated_configs/*.conf /etc/nginx/sites-available/
|
||||
|
|
@ -198,7 +222,19 @@ jobs:
|
|||
echo "✅ nginx reloaded successfully"
|
||||
else
|
||||
echo "❌ Configuration test failed!"
|
||||
/usr/sbin/nginx -t || true
|
||||
echo "🔍 Debugging configuration errors..."
|
||||
/usr/sbin/nginx -t 2>&1 || true
|
||||
|
||||
# Try to identify the problematic file
|
||||
echo "🔍 Checking individual site configs..."
|
||||
for config in /etc/nginx/sites-enabled/*.conf; do
|
||||
echo "Testing $(basename "$config")..."
|
||||
if ! /usr/sbin/nginx -t -c /etc/nginx/nginx.conf -g "include $config;" 2>/dev/null; then
|
||||
echo "❌ Error in $(basename "$config")"
|
||||
head -20 "$config"
|
||||
fi
|
||||
done
|
||||
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
|
@ -243,7 +279,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ghcr.io/cirruslabs/flutter:3.35.5
|
||||
options: --memory=1024m --memory-swap=4096m
|
||||
options: --memory=1536m --memory-swap=2048m
|
||||
needs: deploy-backend
|
||||
if: always() && needs.deploy-backend.result == 'success'
|
||||
steps:
|
||||
|
|
@ -283,16 +319,20 @@ jobs:
|
|||
- name: Build Web App
|
||||
working-directory: mnemo_cards_web_v2
|
||||
env:
|
||||
# Limit Dart VM memory usage (1GB for Dart, 512MB for Node.js)
|
||||
DART_VM_OPTIONS: "--old-gen-heap-size=1024 --max-old-space-size=1024"
|
||||
# Limit Node.js memory for dart2js compilation
|
||||
# Optimized Dart VM memory usage (896MB for Dart, 512MB for Node.js)
|
||||
DART_VM_OPTIONS: "--old-gen-heap-size=896 --max-old-space-size=896"
|
||||
# Node.js memory for dart2js compilation
|
||||
NODE_OPTIONS: "--max-old-space-size=512"
|
||||
# Limit parallel compilation to reduce memory pressure
|
||||
FLUTTER_BUILD_PARALLEL: "1"
|
||||
# Disable analytics to save memory
|
||||
FLUTTER_ANALYTICS_DISABLED: "true"
|
||||
# Reduce GC pressure
|
||||
DART_FLAGS: "--disable-dart-dev"
|
||||
DART_FLAGS: "--disable-dart-dev --no-background-compilation"
|
||||
# Additional memory optimization
|
||||
FLUTTER_WEB_USE_SKIA: "false"
|
||||
# Disable web security for faster builds
|
||||
FLUTTER_WEB_DISABLE_SECURITY: "true"
|
||||
run: |
|
||||
echo "🔍 Проверяем Flutter..."
|
||||
which flutter || echo "Flutter not found in PATH"
|
||||
|
|
@ -307,29 +347,88 @@ jobs:
|
|||
rm -rf ~/.pub-cache/hosted/pub.dev/.cache || true
|
||||
rm -rf ~/.dartServer || true
|
||||
rm -rf ~/.flutter-devtools || true
|
||||
rm -rf ~/.flutter/bin/cache/dart-sdk/bin/snapshots/*.snapshot || true
|
||||
rm -rf /tmp/dart* || true
|
||||
rm -rf /tmp/flutter* || true
|
||||
|
||||
rm -rf .dart_tool/cache || true
|
||||
|
||||
# Drop caches to free memory (if available)
|
||||
echo 3 > /proc/sys/vm/drop_caches 2>/dev/null || true
|
||||
|
||||
|
||||
# Kill any lingering Dart/Flutter processes
|
||||
pkill -f dart || true
|
||||
pkill -f flutter || true
|
||||
sleep 2
|
||||
|
||||
# Sync memory to disk to free up RAM
|
||||
sync || true
|
||||
|
||||
echo "📦 Получаем зависимости..."
|
||||
timeout 300 flutter pub get || (echo "❌ Flutter pub get failed" && exit 1)
|
||||
|
||||
|
||||
# Free memory after pub get
|
||||
echo 3 > /proc/sys/vm/drop_caches 2>/dev/null || true
|
||||
sync || true
|
||||
|
||||
# Final memory cleanup before build
|
||||
echo "🧹 Финальная очистка памяти перед сборкой..."
|
||||
echo 3 > /proc/sys/vm/drop_caches 2>/dev/null || true
|
||||
sync || true
|
||||
sleep 2
|
||||
|
||||
echo "📊 Память перед сборкой:"
|
||||
free -h || true
|
||||
|
||||
echo "🔨 Собираем веб-приложение (оптимизировано для 1.5GB памяти)..."
|
||||
# Use O1 optimization (lowest memory usage, still production-ready)
|
||||
# Build with minimal parallelization to avoid OOM
|
||||
# Additional flags to reduce memory footprint
|
||||
timeout 1800 flutter build web --release \
|
||||
|
||||
# Try multiple build strategies, starting with most memory-efficient
|
||||
echo "🌐 Стратегия 1: WASM сборка с минимальными опциями..."
|
||||
if timeout 1800 flutter build web --release \
|
||||
--dart-define=API_BASE_URL=https://api.mnemo-cards.online \
|
||||
--dart2js-optimization=O1 \
|
||||
--no-tree-shake-icons || (echo "❌ Flutter build failed" && exit 1)
|
||||
--wasm \
|
||||
--no-tree-shake-icons \
|
||||
--dart2js-optimization=O1; then
|
||||
echo "✅ WASM сборка успешна"
|
||||
else
|
||||
echo "⚠️ WASM не удался, стратегия 2: dart2js с максимальной оптимизацией..."
|
||||
|
||||
# Aggressive memory optimization for dart2js
|
||||
export DART_VM_OPTIONS="$DART_VM_OPTIONS --gc-on-threshold --low-memory-mode --enable-isolate-groups --use-slow-path"
|
||||
echo "🔧 Используем агрессивные настройки памяти: $DART_VM_OPTIONS"
|
||||
timeout 1800 bash -c '
|
||||
# Monitor memory usage during build
|
||||
(
|
||||
while true; do
|
||||
echo "$(date +%H:%M:%S) Memory: $(free -m | grep Mem: | awk '\''{printf "%.1fGB", $3/1024}'\'')" >> /tmp/memory.log
|
||||
sleep 10
|
||||
done
|
||||
) &
|
||||
MONITOR_PID=$!
|
||||
|
||||
# Build with memory monitoring
|
||||
flutter build web --release \
|
||||
--dart-define=API_BASE_URL=https://api.mnemo-cards.online \
|
||||
--dart2js-optimization=O1 \
|
||||
--no-tree-shake-icons \
|
||||
--split-debug-info=/tmp/debug-info \
|
||||
--no-pub \
|
||||
--suppress-analytics
|
||||
|
||||
BUILD_RESULT=$?
|
||||
kill $MONITOR_PID 2>/dev/null || true
|
||||
|
||||
if [ $BUILD_RESULT -eq 0 ]; then
|
||||
echo "✅ dart2js сборка успешна"
|
||||
echo "📊 Лог использования памяти:"
|
||||
cat /tmp/memory.log || true
|
||||
else
|
||||
echo "❌ Flutter build failed"
|
||||
echo "📊 Лог использования памяти:"
|
||||
cat /tmp/memory.log || true
|
||||
exit 1
|
||||
fi
|
||||
' || (echo "❌ Flutter build failed" && exit 1)
|
||||
fi
|
||||
|
||||
echo "✅ Сборка завершена"
|
||||
|
||||
|
|
|
|||
|
|
@ -1,203 +0,0 @@
|
|||
# Отчет об исправлении Backend Server
|
||||
**Дата**: 19 ноября 2025
|
||||
**Проблема**: Backend сервер падал при сборке с ошибкой "Address already in use, port = 8443"
|
||||
|
||||
## Причина проблемы
|
||||
|
||||
**Конфликт портов**: Backend сервер и code-server (VSCode) были настроены на один и тот же порт **8443**.
|
||||
|
||||
### Хронология
|
||||
1. При восстановлении VSCode Server мы настроили code-server на порт 8443
|
||||
2. Backend сервер также был настроен на порт 8443
|
||||
3. При попытке запуска backend получал ошибку: `SocketException: Address already in use, port = 8443`
|
||||
4. Systemd пытался перезапустить сервис 5 раз и сдался
|
||||
|
||||
## Решение
|
||||
|
||||
### 1. Изменение порта Backend
|
||||
- **Старый порт**: 8443 (конфликт с code-server)
|
||||
- **Новый порт**: 8081 (стандартный порт для API)
|
||||
|
||||
### 2. Обновление конфигураций
|
||||
|
||||
#### systemd Service
|
||||
Файл: `/etc/systemd/system/mnemo_cards_server.service`
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
ExecStart=/root/mnemo_cards_backend/server.exe -a 0.0.0.0 -p 8081
|
||||
```
|
||||
Изменено: `-p 8443` → `-p 8081`
|
||||
|
||||
#### nginx Configuration
|
||||
Файл: `/etc/nginx/sites-available/api`
|
||||
|
||||
```nginx
|
||||
location / {
|
||||
proxy_pass http://localhost:8081; # было: https://localhost:8443
|
||||
}
|
||||
```
|
||||
Изменения:
|
||||
- Порт: 8443 → 8081
|
||||
- Протокол: https → http (SSL терминируется в nginx)
|
||||
|
||||
### 3. Включение автозапуска
|
||||
```bash
|
||||
systemctl enable mnemo_cards_server
|
||||
```
|
||||
|
||||
## Результаты
|
||||
|
||||
### ✅ Backend Server
|
||||
```bash
|
||||
● mnemo_cards_server.service - MnemoCardsServer
|
||||
Loaded: loaded (/etc/systemd/system/mnemo_cards_server.service; enabled)
|
||||
Active: active (running)
|
||||
```
|
||||
|
||||
### ✅ Порты
|
||||
|
||||
| Сервис | Порт | Адрес | Статус |
|
||||
|--------|------|-------|--------|
|
||||
| code-server (VSCode) | 8443 | 127.0.0.1 | ✅ Работает |
|
||||
| backend (API) | 8081 | 0.0.0.0 | ✅ Работает |
|
||||
| nginx (HTTPS) | 443 | 0.0.0.0 | ✅ Работает |
|
||||
|
||||
### ✅ Доступность API
|
||||
```bash
|
||||
curl -I https://api.mnemo-cards.online/
|
||||
|
||||
HTTP/2 404
|
||||
server: nginx/1.18.0 (Ubuntu)
|
||||
access-control-allow-origin: *
|
||||
```
|
||||
✅ Сервер отвечает (404 нормально для корневого пути)
|
||||
|
||||
## Архитектура
|
||||
|
||||
```
|
||||
Internet
|
||||
↓
|
||||
nginx (port 443) - SSL Termination
|
||||
├─→ api.mnemo-cards.online → http://localhost:8081 (Backend)
|
||||
└─→ vscode.mnemo-cards.online → http://127.0.0.1:8443 (VSCode)
|
||||
```
|
||||
|
||||
## Созданные инструменты
|
||||
|
||||
### fix-backend-port-conflict.sh
|
||||
Автоматический скрипт для исправления конфликта портов:
|
||||
- Изменяет порт в systemd service
|
||||
- Обновляет nginx конфигурацию
|
||||
- Перезапускает сервисы
|
||||
- Проверяет работоспособность
|
||||
|
||||
**Использование**:
|
||||
```bash
|
||||
cd /Users/dmitry/StudioProjects/mnemo_cards/tools/deploy
|
||||
./fix-backend-port-conflict.sh
|
||||
```
|
||||
|
||||
## Управление Backend
|
||||
|
||||
### Проверка статуса
|
||||
```bash
|
||||
ssh root@147.45.152.129 'systemctl status mnemo_cards_server'
|
||||
```
|
||||
|
||||
### Просмотр логов
|
||||
```bash
|
||||
ssh root@147.45.152.129 'journalctl -u mnemo_cards_server -f'
|
||||
```
|
||||
|
||||
### Перезапуск
|
||||
```bash
|
||||
ssh root@147.45.152.129 'systemctl restart mnemo_cards_server'
|
||||
```
|
||||
|
||||
### Проверка порта
|
||||
```bash
|
||||
ssh root@147.45.152.129 'ss -tuln | grep 8081'
|
||||
```
|
||||
|
||||
## Предотвращение проблем в будущем
|
||||
|
||||
### ✅ Сделано
|
||||
1. Backend настроен на автозапуск при загрузке
|
||||
2. Backend использует уникальный порт (8081)
|
||||
3. Созданы скрипты для быстрого восстановления
|
||||
4. Документирована архитектура и порты
|
||||
|
||||
### 📋 Рекомендации
|
||||
1. При добавлении новых сервисов проверять свободные порты
|
||||
2. Документировать используемые порты в конфигурации
|
||||
3. Использовать стандартные порты:
|
||||
- Backend API: 8081
|
||||
- VSCode: 8443
|
||||
- Forgejo: 3000
|
||||
- Frontend: через nginx на 443
|
||||
|
||||
## Тестирование
|
||||
|
||||
### Тест 1: Backend работает
|
||||
```bash
|
||||
ssh root@147.45.152.129 'curl -I http://localhost:8081/'
|
||||
# ✅ HTTP/1.1 404 Not Found
|
||||
```
|
||||
|
||||
### Тест 2: nginx проксирует на backend
|
||||
```bash
|
||||
ssh root@147.45.152.129 'curl -I https://api.mnemo-cards.online/'
|
||||
# ✅ HTTP/2 404
|
||||
```
|
||||
|
||||
### Тест 3: VSCode работает
|
||||
```bash
|
||||
ssh root@147.45.152.129 'curl -I http://127.0.0.1:8443/'
|
||||
# ✅ HTTP/1.1 302 Found (redirect to login)
|
||||
```
|
||||
|
||||
### Тест 4: Порты не конфликтуют
|
||||
```bash
|
||||
ssh root@147.45.152.129 'ss -tuln | grep -E "(8081|8443)"'
|
||||
# ✅ Оба порта слушают без ошибок
|
||||
```
|
||||
|
||||
## Время восстановления
|
||||
|
||||
- **Обнаружение проблемы**: 22:34
|
||||
- **Диагностика**: 22:35
|
||||
- **Исправление**: 22:37
|
||||
- **Проверка**: 22:39
|
||||
|
||||
**Общее время**: ~5 минут
|
||||
|
||||
## Статус
|
||||
|
||||
🟢 **RESOLVED**
|
||||
|
||||
### Работающие сервисы
|
||||
- ✅ Backend API: https://api.mnemo-cards.online/
|
||||
- ✅ VSCode Server: https://vscode.mnemo-cards.online/
|
||||
- ✅ Forgejo Git: https://code.mnemo-cards.online/
|
||||
|
||||
### Автозапуск
|
||||
- ✅ mnemo_cards_server: enabled
|
||||
- ✅ code-server: enabled
|
||||
- ✅ nginx: enabled
|
||||
|
||||
## Дополнительная информация
|
||||
|
||||
### Связанные документы
|
||||
- [VSCODE_SERVER_SETUP.md](./VSCODE_SERVER_SETUP.md) - Настройка VSCode Server
|
||||
- [RECOVERY_REPORT_2025-11-19.md](./RECOVERY_REPORT_2025-11-19.md) - Восстановление VSCode
|
||||
- [README.md](./README.md) - Общая документация по деплою
|
||||
|
||||
### Скрипты
|
||||
- `fix-backend-port-conflict.sh` - Исправление конфликта портов
|
||||
- `fix-vscode-server.sh` - Восстановление VSCode Server
|
||||
|
||||
---
|
||||
|
||||
**Вывод**: Проблема полностью решена. Backend сервер работает на порту 8081, конфликт с VSCode устранен. Все сервисы настроены на автозапуск при перезагрузке сервера.
|
||||
|
||||
|
|
@ -1,120 +0,0 @@
|
|||
# Исправление скриптов сборки Backend
|
||||
|
||||
**Дата**: 19 ноября 2025
|
||||
**Проблема**: После исправления конфликта портов (8443 → 8081), скрипты сборки backend возвращали порт обратно на 8443
|
||||
|
||||
## Исправленные файлы
|
||||
|
||||
Изменены все скрипты сборки для использования порта **8081** вместо **8443**:
|
||||
|
||||
### 1. mnemo_cards_backend/build_app.sh
|
||||
Все вхождения `-p 8443` заменены на `-p 8081`
|
||||
|
||||
**Исправленные строки**:
|
||||
- Строка 25: Dual mode с сертификатами
|
||||
- Строка 38: Dual mode если сертификат создан
|
||||
- Строка 46: HTTP mode если сертификат не создан
|
||||
|
||||
### 2. tools/deploy/backend/server_build.sh
|
||||
Все вхождения `-p 8443` заменены на `-p 8081`
|
||||
|
||||
**Исправленные строки**:
|
||||
- Строка 36: Dual mode с сертификатами
|
||||
- Строка 39: HTTP mode без сертификатов
|
||||
|
||||
### 3. tools/deploy/backend-build_app.sh
|
||||
Все вхождения `-p 8443` заменены на `-p 8081`
|
||||
|
||||
**Исправленные строки**:
|
||||
- Строка 30: HTTPS-only режим
|
||||
- Строка 74: HTTPS-only после создания сертификата
|
||||
- Строка 83: HTTP режим (fallback)
|
||||
|
||||
## Причина проблемы
|
||||
|
||||
Скрипты сборки backend содержали жестко закодированный порт **8443**, который конфликтовал с code-server (VSCode).
|
||||
|
||||
### Последовательность событий:
|
||||
1. ✅ Backend исправлен вручную на порт 8081
|
||||
2. ❌ Запущен скрипт сборки backend
|
||||
3. ❌ Скрипт перезаписал systemd service с портом 8443
|
||||
4. ❌ Backend упал с ошибкой "Address already in use"
|
||||
5. ✅ Исправлены все скрипты сборки
|
||||
6. ✅ Backend восстановлен на порту 8081
|
||||
|
||||
## Решение
|
||||
|
||||
### Автоматическое
|
||||
Используйте скрипт восстановления:
|
||||
```bash
|
||||
cd /Users/dmitry/StudioProjects/mnemo_cards/tools/deploy
|
||||
./fix-backend-port-conflict.sh
|
||||
```
|
||||
|
||||
### Ручное
|
||||
Если нужно вручную:
|
||||
```bash
|
||||
ssh root@147.45.152.129
|
||||
|
||||
# Исправить порт в systemd service
|
||||
sudo sed -i 's/-p 8443/-p 8081/g' /etc/systemd/system/mnemo_cards_server.service
|
||||
|
||||
# Перезапустить
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl restart mnemo_cards_server
|
||||
```
|
||||
|
||||
## Проверка
|
||||
|
||||
После сборки backend проверьте, что используется правильный порт:
|
||||
|
||||
```bash
|
||||
# Проверка systemd service
|
||||
ssh root@147.45.152.129 'cat /etc/systemd/system/mnemo_cards_server.service | grep ExecStart'
|
||||
# Должно быть: -p 8081
|
||||
|
||||
# Проверка порта
|
||||
ssh root@147.45.152.129 'ss -tuln | grep 8081'
|
||||
# Должно показать: 0.0.0.0:8081
|
||||
|
||||
# Проверка статуса
|
||||
ssh root@147.45.152.129 'systemctl status mnemo_cards_server'
|
||||
# Должно быть: Active: active (running)
|
||||
```
|
||||
|
||||
## Распределение портов
|
||||
|
||||
| Сервис | Порт | Адрес | Назначение |
|
||||
|--------|------|-------|-----------|
|
||||
| **Backend API** | 8081 | 0.0.0.0 | HTTP API (SSL в nginx) |
|
||||
| **code-server** | 8443 | 127.0.0.1 | VSCode Server |
|
||||
| **Forgejo** | 3000 | 127.0.0.1 | Git Server |
|
||||
| **nginx** | 443 | 0.0.0.0 | HTTPS Proxy |
|
||||
|
||||
## Текущий статус
|
||||
|
||||
🟢 **ВСЕ ИСПРАВЛЕНО**
|
||||
|
||||
- ✅ Скрипты сборки используют порт 8081
|
||||
- ✅ Backend работает на порту 8081
|
||||
- ✅ code-server работает на порту 8443
|
||||
- ✅ Конфликт портов устранен
|
||||
- ✅ Все сервисы работают стабильно
|
||||
|
||||
## Важно для будущего
|
||||
|
||||
⚠️ **При добавлении новых скриптов сборки**:
|
||||
- Всегда используйте порт **8081** для backend
|
||||
- Порт **8443** зарезервирован для code-server
|
||||
- Документируйте используемые порты
|
||||
|
||||
## Связанные документы
|
||||
|
||||
- [BACKEND_FIX_REPORT_2025-11-19.md](./BACKEND_FIX_REPORT_2025-11-19.md) - Первичное исправление
|
||||
- [fix-backend-port-conflict.sh](./fix-backend-port-conflict.sh) - Скрипт восстановления
|
||||
- [README.md](./README.md) - Общая документация
|
||||
|
||||
---
|
||||
|
||||
**Вывод**: Все скрипты сборки backend теперь используют правильный порт 8081. Конфликт с VSCode больше не возникнет при сборке.
|
||||
|
||||
|
|
@ -1,172 +0,0 @@
|
|||
# Fail2ban Whitelist Configuration
|
||||
|
||||
**Дата**: 19 ноября 2025
|
||||
**Статус**: ✅ Настроено
|
||||
|
||||
## Проблема
|
||||
|
||||
Fail2ban блокировал IP администратора (89.19.210.178) при установке Flutter и интенсивном использовании VSCode Server.
|
||||
|
||||
## Решение
|
||||
|
||||
Добавлен IP администратора в whitelist (ignoreip) для всех VSCode jail'ов.
|
||||
|
||||
## Конфигурация
|
||||
|
||||
**Файл**: `/etc/fail2ban/jail.d/vscode.conf`
|
||||
|
||||
```ini
|
||||
[vscode]
|
||||
enabled = true
|
||||
port = http,https
|
||||
filter = vscode
|
||||
logpath = /var/log/nginx/access.log
|
||||
maxretry = 3
|
||||
bantime = 3600
|
||||
findtime = 600
|
||||
ignoreip = 127.0.0.1/8 ::1 89.19.210.178
|
||||
|
||||
[vscode-ddos]
|
||||
enabled = true
|
||||
port = http,https
|
||||
filter = vscode-ddos
|
||||
logpath = /var/log/nginx/access.log
|
||||
maxretry = 100
|
||||
bantime = 600
|
||||
findtime = 60
|
||||
ignoreip = 127.0.0.1/8 ::1 89.19.210.178
|
||||
```
|
||||
|
||||
## Что означает ignoreip
|
||||
|
||||
- `127.0.0.1/8` - локальные IP адреса (localhost)
|
||||
- `::1` - IPv6 localhost
|
||||
- `89.19.210.178` - ваш текущий внешний IP
|
||||
|
||||
## Параметры защиты
|
||||
|
||||
### vscode jail
|
||||
- **maxretry**: 3 попытки
|
||||
- **bantime**: 3600 секунд (1 час)
|
||||
- **findtime**: 600 секунд (10 минут)
|
||||
|
||||
Блокирует за 3 неудачные попытки входа в течение 10 минут на 1 час.
|
||||
|
||||
### vscode-ddos jail
|
||||
- **maxretry**: 100 запросов
|
||||
- **bantime**: 600 секунд (10 минут)
|
||||
- **findtime**: 60 секунд (1 минута)
|
||||
|
||||
Блокирует за более 100 запросов в минуту на 10 минут (защита от DDoS).
|
||||
|
||||
## Проверка
|
||||
|
||||
### Текущий статус
|
||||
```bash
|
||||
ssh root@147.45.152.129 'fail2ban-client status vscode-ddos'
|
||||
```
|
||||
|
||||
**Результат**:
|
||||
```
|
||||
Status for the jail: vscode-ddos
|
||||
|- Filter
|
||||
| |- Currently failed: 0
|
||||
| |- Total failed: 0
|
||||
`- Actions
|
||||
|- Currently banned: 0
|
||||
|- Total banned: 0
|
||||
`- Banned IP list:
|
||||
```
|
||||
✅ Нет заблокированных IP
|
||||
|
||||
### Проверка whitelist
|
||||
```bash
|
||||
ssh root@147.45.152.129 'fail2ban-client get vscode-ddos ignoreip'
|
||||
```
|
||||
|
||||
Должно показать: `127.0.0.1/8 ::1 89.19.210.178`
|
||||
|
||||
## Добавление нового IP в whitelist
|
||||
|
||||
Если ваш IP изменится или нужно добавить другой IP:
|
||||
|
||||
```bash
|
||||
ssh root@147.45.152.129
|
||||
|
||||
# Редактировать конфигурацию
|
||||
nano /etc/fail2ban/jail.d/vscode.conf
|
||||
|
||||
# Добавить новый IP в строку ignoreip через пробел
|
||||
ignoreip = 127.0.0.1/8 ::1 89.19.210.178 NEW_IP_HERE
|
||||
|
||||
# Перезапустить fail2ban
|
||||
systemctl restart fail2ban
|
||||
|
||||
# Проверить статус
|
||||
systemctl status fail2ban
|
||||
```
|
||||
|
||||
## Разблокировка IP вручную
|
||||
|
||||
Если всё же кто-то был заблокирован:
|
||||
|
||||
```bash
|
||||
# Посмотреть заблокированные IP
|
||||
ssh root@147.45.152.129 'fail2ban-client status vscode-ddos'
|
||||
|
||||
# Разблокировать конкретный IP
|
||||
ssh root@147.45.152.129 'fail2ban-client set vscode-ddos unbanip IP_ADDRESS'
|
||||
|
||||
# Пример
|
||||
ssh root@147.45.152.129 'fail2ban-client set vscode-ddos unbanip 89.19.210.178'
|
||||
```
|
||||
|
||||
## Логи
|
||||
|
||||
### Просмотр логов fail2ban
|
||||
```bash
|
||||
ssh root@147.45.152.129 'tail -f /var/log/fail2ban.log'
|
||||
```
|
||||
|
||||
### Просмотр nginx access log
|
||||
```bash
|
||||
ssh root@147.45.152.129 'tail -f /var/log/nginx/access.log | grep vscode'
|
||||
```
|
||||
|
||||
## Backup
|
||||
|
||||
Создан backup оригинальной конфигурации:
|
||||
```
|
||||
/etc/fail2ban/jail.d/vscode.conf.backup
|
||||
```
|
||||
|
||||
Для восстановления:
|
||||
```bash
|
||||
ssh root@147.45.152.129 'cp /etc/fail2ban/jail.d/vscode.conf.backup /etc/fail2ban/jail.d/vscode.conf && systemctl restart fail2ban'
|
||||
```
|
||||
|
||||
## Безопасность
|
||||
|
||||
✅ **Fail2ban продолжает работать** - защита от атак активна
|
||||
✅ **Ваш IP в whitelist** - вас больше не будет блокировать
|
||||
✅ **Другие IP защищены** - атаки с других адресов будут блокироваться
|
||||
|
||||
## Проверка после изменений
|
||||
|
||||
Все сервисы работают:
|
||||
|
||||
| Сервис | URL | Статус |
|
||||
|--------|-----|--------|
|
||||
| Forgejo | https://code.mnemo-cards.online/ | 🟢 Доступен |
|
||||
| VSCode | https://vscode.mnemo-cards.online/ | 🟢 Доступен |
|
||||
| Backend API | https://api.mnemo-cards.online/ | 🟢 Доступен |
|
||||
|
||||
## Связанные документы
|
||||
|
||||
- [VSCODE_SERVER_SETUP.md](./VSCODE_SERVER_SETUP.md) - Настройка VSCode Server
|
||||
- [RECOVERY_REPORT_2025-11-19.md](./RECOVERY_REPORT_2025-11-19.md) - Восстановление после перезагрузки
|
||||
|
||||
---
|
||||
|
||||
**Вывод**: Ваш IP (89.19.210.178) добавлен в whitelist. Fail2ban больше вас не заблокирует, но продолжит защищать сервер от атак с других IP адресов.
|
||||
|
||||
|
|
@ -1,184 +0,0 @@
|
|||
# Отчет о восстановлении VSCode Server
|
||||
**Дата**: 19 ноября 2025
|
||||
**Проблема**: После перезагрузки сервера не открываются vscode.mnemo-cards.online и code.mnemo-cards.online
|
||||
|
||||
## Выполненные работы
|
||||
|
||||
### 1. Диагностика ✅
|
||||
- Проверен статус code-server на сервере
|
||||
- Обнаружено, что code-server был запущен, но на неправильном порту (8080 вместо 8443)
|
||||
- Обнаружено отсутствие nginx конфигурации для vscode.mnemo-cards.online
|
||||
- Выявлена проблема с IPv6/IPv4 (nginx пытался подключиться к ::1 вместо 127.0.0.1)
|
||||
- Обнаружен конфликт доменных имен
|
||||
|
||||
### 2. Исправления ✅
|
||||
|
||||
#### code-server Service
|
||||
- Создан правильный systemd service файл `/etc/systemd/system/code-server.service`
|
||||
- Настроен автозапуск при загрузке системы (`systemctl enable`)
|
||||
- Исправлен порт с 8080 на 8443
|
||||
- Настроен bind на 127.0.0.1:8443 (IPv4)
|
||||
- Добавлен пароль: `AGktOidxrah1KVC0`
|
||||
|
||||
#### nginx Конфигурация
|
||||
- Развернута конфигурация для vscode.mnemo-cards.online
|
||||
- Исправлен proxy_pass с `http://localhost:8443` на `http://127.0.0.1:8443`
|
||||
- Настроено SSL с Let's Encrypt сертификатами
|
||||
- Добавлена поддержка WebSocket для VSCode
|
||||
- Настроено rate limiting для защиты от злоупотреблений
|
||||
|
||||
#### Разрешение конфликта доменов
|
||||
- **vscode.mnemo-cards.online** → VSCode Server (code-server)
|
||||
- **code.mnemo-cards.online** → Forgejo Git Server (не VSCode!)
|
||||
- Удален code.mnemo-cards.online из конфигурации VSCode
|
||||
|
||||
### 3. Созданные инструменты ✅
|
||||
|
||||
Создано 7 скриптов для автоматизации:
|
||||
|
||||
1. **fix-vscode-server.sh** - Автоматическое восстановление code-server
|
||||
2. **check-nginx.sh** - Проверка и перезагрузка nginx
|
||||
3. **deploy-vscode-nginx.sh** - Развертывание nginx конфигурации
|
||||
4. **fix-nginx-duplicates.sh** - Удаление дублирующихся конфигураций
|
||||
5. **test-vscode-from-server.sh** - Тестирование с сервера
|
||||
6. **test-vscode-final.sh** - Финальное тестирование
|
||||
7. **fix-code-domain-conflict.sh** - Исправление конфликтов доменов
|
||||
|
||||
### 4. Документация ✅
|
||||
|
||||
Создана подробная документация:
|
||||
- **VSCODE_SERVER_SETUP.md** - Полное руководство по настройке
|
||||
- **README.md** - Обновлен с информацией о VSCode Server
|
||||
- **RECOVERY_REPORT_2025-11-19.md** - Этот отчет
|
||||
|
||||
## Результаты
|
||||
|
||||
### ✅ Работающие сервисы
|
||||
|
||||
| URL | Сервис | Статус |
|
||||
|-----|--------|--------|
|
||||
| https://vscode.mnemo-cards.online/ | VSCode Server | 🟢 Работает |
|
||||
| https://code.mnemo-cards.online/ | Forgejo Git Server | 🟢 Работает |
|
||||
|
||||
### ✅ Проверки
|
||||
|
||||
```bash
|
||||
# Тест 1: vscode.mnemo-cards.online
|
||||
HTTP/2 302
|
||||
location: ./login
|
||||
✅ Работает - редирект на страницу логина
|
||||
|
||||
# Тест 2: code.mnemo-cards.online
|
||||
HTTP/2 200
|
||||
✅ Работает - Forgejo главная страница
|
||||
|
||||
# Тест 3: code-server service
|
||||
● code-server.service - code-server
|
||||
Active: active (running)
|
||||
Enabled: enabled
|
||||
✅ Сервис запущен и включен для автозапуска
|
||||
```
|
||||
|
||||
## Доступ к VSCode Server
|
||||
|
||||
**URL**: https://vscode.mnemo-cards.online/
|
||||
**Пароль**: `AGktOidxrah1KVC0`
|
||||
**Пользователь**: root
|
||||
**Рабочая директория**: /root/
|
||||
|
||||
## Быстрое восстановление после перезагрузки
|
||||
|
||||
Если после перезагрузки сервера VSCode Server снова не работает:
|
||||
|
||||
```bash
|
||||
cd /Users/dmitry/StudioProjects/mnemo_cards/tools/deploy
|
||||
./fix-vscode-server.sh
|
||||
```
|
||||
|
||||
Этот скрипт автоматически:
|
||||
- Проверит установку code-server
|
||||
- Исправит конфигурацию
|
||||
- Создаст/обновит systemd service
|
||||
- Включит автозапуск
|
||||
- Запустит сервис
|
||||
- Перезагрузит nginx
|
||||
|
||||
## Управление сервисом
|
||||
|
||||
### Проверка статуса
|
||||
```bash
|
||||
ssh root@147.45.152.129 'systemctl status code-server'
|
||||
```
|
||||
|
||||
### Просмотр логов
|
||||
```bash
|
||||
ssh root@147.45.152.129 'journalctl -u code-server -f'
|
||||
```
|
||||
|
||||
### Перезапуск
|
||||
```bash
|
||||
ssh root@147.45.152.129 'systemctl restart code-server'
|
||||
```
|
||||
|
||||
## Предотвращение проблем в будущем
|
||||
|
||||
✅ **Сделано**:
|
||||
1. code-server настроен на автозапуск (`systemctl enable`)
|
||||
2. Добавлен `Restart=always` в systemd service
|
||||
3. Созданы скрипты для быстрого восстановления
|
||||
4. Написана подробная документация
|
||||
|
||||
🔄 **Рекомендации**:
|
||||
1. После обновления сервера проверить статус всех сервисов
|
||||
2. Периодически проверять SSL сертификаты (`certbot renew`)
|
||||
3. Делать backup конфигураций nginx перед изменениями
|
||||
4. Тестировать доступность после каждой перезагрузки сервера
|
||||
|
||||
## Архитектура
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ Internet │
|
||||
└────────────────────┬────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ nginx (port 443) │
|
||||
│ SSL Termination │
|
||||
└─────┬────────────────────────────────────┬──────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌─────────────────┐ ┌────────────────┐
|
||||
│ code-server │ │ Forgejo │
|
||||
│ 127.0.0.1:8443 │ │localhost:3000 │
|
||||
│ │ │ │
|
||||
│ vscode.mnemo... │ │code.mnemo... │
|
||||
└─────────────────┘ └────────────────┘
|
||||
```
|
||||
|
||||
## Таймлайн восстановления
|
||||
|
||||
- **22:24** - Сервер перезагружен
|
||||
- **22:27** - Обнаружена проблема
|
||||
- **22:27** - Начата диагностика
|
||||
- **22:28** - Запущен code-server на правильном порту
|
||||
- **22:28** - Развернута nginx конфигурация
|
||||
- **22:29** - Исправлен конфликт доменов
|
||||
- **22:30** - Исправлена проблема IPv6/IPv4
|
||||
- **22:32** - ✅ Все сервисы восстановлены и проверены
|
||||
|
||||
**Время восстановления**: ~8 минут
|
||||
**Время автоматизации**: +15 минут (создание скриптов и документации)
|
||||
|
||||
## Итог
|
||||
|
||||
🎉 **Успешно восстановлены оба сервиса!**
|
||||
|
||||
- ✅ VSCode Server доступен по https://vscode.mnemo-cards.online/
|
||||
- ✅ Forgejo Git Server доступен по https://code.mnemo-cards.online/
|
||||
- ✅ Настроен автозапуск при перезагрузке
|
||||
- ✅ Созданы инструменты для быстрого восстановления
|
||||
- ✅ Написана полная документация
|
||||
|
||||
**Статус**: 🟢 Оба сервиса работают стабильно
|
||||
|
||||
|
|
@ -1,212 +0,0 @@
|
|||
# VSCode Server Setup Guide
|
||||
|
||||
## Problem
|
||||
After server reboot, VSCode Server (code-server) was not accessible:
|
||||
- https://vscode.mnemo-cards.online/ - not working
|
||||
- https://code.mnemo-cards.online/ - not working
|
||||
|
||||
## Root Causes Identified
|
||||
|
||||
1. **code-server was not configured to start on boot**
|
||||
- Service existed but wasn't properly enabled
|
||||
- Configuration file had wrong port (8080 instead of 8443)
|
||||
|
||||
2. **nginx configuration was missing**
|
||||
- VSCode nginx config wasn't deployed to the server
|
||||
- nginx was trying to use IPv6 (::1) instead of IPv4 (127.0.0.1)
|
||||
|
||||
3. **Domain conflict**
|
||||
- Both `code.mnemo-cards.online` and `vscode.mnemo-cards.online` were initially configured for VSCode
|
||||
- But `code.mnemo-cards.online` is actually used by Forgejo (git server)
|
||||
|
||||
## Solution
|
||||
|
||||
### Correct Domain Mapping
|
||||
- **https://vscode.mnemo-cards.online/** → VSCode Server (code-server on port 8443)
|
||||
- **https://code.mnemo-cards.online/** → Forgejo Git Server (port 3000)
|
||||
|
||||
### Fixed Components
|
||||
|
||||
#### 1. code-server Service
|
||||
Created proper systemd service at `/etc/systemd/system/code-server.service`:
|
||||
```ini
|
||||
[Unit]
|
||||
Description=code-server
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Environment=PASSWORD=AGktOidxrah1KVC0
|
||||
ExecStart=/usr/bin/code-server --bind-addr 127.0.0.1:8443 --auth password
|
||||
WorkingDirectory=/root
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
User=root
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
Configuration at `/root/.config/code-server/config.yaml`:
|
||||
```yaml
|
||||
bind-addr: 127.0.0.1:8443
|
||||
auth: password
|
||||
password: AGktOidxrah1KVC0
|
||||
cert: false
|
||||
```
|
||||
|
||||
#### 2. nginx Configuration
|
||||
Deployed proper nginx configuration for vscode.mnemo-cards.online:
|
||||
- Location: `/etc/nginx/sites-available/vscode.mnemo-cards.online`
|
||||
- Proxy: http://127.0.0.1:8443 (using IPv4, not localhost which resolves to IPv6)
|
||||
- SSL: Let's Encrypt certificates
|
||||
- Rate limiting: Configured for login and general access
|
||||
- WebSocket support: Enabled for VSCode
|
||||
|
||||
## Deployment Scripts
|
||||
|
||||
Created the following scripts in `tools/deploy/`:
|
||||
|
||||
1. **fix-vscode-server.sh** - Diagnoses and fixes code-server installation and configuration
|
||||
2. **fix-vscode-rate-limit.sh** - Fixes 429 errors by updating rate limits in nginx.conf
|
||||
3. **check-nginx.sh** - Checks nginx status and reloads configuration
|
||||
4. **deploy-vscode-nginx.sh** - Deploys VSCode nginx configuration to server
|
||||
5. **fix-nginx-duplicates.sh** - Removes duplicate nginx configurations
|
||||
6. **test-vscode-from-server.sh** - Tests VSCode connectivity from server
|
||||
7. **test-vscode-final.sh** - Final tests of both URLs
|
||||
|
||||
## How to Use
|
||||
|
||||
### Quick Fix After Server Reboot
|
||||
If VSCode Server is not accessible after server reboot, run:
|
||||
```bash
|
||||
cd /Users/dmitry/StudioProjects/mnemo_cards/tools/deploy
|
||||
./fix-vscode-server.sh
|
||||
```
|
||||
|
||||
### Deploy nginx Configuration
|
||||
To deploy or update nginx configuration:
|
||||
```bash
|
||||
cd /Users/dmitry/StudioProjects/mnemo_cards/tools/deploy
|
||||
./deploy-vscode-nginx.sh
|
||||
```
|
||||
|
||||
### Test Connectivity
|
||||
To test if everything is working:
|
||||
```bash
|
||||
cd /Users/dmitry/StudioProjects/mnemo_cards/tools/deploy
|
||||
./test-vscode-final.sh
|
||||
```
|
||||
|
||||
## Access Information
|
||||
|
||||
- **URL**: https://vscode.mnemo-cards.online/
|
||||
- **Username**: (no username required, password only)
|
||||
- **Password**: AGktOidxrah1KVC0
|
||||
|
||||
## Service Management
|
||||
|
||||
### Check Status
|
||||
```bash
|
||||
ssh root@147.45.152.129
|
||||
systemctl status code-server
|
||||
```
|
||||
|
||||
### View Logs
|
||||
```bash
|
||||
ssh root@147.45.152.129
|
||||
journalctl -u code-server -f
|
||||
```
|
||||
|
||||
### Restart Service
|
||||
```bash
|
||||
ssh root@147.45.152.129
|
||||
systemctl restart code-server
|
||||
```
|
||||
|
||||
### Check nginx Status
|
||||
```bash
|
||||
ssh root@147.45.152.129
|
||||
systemctl status nginx
|
||||
nginx -t # Test configuration
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### VSCode Server Not Starting
|
||||
1. Check if service is running: `systemctl status code-server`
|
||||
2. Check logs: `journalctl -u code-server -n 50`
|
||||
3. Verify port is listening: `ss -tuln | grep 8443`
|
||||
4. Run fix script: `./fix-vscode-server.sh`
|
||||
|
||||
### nginx 502 Bad Gateway
|
||||
1. Verify code-server is running on port 8443
|
||||
2. Check nginx error logs: `tail -f /var/log/nginx/error.log`
|
||||
3. Verify proxy_pass uses 127.0.0.1:8443 (not localhost)
|
||||
|
||||
### 429 Too Many Requests
|
||||
If you get `429 (Too Many Requests)` errors when loading VSCode:
|
||||
1. Run the fix script: `./fix-vscode-rate-limit.sh`
|
||||
2. Redeploy nginx config: `./deploy-vscode-nginx.sh`
|
||||
3. The issue is usually caused by too strict rate limiting for static files
|
||||
4. Static files are now excluded from rate limiting automatically
|
||||
|
||||
### SSL Certificate Issues
|
||||
Certificates are managed by Let's Encrypt and stored at:
|
||||
```
|
||||
/etc/letsencrypt/live/vscode.mnemo-cards.online/
|
||||
```
|
||||
|
||||
To renew certificates:
|
||||
```bash
|
||||
ssh root@147.45.152.129
|
||||
certbot renew
|
||||
systemctl reload nginx
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Internet
|
||||
↓
|
||||
nginx (port 443) - SSL termination
|
||||
↓
|
||||
code-server (127.0.0.1:8443) - VSCode Server
|
||||
↓
|
||||
/root/ - Working directory
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- code-server runs as root user (WorkingDirectory=/root)
|
||||
- Authentication is enabled with password
|
||||
- WebSocket support is enabled for VSCode features
|
||||
- Rate limiting is configured to prevent abuse:
|
||||
- General requests: 200 requests/minute (burst: 50)
|
||||
- Login attempts: 5 requests/minute (burst: 2)
|
||||
- Static files (JS, CSS, images): No rate limiting
|
||||
- Automatic restart is configured (Restart=always)
|
||||
- Service is enabled to start on boot (enabled via systemctl)
|
||||
|
||||
## Recent Changes
|
||||
|
||||
### 2025-11-22
|
||||
1. ✅ Fixed 429 (Too Many Requests) error for static files
|
||||
- Excluded static files (`/static/`, `/out/`, file extensions) from rate limiting
|
||||
- Increased general rate limit from 30r/m to 200r/m
|
||||
- Added caching for static files
|
||||
|
||||
### 2025-11-19
|
||||
1. ✅ Fixed code-server service configuration
|
||||
2. ✅ Deployed nginx configuration
|
||||
3. ✅ Fixed IPv6/IPv4 issue (localhost → 127.0.0.1)
|
||||
4. ✅ Resolved domain conflict (removed code.mnemo-cards.online from VSCode config)
|
||||
5. ✅ Enabled service auto-start on boot
|
||||
6. ✅ Verified both URLs are working
|
||||
|
||||
## Status
|
||||
|
||||
🟢 **OPERATIONAL**
|
||||
- vscode.mnemo-cards.online - Working ✅
|
||||
- code.mnemo-cards.online - Working ✅ (Forgejo)
|
||||
|
||||
|
|
@ -1,252 +0,0 @@
|
|||
# Рекомендации по очистке дискового пространства на сервере
|
||||
|
||||
**Дата анализа:** $(date)
|
||||
**Текущее использование диска:** 36GB из 40GB (90%)
|
||||
**Доступно:** 4.2GB
|
||||
|
||||
## Критичные находки (можно освободить ~18-20GB)
|
||||
|
||||
### 1. Docker неиспользуемые ресурсы ⚠️ **~12.2GB**
|
||||
|
||||
**Неиспользуемые Docker образы:** 6.24GB (81% от всех образов)
|
||||
- `code.mnemo-cards.online/cinnabarflower/cards/agent:latest` - 4.29GB (не используется)
|
||||
- `moby/buildkit:buildx-stable-1` - 227MB (не используется)
|
||||
- `dart:stable` - 787MB (не используется)
|
||||
- `ghcr.io/cirruslabs/flutter:3.35.5` - 3.56GB (используется как базовый, но можно очистить старые версии)
|
||||
- `node:16-bullseye` - 940MB (не используется)
|
||||
|
||||
**Неиспользуемые Docker volumes:** 5.948GB (91% от всех volumes)
|
||||
- `GITEA-ACTIONS-TASK-278_WORKFLOW-Build-Agent-Image_JOB-build-and-push` - 1.103GB (старые CI/CD задачи)
|
||||
- `GITEA-ACTIONS-TASK-278_WORKFLOW-Build-Agent-Image_JOB-build-and-push-env` - 15.88MB
|
||||
- `GITEA-ACTIONS-TASK-284_WORKFLOW-Build-Agent-Image_JOB-build-and-push` - 1.103GB (старые CI/CD задачи)
|
||||
- `GITEA-ACTIONS-TASK-284_WORKFLOW-Build-Agent-Image_JOB-build-and-push-env` - 16.92MB
|
||||
- `act-toolcache` - 3.708GB (кэш инструментов для act)
|
||||
|
||||
**Команды для очистки:**
|
||||
```bash
|
||||
# Просмотр неиспользуемых ресурсов
|
||||
docker system df
|
||||
|
||||
# Удаление неиспользуемых образов, контейнеров, сетей и volumes
|
||||
docker system prune -a --volumes
|
||||
|
||||
# Или более безопасно - только неиспользуемые volumes
|
||||
docker volume prune
|
||||
|
||||
# Удаление только неиспользуемых образов
|
||||
docker image prune -a
|
||||
```
|
||||
|
||||
**⚠️ Внимание:** Команда `docker system prune -a --volumes` удалит ВСЕ неиспользуемые ресурсы. Убедитесь, что не нужны старые образы для rollback.
|
||||
|
||||
---
|
||||
|
||||
### 2. Telegram Bot Backups ⚠️ **5.2GB**
|
||||
|
||||
**Расположение:** `/root/mnemo_cards_telegram_bot/backups`
|
||||
|
||||
**Рекомендация:** Проверить содержимое и удалить старые backups, оставив только последние несколько.
|
||||
|
||||
**Команда для проверки:**
|
||||
```bash
|
||||
ls -lh /root/mnemo_cards_telegram_bot/backups
|
||||
du -h /root/mnemo_cards_telegram_bot/backups/* | sort -hr
|
||||
```
|
||||
|
||||
**Команда для удаления (после проверки):**
|
||||
```bash
|
||||
# Удалить backups старше 30 дней (пример)
|
||||
find /root/mnemo_cards_telegram_bot/backups -type f -mtime +30 -delete
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Docker Overlay2 ⚠️ **9.1GB**
|
||||
|
||||
**Расположение:** `/var/lib/docker/overlay2`
|
||||
|
||||
Это хранилище Docker для слоев образов. После очистки неиспользуемых образов (пункт 1) размер должен уменьшиться.
|
||||
|
||||
**Команда для очистки:**
|
||||
```bash
|
||||
# Очистка произойдет автоматически после docker system prune
|
||||
# Или вручную (осторожно!):
|
||||
docker system prune -a --volumes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Средние находки (можно освободить ~1-2GB)
|
||||
|
||||
### 4. Кэш директории **~1GB**
|
||||
|
||||
**Root cache:** `/root/.cache` - 751MB
|
||||
- `act` - 635MB (кэш для GitHub Actions локального запуска)
|
||||
- `code-server` - 117MB (кэш VSCode Server)
|
||||
|
||||
**Pub cache:** `/root/.pub-cache` - 663MB (кэш Dart пакетов)
|
||||
|
||||
**System cache:** `/var/cache` - 275MB
|
||||
- `apt` - 257MB (кэш пакетов apt)
|
||||
|
||||
**Команды для очистки:**
|
||||
```bash
|
||||
# Очистка apt кэша
|
||||
apt-get clean
|
||||
apt-get autoclean
|
||||
|
||||
# Очистка pub cache (можно пересобрать при необходимости)
|
||||
rm -rf ~/.pub-cache/hosted/*
|
||||
|
||||
# Очистка act cache (если не используется)
|
||||
rm -rf ~/.cache/act
|
||||
|
||||
# Очистка code-server cache (можно пересобрать)
|
||||
rm -rf ~/.cache/code-server
|
||||
```
|
||||
|
||||
**⚠️ Внимание:** После очистки кэша, при следующем использовании пакеты/инструменты будут загружены заново.
|
||||
|
||||
---
|
||||
|
||||
### 5. Старые Backup директории **~248MB**
|
||||
|
||||
**Расположение:** `/var/www/mnemo_cards.backup.*`
|
||||
|
||||
**Найдено:** 8 backup директорий по ~31MB каждая (все от 25-26 октября 2025)
|
||||
|
||||
**Список:**
|
||||
- `mnemo_cards.backup.20251025_141822` - 31MB
|
||||
- `mnemo_cards.backup.20251025_141931` - 31MB
|
||||
- `mnemo_cards.backup.20251025_154819` - 31MB
|
||||
- `mnemo_cards.backup.20251025_211926` - 31MB
|
||||
- `mnemo_cards.backup.20251025_234756` - 31MB
|
||||
- `mnemo_cards.backup.20251026_000205` - 31MB
|
||||
- `mnemo_cards.backup.20251026_003152` - 31MB
|
||||
- `mnemo_cards.backup.20251026_014752` - 31MB
|
||||
|
||||
**Рекомендация:** Оставить только последний backup, остальные удалить.
|
||||
|
||||
**Команда для удаления:**
|
||||
```bash
|
||||
# Просмотр всех backups
|
||||
ls -lh /var/www/mnemo_cards.backup.*
|
||||
|
||||
# Удалить все кроме последнего (самого нового)
|
||||
cd /var/www
|
||||
ls -t mnemo_cards.backup.* | tail -n +2 | xargs rm -rf
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6. Логи **~760MB**
|
||||
|
||||
**Общий размер:** `/var/log` - 760MB
|
||||
|
||||
**Nginx логи:** 39MB
|
||||
- `access.log.1` - 23MB
|
||||
- `access.log` - 11MB (текущий)
|
||||
- `error.log.1` - 2.3MB
|
||||
- `error.log` - 2.0MB (текущий)
|
||||
|
||||
**Старые логи (30+ дней):** 34 файла
|
||||
|
||||
**Команды для очистки:**
|
||||
```bash
|
||||
# Ротация nginx логов (оставить только последние 7 дней)
|
||||
find /var/log/nginx -type f -name "*.log.*" -mtime +7 -delete
|
||||
|
||||
# Очистка старых логов (30+ дней)
|
||||
find /var/log -type f -mtime +30 -delete
|
||||
|
||||
# Очистка старых сжатых логов
|
||||
find /var/log -type f -name "*.gz" -mtime +30 -delete
|
||||
|
||||
# Настройка logrotate для автоматической ротации
|
||||
# (проверить /etc/logrotate.d/nginx)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Малые находки (можно освободить ~50-100MB)
|
||||
|
||||
### 7. Старые системные логи
|
||||
|
||||
**Команда для просмотра:**
|
||||
```bash
|
||||
find /var/log -type f -mtime +30 -ls
|
||||
```
|
||||
|
||||
**Команда для удаления:**
|
||||
```bash
|
||||
find /var/log -type f -mtime +30 -delete
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Итоговая таблица рекомендаций
|
||||
|
||||
| Категория | Размер | Приоритет | Безопасность | Команда |
|
||||
|-----------|--------|-----------|--------------|---------|
|
||||
| Docker неиспользуемые ресурсы | ~12.2GB | 🔴 Высокий | ✅ Безопасно | `docker system prune -a --volumes` |
|
||||
| Telegram Bot Backups | 5.2GB | 🔴 Высокий | ⚠️ Проверить | `find /root/mnemo_cards_telegram_bot/backups -mtime +30 -delete` |
|
||||
| Docker Overlay2 | 9.1GB | 🟡 Средний | ✅ После очистки Docker | Автоматически после prune |
|
||||
| Кэш (pub, apt, act) | ~1GB | 🟡 Средний | ✅ Безопасно | `apt-get clean && rm -rf ~/.pub-cache/hosted/*` |
|
||||
| Старые backups | ~248MB | 🟡 Средний | ✅ Безопасно | Удалить все кроме последнего |
|
||||
| Логи | ~760MB | 🟢 Низкий | ✅ Безопасно | `find /var/log -mtime +30 -delete` |
|
||||
|
||||
## Общий потенциал освобождения: ~18-20GB
|
||||
|
||||
## Рекомендуемый порядок действий
|
||||
|
||||
1. **Сначала Docker** (самый большой эффект):
|
||||
```bash
|
||||
docker system df # Проверить
|
||||
docker system prune -a --volumes # Очистить
|
||||
```
|
||||
|
||||
2. **Проверить Telegram Bot backups**:
|
||||
```bash
|
||||
ls -lh /root/mnemo_cards_telegram_bot/backups
|
||||
# Решить, какие удалить
|
||||
```
|
||||
|
||||
3. **Очистить кэш**:
|
||||
```bash
|
||||
apt-get clean
|
||||
apt-get autoclean
|
||||
```
|
||||
|
||||
4. **Удалить старые backups веб-приложения**:
|
||||
```bash
|
||||
cd /var/www
|
||||
ls -t mnemo_cards.backup.* | tail -n +2 | xargs rm -rf
|
||||
```
|
||||
|
||||
5. **Очистить старые логи**:
|
||||
```bash
|
||||
find /var/log -type f -mtime +30 -delete
|
||||
```
|
||||
|
||||
## ⚠️ ВАЖНЫЕ ПРЕДУПРЕЖДЕНИЯ
|
||||
|
||||
1. **НЕ удаляйте** директории проекта:
|
||||
- `/root/mnemo_cards_backend` (464MB) - рабочий проект
|
||||
- `/root/mnemo_cards_common` (672KB) - рабочий проект
|
||||
- `/root/mnemo_cards_common_backend` (1.5MB) - рабочий проект
|
||||
- `/var/www/mnemo_cards` - текущее веб-приложение
|
||||
|
||||
2. **НЕ удаляйте** данные проекта:
|
||||
- `/root/mnemo_cards_backend/isar` (236MB) - база данных
|
||||
- `/root/mnemo_cards_backend/data` (213MB) - данные приложения
|
||||
|
||||
3. **Перед удалением Docker ресурсов** убедитесь, что не нужны старые образы для rollback.
|
||||
|
||||
4. **Перед удалением backups** проверьте их содержимое и убедитесь, что текущая версия работает.
|
||||
|
||||
## После очистки
|
||||
|
||||
После выполнения рекомендаций ожидаемое использование диска: **~16-18GB из 40GB (40-45%)**
|
||||
|
||||
Это освободит **~18-20GB** дискового пространства.
|
||||
|
||||
|
|
@ -193,24 +193,18 @@ generate_nginx_config "code.mnemo-cards.online" "3000" "forgejo"
|
|||
echo ""
|
||||
echo "📊 Validating generated configurations..."
|
||||
|
||||
# Test configurations by temporarily copying them to sites-available and testing
|
||||
# Test configurations syntax (basic validation only)
|
||||
echo "Testing generated configurations..."
|
||||
for config in "$OUTPUT_DIR"/*.conf; do
|
||||
config_name=$(basename "$config")
|
||||
echo "Testing $config_name..."
|
||||
|
||||
# Copy to temp location and test
|
||||
cp "$config" "/etc/nginx/sites-available/${config_name}.test" 2>/dev/null || true
|
||||
ln -sf "/etc/nginx/sites-available/${config_name}.test" "/etc/nginx/sites-enabled/${config_name}.test" 2>/dev/null || true
|
||||
|
||||
if /usr/sbin/nginx -t 2>/dev/null; then
|
||||
echo "✅ Valid"
|
||||
# Basic syntax check - look for obvious errors
|
||||
if grep -q "server {" "$config" && grep -q "}" "$config"; then
|
||||
echo "✅ Basic structure OK"
|
||||
else
|
||||
echo "❌ Invalid"
|
||||
echo "❌ Missing server block or closing brace"
|
||||
fi
|
||||
|
||||
# Clean up test files
|
||||
rm -f "/etc/nginx/sites-enabled/${config_name}.test" "/etc/nginx/sites-available/${config_name}.test" 2>/dev/null || true
|
||||
done
|
||||
|
||||
echo ""
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
# Nginx configuration for code.mnemo-cards.online
|
||||
# Generated by generate-nginx-configs.sh on Sun Nov 23 02:51:54 MSK 2025
|
||||
# Generated by generate-nginx-configs.sh on Thu Nov 27 17:36:01 MSK 2025
|
||||
# Service: forgejo
|
||||
|
||||
server {
|
||||
|
|
@ -47,14 +47,6 @@ server {
|
|||
proxy_buffering off;
|
||||
proxy_request_buffering off;
|
||||
}
|
||||
}
|
||||
|
||||
# Gzip compression
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_proxied expired no-cache no-store private auth;
|
||||
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/javascript;
|
||||
|
||||
# Security - deny access to hidden files
|
||||
location ~ /\. {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
# Nginx configuration for mnemo-cards.online
|
||||
# Generated by generate-nginx-configs.sh on Sun Nov 23 02:51:54 MSK 2025
|
||||
# Generated by generate-nginx-configs.sh on Thu Nov 27 17:36:01 MSK 2025
|
||||
# Service: webapp
|
||||
|
||||
server {
|
||||
|
|
@ -45,14 +45,6 @@ server {
|
|||
root /var/www/html;
|
||||
try_files $uri =404;
|
||||
}
|
||||
}
|
||||
|
||||
# Gzip compression
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_proxied expired no-cache no-store private auth;
|
||||
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/javascript;
|
||||
|
||||
# Security - deny access to hidden files
|
||||
location ~ /\. {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
# Nginx configuration for vscode.mnemo-cards.online
|
||||
# Generated by generate-nginx-configs.sh on Sun Nov 23 02:51:54 MSK 2025
|
||||
# Generated by generate-nginx-configs.sh on Thu Nov 27 17:36:01 MSK 2025
|
||||
# Service: vscode
|
||||
|
||||
server {
|
||||
|
|
@ -28,10 +28,6 @@ server {
|
|||
# VSCode Server specific settings
|
||||
client_max_body_size 100M;
|
||||
|
||||
# Rate limiting for VSCode
|
||||
limit_req_zone $binary_remote_addr zone=vscode_general:10m rate=100r/m;
|
||||
limit_req_zone $binary_remote_addr zone=vscode_login:10m rate=5r/m;
|
||||
|
||||
# Static files - no rate limiting
|
||||
location ~ ^/(static|out|node_modules)/ {
|
||||
proxy_pass http://127.0.0.1:8443;
|
||||
|
|
@ -64,31 +60,8 @@ server {
|
|||
proxy_read_timeout 60s;
|
||||
}
|
||||
|
||||
# Special rate limiting for login attempts
|
||||
location /login {
|
||||
limit_req zone=vscode_login burst=2 nodelay;
|
||||
|
||||
proxy_pass http://127.0.0.1:8443;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
|
||||
proxy_connect_timeout 60s;
|
||||
proxy_send_timeout 60s;
|
||||
proxy_read_timeout 60s;
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_request_buffering off;
|
||||
}
|
||||
|
||||
# Main proxy location with rate limiting
|
||||
# Main proxy location
|
||||
location / {
|
||||
limit_req zone=vscode_general burst=50 nodelay;
|
||||
proxy_pass http://127.0.0.1:8443;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
|
|
@ -106,14 +79,6 @@ server {
|
|||
proxy_buffering off;
|
||||
proxy_request_buffering off;
|
||||
}
|
||||
}
|
||||
|
||||
# Gzip compression
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_proxied expired no-cache no-store private auth;
|
||||
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/javascript;
|
||||
|
||||
# Security - deny access to hidden files
|
||||
location ~ /\. {
|
||||
|
|
|
|||
271
tools/deploy/verify-nginx-config.sh
Executable file
271
tools/deploy/verify-nginx-config.sh
Executable file
|
|
@ -0,0 +1,271 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Script to verify nginx configurations for conflicts and errors
|
||||
# This script checks for common nginx configuration issues
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
CONFIG_DIR="$SCRIPT_DIR/generated_configs"
|
||||
|
||||
echo "🔍 Verifying nginx configurations..."
|
||||
echo "Config directory: $CONFIG_DIR"
|
||||
echo ""
|
||||
|
||||
# Check if config directory exists
|
||||
if [ ! -d "$CONFIG_DIR" ]; then
|
||||
echo "❌ Config directory not found: $CONFIG_DIR"
|
||||
echo "Run generate-nginx-configs.sh first"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Arrays to track found issues
|
||||
issues_found=0
|
||||
warnings_found=0
|
||||
|
||||
# Function to check server block structure
|
||||
check_server_structure() {
|
||||
local file="$1"
|
||||
local filename=$(basename "$file")
|
||||
|
||||
echo "📋 Checking $filename..."
|
||||
|
||||
# Check for server blocks
|
||||
local server_blocks=$(grep -c "^server {" "$file")
|
||||
if [ "$server_blocks" -lt 2 ]; then
|
||||
echo "❌ Expected at least 2 server blocks (HTTP + HTTPS), found $server_blocks"
|
||||
((issues_found++))
|
||||
else
|
||||
echo "✅ Found $server_blocks server blocks"
|
||||
fi
|
||||
|
||||
# Check for proper closing braces
|
||||
local open_braces=$(grep -c "{" "$file")
|
||||
local close_braces=$(grep -c "}" "$file")
|
||||
if [ "$open_braces" -ne "$close_braces" ]; then
|
||||
echo "❌ Mismatched braces: $open_braces open, $close_braces close"
|
||||
((issues_found++))
|
||||
else
|
||||
echo "✅ Braces balanced"
|
||||
fi
|
||||
|
||||
# Check for server_name directives
|
||||
if ! grep -q "server_name" "$file"; then
|
||||
echo "❌ Missing server_name directive"
|
||||
((issues_found++))
|
||||
else
|
||||
echo "✅ Has server_name directive"
|
||||
fi
|
||||
|
||||
# Check for SSL configuration in HTTPS block
|
||||
if grep -q "listen 443" "$file"; then
|
||||
if ! grep -q "ssl_certificate" "$file"; then
|
||||
echo "❌ HTTPS block missing SSL certificate configuration"
|
||||
((issues_found++))
|
||||
else
|
||||
echo "✅ HTTPS block has SSL configuration"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check for location blocks
|
||||
local location_blocks=$(grep -c "^ location" "$file")
|
||||
if [ "$location_blocks" -eq 0 ]; then
|
||||
echo "❌ No location blocks found"
|
||||
((issues_found++))
|
||||
else
|
||||
echo "✅ Found $location_blocks location blocks"
|
||||
fi
|
||||
|
||||
# Check for security headers
|
||||
if grep -q "add_header.*X-Frame-Options" "$file"; then
|
||||
echo "✅ Has security headers"
|
||||
else
|
||||
echo "⚠️ Missing security headers"
|
||||
((warnings_found++))
|
||||
fi
|
||||
|
||||
# Check for deny access to hidden files
|
||||
if grep -F -q "location ~ /\." "$file"; then
|
||||
echo "✅ Has protection for hidden files"
|
||||
else
|
||||
echo "⚠️ Missing protection for hidden files"
|
||||
((warnings_found++))
|
||||
fi
|
||||
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Function to check for server_name conflicts
|
||||
check_server_name_conflicts() {
|
||||
echo "🔍 Checking for server_name conflicts..."
|
||||
|
||||
# Collect all unique server_names from all config files
|
||||
# Multiple server blocks in the same file with the same name are OK (HTTP/HTTPS)
|
||||
local all_names=""
|
||||
local conflicts=""
|
||||
|
||||
for config in "$CONFIG_DIR"/*.conf; do
|
||||
if [ -f "$config" ]; then
|
||||
local filename=$(basename "$config")
|
||||
local file_unique_names=""
|
||||
|
||||
# First collect all unique server_names from this file
|
||||
while read -r line; do
|
||||
if [[ $line =~ server_name[[:space:]]+(.*)[[:space:]]*\; ]]; then
|
||||
local names="${BASH_REMATCH[1]}"
|
||||
# Split multiple names and add to file's unique list
|
||||
for name in $names; do
|
||||
# Trim whitespace and check uniqueness
|
||||
name=$(echo "$name" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
|
||||
if [ "$name" != "_" ] && [ "$name" != "" ]; then
|
||||
# Check if name is already in the list
|
||||
local already_exists=0
|
||||
for existing in $file_unique_names; do
|
||||
if [ "$existing" = "$name" ]; then
|
||||
already_exists=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ $already_exists -eq 0 ]; then
|
||||
file_unique_names="$file_unique_names $name"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
fi
|
||||
done < "$config"
|
||||
|
||||
# Now check each unique name from this file against all previously seen names
|
||||
for name in $file_unique_names; do
|
||||
if echo "$all_names" | grep -q "^$name:"; then
|
||||
local existing_file=$(echo "$all_names" | grep "^$name:" | cut -d: -f2)
|
||||
# Only report conflict if it's a different file
|
||||
if [ "$existing_file" != "$filename" ]; then
|
||||
echo "❌ server_name conflict: '$name' found in both $existing_file and $filename"
|
||||
conflicts="$conflicts $name"
|
||||
((issues_found++))
|
||||
fi
|
||||
else
|
||||
all_names="$all_names$name:$filename "
|
||||
fi
|
||||
done
|
||||
fi
|
||||
done
|
||||
|
||||
local unique_count=$(echo "$all_names" | wc -w)
|
||||
if [ $unique_count -gt 0 ]; then
|
||||
echo "✅ Found $unique_count unique server_names across files"
|
||||
else
|
||||
echo "❌ No server_names found"
|
||||
((issues_found++))
|
||||
fi
|
||||
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Function to check for common nginx syntax issues
|
||||
check_syntax_issues() {
|
||||
echo "🔧 Checking for common syntax issues..."
|
||||
|
||||
for config in "$CONFIG_DIR"/*.conf; do
|
||||
if [ -f "$config" ]; then
|
||||
local filename=$(basename "$config")
|
||||
|
||||
# Check for directives that should not be in server blocks
|
||||
if grep -q "^ limit_req_zone" "$config"; then
|
||||
echo "❌ limit_req_zone found inside server block in $filename (should be in http block)"
|
||||
((issues_found++))
|
||||
fi
|
||||
|
||||
if grep -q "^ gzip " "$config"; then
|
||||
echo "❌ gzip directive found inside server block in $filename (should be in http block)"
|
||||
((issues_found++))
|
||||
fi
|
||||
|
||||
# Check for unclosed strings
|
||||
local unclosed_quotes=$(grep -c '"' "$config")
|
||||
if [ $((unclosed_quotes % 2)) -ne 0 ]; then
|
||||
echo "❌ Unclosed quotes in $filename"
|
||||
((issues_found++))
|
||||
fi
|
||||
|
||||
# Check for invalid characters in server_name
|
||||
while read -r line; do
|
||||
if [[ $line =~ server_name[[:space:]]+(.*)[[:space:]]*\; ]]; then
|
||||
local names="${BASH_REMATCH[1]}"
|
||||
if [[ $names =~ [^a-zA-Z0-9._*-] ]]; then
|
||||
echo "❌ Invalid characters in server_name '$names' in $filename"
|
||||
((issues_found++))
|
||||
fi
|
||||
fi
|
||||
done < "$config"
|
||||
fi
|
||||
done
|
||||
|
||||
echo "✅ Syntax check completed"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Function to check SSL configuration
|
||||
check_ssl_config() {
|
||||
echo "🔐 Checking SSL configuration..."
|
||||
|
||||
for config in "$CONFIG_DIR"/*.conf; do
|
||||
if [ -f "$config" ]; then
|
||||
local filename=$(basename "$config")
|
||||
|
||||
if grep -q "listen 443" "$config"; then
|
||||
# Check SSL protocols
|
||||
if grep -q "ssl_protocols" "$config"; then
|
||||
echo "✅ $filename has SSL protocols configured"
|
||||
else
|
||||
echo "⚠️ $filename missing SSL protocols configuration"
|
||||
((warnings_found++))
|
||||
fi
|
||||
|
||||
# Check SSL ciphers
|
||||
if grep -q "ssl_ciphers" "$config"; then
|
||||
echo "✅ $filename has SSL ciphers configured"
|
||||
else
|
||||
echo "⚠️ $filename missing SSL ciphers configuration"
|
||||
((warnings_found++))
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Main verification process
|
||||
echo "📊 Starting comprehensive verification..."
|
||||
echo ""
|
||||
|
||||
# Check each configuration file
|
||||
for config in "$CONFIG_DIR"/*.conf; do
|
||||
if [ -f "$config" ]; then
|
||||
check_server_structure "$config"
|
||||
fi
|
||||
done
|
||||
|
||||
# Cross-file checks
|
||||
check_server_name_conflicts
|
||||
check_syntax_issues
|
||||
check_ssl_config
|
||||
|
||||
# Summary
|
||||
echo "📊 Verification Summary:"
|
||||
echo "Issues found: $issues_found"
|
||||
echo "Warnings: $warnings_found"
|
||||
echo ""
|
||||
|
||||
if [ $issues_found -gt 0 ]; then
|
||||
echo "❌ Configuration has $issues_found issue(s) that must be fixed"
|
||||
exit 1
|
||||
elif [ $warnings_found -gt 0 ]; then
|
||||
echo "⚠️ Configuration has $warnings_found warning(s) - review recommended"
|
||||
exit 0
|
||||
else
|
||||
echo "✅ All configurations passed verification!"
|
||||
exit 0
|
||||
fi
|
||||
Loading…
Reference in a new issue