@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Скрипт для загрузки префиксов из текстовых файлов в ExaBGP
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
import ipaddress
|
||||
from pathlib import Path
|
||||
from typing import List, Set
|
||||
|
||||
# Настройки
|
||||
DATA_DIR = "/app/data"
|
||||
LOG_FILE = "/app/logs/prefixes.log"
|
||||
PREFIX_FILES = ["prefixes.txt", "additional_prefixes.txt"]
|
||||
|
||||
def log_message(message: str):
|
||||
"""Запись сообщения в лог"""
|
||||
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
log_entry = f"[{timestamp}] {message}"
|
||||
|
||||
# Вывод в stdout для ExaBGP
|
||||
print(log_entry, flush=True)
|
||||
|
||||
# Запись в файл
|
||||
with open(LOG_FILE, "a") as f:
|
||||
f.write(log_entry + "\n")
|
||||
|
||||
def validate_prefix(prefix: str) -> bool:
|
||||
"""Валидация IP префикса"""
|
||||
try:
|
||||
ipaddress.ip_network(prefix, strict=False)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
def load_prefixes_from_file(file_path: Path) -> Set[str]:
|
||||
"""Загрузка префиксов из файла"""
|
||||
prefixes = set()
|
||||
|
||||
if not file_path.exists():
|
||||
log_message(f"File not found: {file_path}")
|
||||
return prefixes
|
||||
|
||||
try:
|
||||
with open(file_path, 'r') as f:
|
||||
for line_num, line in enumerate(f, 1):
|
||||
line = line.strip()
|
||||
|
||||
# Пропуск пустых строк и комментариев
|
||||
if not line or line.startswith('#'):
|
||||
continue
|
||||
|
||||
# Валидация префикса
|
||||
if validate_prefix(line):
|
||||
prefixes.add(line)
|
||||
else:
|
||||
log_message(f"Invalid prefix in {file_path}:{line_num}: {line}")
|
||||
|
||||
except Exception as e:
|
||||
log_message(f"Error reading {file_path}: {e}")
|
||||
|
||||
return prefixes
|
||||
|
||||
def load_all_prefixes() -> Set[str]:
|
||||
"""Загрузка всех префиксов из всех файлов"""
|
||||
all_prefixes = set()
|
||||
|
||||
for filename in PREFIX_FILES:
|
||||
file_path = Path(DATA_DIR) / filename
|
||||
prefixes = load_prefixes_from_file(file_path)
|
||||
all_prefixes.update(prefixes)
|
||||
log_message(f"Loaded {len(prefixes)} prefixes from {filename}")
|
||||
|
||||
return all_prefixes
|
||||
|
||||
def announce_prefixes(prefixes: Set[str]):
|
||||
"""Анонсирование префиксов через ExaBGP API"""
|
||||
for prefix in sorted(prefixes):
|
||||
# Формат команды для ExaBGP
|
||||
command = {
|
||||
"command": "announce route",
|
||||
"neighbor": {
|
||||
"ip": "192.168.1.1",
|
||||
"description": "RouterOS peer"
|
||||
},
|
||||
"attribute": {
|
||||
"origin": "igp",
|
||||
"as-path": [65000],
|
||||
"next-hop": "192.168.1.100"
|
||||
},
|
||||
"nlri": prefix
|
||||
}
|
||||
|
||||
# Отправка команды в ExaBGP
|
||||
print(json.dumps(command), flush=True)
|
||||
log_message(f"Announced prefix: {prefix}")
|
||||
|
||||
def withdraw_prefixes(prefixes: Set[str]):
|
||||
"""Отзыв префиксов через ExaBGP API"""
|
||||
for prefix in sorted(prefixes):
|
||||
command = {
|
||||
"command": "withdraw route",
|
||||
"neighbor": {
|
||||
"ip": "192.168.1.1",
|
||||
"description": "RouterOS peer"
|
||||
},
|
||||
"nlri": prefix
|
||||
}
|
||||
|
||||
print(json.dumps(command), flush=True)
|
||||
log_message(f"Withdrew prefix: {prefix}")
|
||||
|
||||
def main():
|
||||
"""Основная функция"""
|
||||
log_message("Starting prefix loader...")
|
||||
|
||||
# Создание директории для логов
|
||||
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
|
||||
|
||||
# Загрузка префиксов
|
||||
prefixes = load_all_prefixes()
|
||||
log_message(f"Total prefixes loaded: {len(prefixes)}")
|
||||
|
||||
if not prefixes:
|
||||
log_message("No valid prefixes found. Exiting.")
|
||||
return
|
||||
|
||||
# Анонсирование префиксов
|
||||
announce_prefixes(prefixes)
|
||||
log_message("All prefixes announced successfully")
|
||||
|
||||
# Ожидание команд от ExaBGP
|
||||
try:
|
||||
while True:
|
||||
line = sys.stdin.readline()
|
||||
if not line:
|
||||
break
|
||||
|
||||
# Обработка команд от ExaBGP
|
||||
try:
|
||||
data = json.loads(line.strip())
|
||||
log_message(f"Received command: {data}")
|
||||
except json.JSONDecodeError:
|
||||
log_message(f"Invalid JSON received: {line.strip()}")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
log_message("Received interrupt signal")
|
||||
except Exception as e:
|
||||
log_message(f"Error in main loop: {e}")
|
||||
finally:
|
||||
# Отзыв всех префиксов при завершении
|
||||
log_message("Withdrawing all prefixes...")
|
||||
withdraw_prefixes(prefixes)
|
||||
log_message("Prefix loader stopped")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Скрипт мониторинга BGP сервера
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import json
|
||||
import time
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
def run_command(cmd):
|
||||
"""Выполнение команды и возврат результата"""
|
||||
try:
|
||||
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
||||
return result.returncode == 0, result.stdout, result.stderr
|
||||
except Exception as e:
|
||||
return False, "", str(e)
|
||||
|
||||
def check_container_status():
|
||||
"""Проверка статуса Docker контейнера"""
|
||||
success, output, error = run_command("docker ps --filter name=bgp-server --format '{{.Status}}'")
|
||||
if success and output.strip():
|
||||
return True, output.strip()
|
||||
return False, "Container not running"
|
||||
|
||||
def check_bgp_session():
|
||||
"""Проверка BGP сессии"""
|
||||
success, output, error = run_command("docker exec bgp-server exabgpcli show neighbor")
|
||||
if success:
|
||||
return True, output
|
||||
return False, "Cannot check BGP session"
|
||||
|
||||
def check_prefixes():
|
||||
"""Проверка загруженных префиксов"""
|
||||
try:
|
||||
with open("/app/logs/prefixes.log", "r") as f:
|
||||
lines = f.readlines()
|
||||
return True, f"Found {len(lines)} log entries"
|
||||
except FileNotFoundError:
|
||||
return False, "Prefix log not found"
|
||||
|
||||
def check_network_connectivity():
|
||||
"""Проверка сетевого подключения"""
|
||||
success, output, error = run_command("docker exec bgp-server ping -c 1 192.168.1.1")
|
||||
return success, "Network connectivity OK" if success else "Network connectivity failed"
|
||||
|
||||
def main():
|
||||
"""Основная функция мониторинга"""
|
||||
print("=== BGP Server Monitoring ===")
|
||||
print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
print()
|
||||
|
||||
# Проверка контейнера
|
||||
print("1. Container Status:")
|
||||
status, details = check_container_status()
|
||||
print(f" Status: {'✓ Running' if status else '✗ Stopped'}")
|
||||
print(f" Details: {details}")
|
||||
print()
|
||||
|
||||
# Проверка сети
|
||||
print("2. Network Connectivity:")
|
||||
net_ok, net_details = check_network_connectivity()
|
||||
print(f" Status: {'✓ OK' if net_ok else '✗ Failed'}")
|
||||
print(f" Details: {net_details}")
|
||||
print()
|
||||
|
||||
# Проверка BGP сессии
|
||||
print("3. BGP Session:")
|
||||
bgp_ok, bgp_details = check_bgp_session()
|
||||
print(f" Status: {'✓ Active' if bgp_ok else '✗ Inactive'}")
|
||||
if bgp_ok:
|
||||
print(f" Details: {bgp_details[:200]}...")
|
||||
else:
|
||||
print(f" Details: {bgp_details}")
|
||||
print()
|
||||
|
||||
# Проверка префиксов
|
||||
print("4. Prefixes:")
|
||||
prefix_ok, prefix_details = check_prefixes()
|
||||
print(f" Status: {'✓ Loaded' if prefix_ok else '✗ Not loaded'}")
|
||||
print(f" Details: {prefix_details}")
|
||||
print()
|
||||
|
||||
# Общий статус
|
||||
overall_status = status and net_ok and bgp_ok and prefix_ok
|
||||
print("=== Overall Status ===")
|
||||
print(f"Status: {'✓ HEALTHY' if overall_status else '✗ UNHEALTHY'}")
|
||||
|
||||
return 0 if overall_status else 1
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Скрипт для перезагрузки префиксов без перезапуска BGP сервера
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
def run_command(cmd):
|
||||
"""Выполнение команды"""
|
||||
try:
|
||||
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
||||
return result.returncode == 0, result.stdout, result.stderr
|
||||
except Exception as e:
|
||||
return False, "", str(e)
|
||||
|
||||
def reload_prefixes():
|
||||
"""Перезагрузка префиксов"""
|
||||
print("Reloading prefixes...")
|
||||
|
||||
# Остановка процесса загрузки префиксов
|
||||
print("Stopping prefix loader process...")
|
||||
success, output, error = run_command("docker exec bgp-server pkill -f load_prefixes.py")
|
||||
|
||||
if not success:
|
||||
print("Warning: Could not stop prefix loader process")
|
||||
|
||||
# Ожидание завершения процесса
|
||||
time.sleep(2)
|
||||
|
||||
# Проверка что процесс остановлен
|
||||
success, output, error = run_command("docker exec bgp-server pgrep -f load_prefixes.py")
|
||||
if success:
|
||||
print("Error: Prefix loader process is still running")
|
||||
return False
|
||||
|
||||
print("Prefix loader process stopped successfully")
|
||||
|
||||
# Запуск нового процесса загрузки префиксов
|
||||
print("Starting new prefix loader process...")
|
||||
success, output, error = run_command("docker exec bgp-server /app/scripts/load_prefixes.py &")
|
||||
|
||||
if success:
|
||||
print("Prefix loader process started successfully")
|
||||
return True
|
||||
else:
|
||||
print(f"Error starting prefix loader: {error}")
|
||||
return False
|
||||
|
||||
def check_status():
|
||||
"""Проверка статуса после перезагрузки"""
|
||||
print("Checking status...")
|
||||
time.sleep(5)
|
||||
|
||||
# Проверка процесса
|
||||
success, output, error = run_command("docker exec bgp-server pgrep -f load_prefixes.py")
|
||||
if success:
|
||||
print("✓ Prefix loader process is running")
|
||||
else:
|
||||
print("✗ Prefix loader process is not running")
|
||||
return False
|
||||
|
||||
# Проверка логов
|
||||
success, output, error = run_command("docker exec bgp-server tail -n 5 /app/logs/prefixes.log")
|
||||
if success:
|
||||
print("Recent log entries:")
|
||||
print(output)
|
||||
else:
|
||||
print("No recent log entries found")
|
||||
|
||||
return True
|
||||
|
||||
def main():
|
||||
"""Основная функция"""
|
||||
print("=== BGP Prefix Reloader ===")
|
||||
|
||||
# Проверка что контейнер запущен
|
||||
success, output, error = run_command("docker ps --filter name=bgp-server --format '{{.Status}}'")
|
||||
if not success or not output.strip():
|
||||
print("Error: BGP server container is not running")
|
||||
print("Please start the container first: docker-compose up -d")
|
||||
return 1
|
||||
|
||||
print("BGP server container is running")
|
||||
|
||||
# Перезагрузка префиксов
|
||||
if reload_prefixes():
|
||||
print("Prefix reload completed successfully")
|
||||
|
||||
# Проверка статуса
|
||||
if check_status():
|
||||
print("✓ All checks passed")
|
||||
return 0
|
||||
else:
|
||||
print("✗ Some checks failed")
|
||||
return 1
|
||||
else:
|
||||
print("✗ Prefix reload failed")
|
||||
return 1
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,96 @@
|
||||
# PowerShell скрипт для запуска BGP сервера
|
||||
|
||||
param(
|
||||
[switch]$Build,
|
||||
[switch]$Logs,
|
||||
[switch]$Monitor
|
||||
)
|
||||
|
||||
Write-Host "=== BGP Server Management ===" -ForegroundColor Green
|
||||
|
||||
# Проверка Docker
|
||||
Write-Host "Checking Docker..." -ForegroundColor Yellow
|
||||
try {
|
||||
docker --version | Out-Null
|
||||
Write-Host "✓ Docker is available" -ForegroundColor Green
|
||||
} catch {
|
||||
Write-Host "✗ Docker is not available. Please install Docker Desktop." -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Проверка Docker Compose
|
||||
Write-Host "Checking Docker Compose..." -ForegroundColor Yellow
|
||||
try {
|
||||
docker-compose --version | Out-Null
|
||||
Write-Host "✓ Docker Compose is available" -ForegroundColor Green
|
||||
} catch {
|
||||
Write-Host "✗ Docker Compose is not available." -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Создание необходимых директорий
|
||||
Write-Host "Creating directories..." -ForegroundColor Yellow
|
||||
if (!(Test-Path "logs")) {
|
||||
New-Item -ItemType Directory -Path "logs" | Out-Null
|
||||
Write-Host "✓ Created logs directory" -ForegroundColor Green
|
||||
}
|
||||
|
||||
if (!(Test-Path "data")) {
|
||||
New-Item -ItemType Directory -Path "data" | Out-Null
|
||||
Write-Host "✓ Created data directory" -ForegroundColor Green
|
||||
}
|
||||
|
||||
# Сборка образа если требуется
|
||||
if ($Build) {
|
||||
Write-Host "Building Docker image..." -ForegroundColor Yellow
|
||||
docker-compose build
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "✗ Build failed" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
Write-Host "✓ Build completed" -ForegroundColor Green
|
||||
}
|
||||
|
||||
# Остановка существующего контейнера
|
||||
Write-Host "Stopping existing container..." -ForegroundColor Yellow
|
||||
docker-compose down 2>$null
|
||||
Write-Host "✓ Existing container stopped" -ForegroundColor Green
|
||||
|
||||
# Запуск сервера
|
||||
Write-Host "Starting BGP server..." -ForegroundColor Yellow
|
||||
docker-compose up -d
|
||||
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
Write-Host "✓ BGP server started successfully" -ForegroundColor Green
|
||||
|
||||
# Ожидание запуска
|
||||
Write-Host "Waiting for server to initialize..." -ForegroundColor Yellow
|
||||
Start-Sleep -Seconds 10
|
||||
|
||||
# Проверка статуса
|
||||
Write-Host "Checking server status..." -ForegroundColor Yellow
|
||||
$status = docker-compose ps
|
||||
Write-Host $status
|
||||
|
||||
if ($Logs) {
|
||||
Write-Host "Showing logs..." -ForegroundColor Yellow
|
||||
docker-compose logs -f bgp-server
|
||||
}
|
||||
|
||||
if ($Monitor) {
|
||||
Write-Host "Starting monitoring..." -ForegroundColor Yellow
|
||||
docker exec bgp-server python3 /app/scripts/monitor.py
|
||||
}
|
||||
|
||||
} else {
|
||||
Write-Host "✗ Failed to start BGP server" -ForegroundColor Red
|
||||
Write-Host "Check logs with: docker-compose logs bgp-server" -ForegroundColor Yellow
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "=== Setup Complete ===" -ForegroundColor Green
|
||||
Write-Host "Useful commands:" -ForegroundColor Cyan
|
||||
Write-Host " View logs: docker-compose logs -f bgp-server" -ForegroundColor White
|
||||
Write-Host " Check status: docker-compose ps" -ForegroundColor White
|
||||
Write-Host " Stop server: docker-compose down" -ForegroundColor White
|
||||
Write-Host " Monitor: docker exec bgp-server python3 /app/scripts/monitor.py" -ForegroundColor White
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Скрипт запуска BGP сервера
|
||||
|
||||
set -e
|
||||
|
||||
echo "Starting BGP Server..."
|
||||
|
||||
# Создание директорий если не существуют
|
||||
mkdir -p /app/logs
|
||||
|
||||
# Проверка наличия файлов с префиксами
|
||||
if [ ! -f "/app/data/prefixes.txt" ]; then
|
||||
echo "Warning: /app/data/prefixes.txt not found. Creating empty file."
|
||||
echo "# Default prefixes file" > /app/data/prefixes.txt
|
||||
echo "192.168.1.0/24" >> /app/data/prefixes.txt
|
||||
fi
|
||||
|
||||
# Проверка конфигурации
|
||||
echo "Validating ExaBGP configuration..."
|
||||
exabgp --validate /app/exabgp.conf
|
||||
|
||||
# Запуск ExaBGP в фоновом режиме
|
||||
echo "Starting ExaBGP..."
|
||||
exabgp /app/exabgp.conf &
|
||||
|
||||
# Сохранение PID
|
||||
EXABGP_PID=$!
|
||||
echo $EXABGP_PID > /app/logs/exabgp.pid
|
||||
|
||||
# Ожидание запуска
|
||||
sleep 5
|
||||
|
||||
# Проверка статуса
|
||||
if kill -0 $EXABGP_PID 2>/dev/null; then
|
||||
echo "ExaBGP started successfully with PID: $EXABGP_PID"
|
||||
else
|
||||
echo "Failed to start ExaBGP"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Функция для graceful shutdown
|
||||
cleanup() {
|
||||
echo "Shutting down BGP server..."
|
||||
if [ -f "/app/logs/exabgp.pid" ]; then
|
||||
kill $(cat /app/logs/exabgp.pid) 2>/dev/null || true
|
||||
fi
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Обработка сигналов
|
||||
trap cleanup SIGTERM SIGINT
|
||||
|
||||
# Ожидание завершения
|
||||
wait $EXABGP_PID
|
||||
@@ -0,0 +1,33 @@
|
||||
# PowerShell скрипт для остановки BGP сервера
|
||||
|
||||
Write-Host "=== Stopping BGP Server ===" -ForegroundColor Yellow
|
||||
|
||||
# Проверка что контейнер запущен
|
||||
$containerStatus = docker ps --filter name=bgp-server --format "{{.Status}}"
|
||||
if (!$containerStatus) {
|
||||
Write-Host "BGP server is not running" -ForegroundColor Yellow
|
||||
exit 0
|
||||
}
|
||||
|
||||
Write-Host "BGP server is running. Stopping..." -ForegroundColor Yellow
|
||||
|
||||
# Остановка контейнера
|
||||
docker-compose down
|
||||
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
Write-Host "✓ BGP server stopped successfully" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host "✗ Failed to stop BGP server" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Проверка что контейнер остановлен
|
||||
$containerStatus = docker ps --filter name=bgp-server --format "{{.Status}}"
|
||||
if (!$containerStatus) {
|
||||
Write-Host "✓ Container is stopped" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host "✗ Container is still running" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "=== BGP Server Stopped ===" -ForegroundColor Green
|
||||
Reference in New Issue
Block a user