From 699cb4b5ba0231b74e1bee0958afa86dde2f97a6 Mon Sep 17 00:00:00 2001 From: Denis Shatskiy Date: Fri, 11 Jul 2025 17:20:30 +0700 Subject: [PATCH] Enhance Docker setup and scripts by adding default environment variables for BGP configuration, improving the update process with safe and quick update options, and implementing testing capabilities in the prefix loader script. Update start.sh to include permission checks and network connectivity validation during ExaBGP startup. --- DOCKER_RUN.md | 35 ++++++++++++++ Dockerfile | 11 ++++- scripts/load_prefixes.py | 7 +++ scripts/start.sh | 42 +++++++++++++++- scripts/update-container.ps1 | 92 ++++++++++++++++++++++++++++++++++++ 5 files changed, 184 insertions(+), 3 deletions(-) create mode 100644 scripts/update-container.ps1 diff --git a/DOCKER_RUN.md b/DOCKER_RUN.md index d28a1f0..391ce4e 100644 --- a/DOCKER_RUN.md +++ b/DOCKER_RUN.md @@ -45,6 +45,15 @@ docker run -d ` -e BGP_KEEPALIVE=30 ` git.shts.su/infra/bgp-server:latest +# Простой запуск с настройками по умолчанию +docker run -d ` + --name bgp-server ` + --restart unless-stopped ` + -p 179:179 ` + -v ${PWD}/data:/app/data:ro ` + -v ${PWD}/logs:/app/logs ` + git.shts.su/infra/bgp-server:latest + # Пример с кастомными настройками docker run -d ` --name bgp-server-custom ` @@ -178,6 +187,32 @@ docker logs bgp-server docker logs -f bgp-server ``` +### Обновление контейнера + +```powershell +# Безопасное обновление (рекомендуется) +docker stop bgp-server +docker rm bgp-server +docker pull git.shts.su/infra/bgp-server:latest +docker run -d ` + --name bgp-server ` + --restart unless-stopped ` + -p 179:179 ` + -v ${PWD}/data:/app/data:ro ` + -v ${PWD}/logs:/app/logs ` + git.shts.su/infra/bgp-server:latest + +# Быстрое обновление (если настройки не изменились) +docker pull git.shts.su/infra/bgp-server:latest +docker restart bgp-server + +# Использование скрипта обновления +.\scripts\update-container.ps1 + +# Принудительное обновление без подтверждения +.\scripts\update-container.ps1 -Force +``` + ### Обновление префиксов ```powershell diff --git a/Dockerfile b/Dockerfile index a4dcf72..00be3da 100644 --- a/Dockerfile +++ b/Dockerfile @@ -29,5 +29,14 @@ WORKDIR /app # Открытие BGP порта EXPOSE 179 +# Установка переменных окружения по умолчанию +ENV BGP_LOCAL_AS=65000 +ENV BGP_ROUTER_ID=192.168.1.100 +ENV BGP_NEIGHBOR_IP=192.168.1.1 +ENV BGP_NEIGHBOR_AS=65001 +ENV BGP_HOLD_TIME=90 +ENV BGP_KEEPALIVE=30 +ENV BGP_LOG_LEVEL=INFO + # Команда запуска -CMD ["/app/scripts/start.sh"] \ No newline at end of file +ENTRYPOINT ["/app/scripts/start.sh"] \ No newline at end of file diff --git a/scripts/load_prefixes.py b/scripts/load_prefixes.py index e60c817..c1e5cbc 100644 --- a/scripts/load_prefixes.py +++ b/scripts/load_prefixes.py @@ -123,6 +123,13 @@ def withdraw_prefixes(prefixes: Set[str]): def main(): """Основная функция""" + # Проверка тестового режима + if len(sys.argv) > 1 and sys.argv[1] == '--test': + print("Testing prefix loader...") + prefixes = load_all_prefixes() + print(f"Found {len(prefixes)} prefixes: {list(prefixes)}") + return + log_message("Starting prefix loader...") # Создание директории для логов diff --git a/scripts/start.sh b/scripts/start.sh index c747ae2..43f4c1e 100644 --- a/scripts/start.sh +++ b/scripts/start.sh @@ -40,8 +40,18 @@ echo "Prefixes file content:" cat /app/data/prefixes.txt echo "---" +# Проверка прав доступа к файлам +echo "Checking file permissions:" +ls -la /app/data/ +ls -la /app/scripts/ +echo "---" + # Генерация конфигурации из переменных окружения echo "Generating ExaBGP configuration from environment variables..." +echo "Environment variables:" +env | grep BGP_ || echo "No BGP_ variables found" +echo "---" + python3 /app/scripts/generate_config.py # Проверка конфигурации @@ -51,13 +61,29 @@ cat /app/exabgp.conf echo "---" exabgp --validate /app/exabgp.conf +# Тестовый запуск скрипта загрузки префиксов +echo "Testing prefix loader script..." +python3 /app/scripts/load_prefixes.py --test 2>&1 || echo "Prefix loader test failed (this is normal)" +echo "---" + +# Проверка сетевого подключения +echo "Checking network connectivity..." +NEIGHBOR_IP=${BGP_NEIGHBOR_IP:-192.168.1.1} +if ping -c 1 $NEIGHBOR_IP > /dev/null 2>&1; then + echo "Network connectivity to $NEIGHBOR_IP: OK" +else + echo "Warning: Cannot reach $NEIGHBOR_IP. BGP session may not establish." +fi + # Запуск ExaBGP в фоновом режиме с логированием echo "Starting ExaBGP..." LOG_LEVEL=${BGP_LOG_LEVEL:-INFO} -exabgp --log.level $LOG_LEVEL /app/exabgp.conf > /app/logs/exabgp.log 2>&1 & + +# Запуск с подробным логированием в режиме демона +exabgp --log.level $LOG_LEVEL --daemon /app/exabgp.conf > /app/logs/exabgp.log 2>&1 & +EXABGP_PID=$! # Сохранение PID -EXABGP_PID=$! echo $EXABGP_PID > /app/logs/exabgp.pid # Ожидание запуска @@ -66,8 +92,15 @@ sleep 5 # Проверка статуса if kill -0 $EXABGP_PID 2>/dev/null; then echo "ExaBGP started successfully with PID: $EXABGP_PID" + echo "Recent logs:" + tail -10 /app/logs/exabgp.log else echo "Failed to start ExaBGP" + echo "Full logs:" + cat /app/logs/exabgp.log + echo "---" + echo "Process status:" + ps aux | grep exabgp || echo "No exabgp process found" exit 1 fi @@ -84,4 +117,9 @@ cleanup() { trap cleanup SIGTERM SIGINT # Ожидание завершения +echo "Waiting for ExaBGP to run..." +echo "Process status:" +ps aux | grep exabgp || echo "No exabgp process found" +echo "---" + wait $EXABGP_PID \ No newline at end of file diff --git a/scripts/update-container.ps1 b/scripts/update-container.ps1 new file mode 100644 index 0000000..19f219b --- /dev/null +++ b/scripts/update-container.ps1 @@ -0,0 +1,92 @@ +# Скрипт для безопасного обновления BGP Server контейнера + +param( + [string]$ContainerName = "bgp-server", + [string]$ImageName = "git.shts.su/infra/bgp-server:latest", + [string]$DataPath = "./data", + [string]$LogsPath = "./logs", + [switch]$Force +) + +Write-Host "=== BGP Server Container Update Script ===" -ForegroundColor Green + +# Проверка существования контейнера +$containerExists = docker ps -a --filter "name=$ContainerName" --format "table {{.Names}}" | Select-String $ContainerName + +if ($containerExists) { + Write-Host "Found existing container: $ContainerName" -ForegroundColor Yellow + + if (-not $Force) { + $response = Read-Host "Do you want to update the container? (y/N)" + if ($response -ne "y" -and $response -ne "Y") { + Write-Host "Update cancelled." -ForegroundColor Red + exit 0 + } + } + + # Остановка и удаление старого контейнера + Write-Host "Stopping container..." -ForegroundColor Yellow + docker stop $ContainerName + + Write-Host "Removing container..." -ForegroundColor Yellow + docker rm $ContainerName +} else { + Write-Host "No existing container found. Creating new one..." -ForegroundColor Green +} + +# Создание директорий если не существуют +if (-not (Test-Path $DataPath)) { + Write-Host "Creating data directory: $DataPath" -ForegroundColor Yellow + New-Item -ItemType Directory -Path $DataPath -Force | Out-Null +} + +if (-not (Test-Path $LogsPath)) { + Write-Host "Creating logs directory: $LogsPath" -ForegroundColor Yellow + New-Item -ItemType Directory -Path $LogsPath -Force | Out-Null +} + +# Загрузка нового образа +Write-Host "Pulling latest image..." -ForegroundColor Yellow +docker pull $ImageName + +if ($LASTEXITCODE -ne 0) { + Write-Host "Failed to pull image. Exiting." -ForegroundColor Red + exit 1 +} + +# Запуск нового контейнера +Write-Host "Starting new container..." -ForegroundColor Yellow +$currentPath = Get-Location +$dataVolume = "${currentPath}\${DataPath}:/app/data:ro" +$logsVolume = "${currentPath}\${LogsPath}:/app/logs" + +docker run -d ` + --name $ContainerName ` + --restart unless-stopped ` + -p 179:179 ` + -v $dataVolume ` + -v $logsVolume ` + $ImageName + +if ($LASTEXITCODE -eq 0) { + Write-Host "Container started successfully!" -ForegroundColor Green + + # Ожидание запуска + Write-Host "Waiting for container to start..." -ForegroundColor Yellow + Start-Sleep -Seconds 5 + + # Проверка статуса + $status = docker ps --filter "name=$ContainerName" --format "table {{.Status}}" + Write-Host "Container status: $status" -ForegroundColor Cyan + + # Показ логов + Write-Host "Recent logs:" -ForegroundColor Cyan + docker logs --tail=10 $ContainerName + + Write-Host "`nContainer update completed successfully!" -ForegroundColor Green + Write-Host "To view logs: docker logs -f $ContainerName" -ForegroundColor Cyan + Write-Host "To check status: docker ps" -ForegroundColor Cyan +} else { + Write-Host "Failed to start container. Check the error above." -ForegroundColor Red + exit 1 +} \ No newline at end of file