rewrite
This commit is contained in:
83
database/migration.py
Normal file
83
database/migration.py
Normal file
@@ -0,0 +1,83 @@
|
||||
"""Migration: Import existing HAProxy config to database"""
|
||||
|
||||
import re
|
||||
from database import db
|
||||
from database.models import VirtualHost, BackendServer
|
||||
|
||||
def parse_existing_haproxy_config(config_path):
|
||||
"""Parse existing haproxy.cfg and import to DB"""
|
||||
try:
|
||||
with open(config_path, 'r') as f:
|
||||
config_content = f.read()
|
||||
|
||||
print(f"[MIGRATION] Parsing {config_path}...")
|
||||
|
||||
# Pattern: frontend FNAME ...
|
||||
frontend_pattern = r'frontend\s+(\S+)\s*\n(.*?)(?=\n\nbackend|\Z)'
|
||||
frontends = re.findall(frontend_pattern, config_content, re.DOTALL)
|
||||
|
||||
vhost_count = 0
|
||||
for fe_name, fe_content in frontends:
|
||||
# Skip stats frontend
|
||||
if 'stats' in fe_name.lower():
|
||||
continue
|
||||
|
||||
# Extract bind
|
||||
bind_match = re.search(r'bind\s+([^\s:]+):(\d+)', fe_content)
|
||||
if not bind_match:
|
||||
continue
|
||||
|
||||
ip, port = bind_match.groups()
|
||||
|
||||
# Extract backend name
|
||||
backend_match = re.search(r'default_backend\s+(\S+)', fe_content)
|
||||
backend_name = backend_match.group(1) if backend_match else f'be_{fe_name}'
|
||||
|
||||
# Check if already exists
|
||||
vhost = VirtualHost.query.filter_by(name=fe_name).first()
|
||||
if vhost:
|
||||
print(f"[MIGRATION] Vhost '{fe_name}' already exists, skipping...")
|
||||
continue
|
||||
|
||||
# Create vhost
|
||||
vhost = VirtualHost(
|
||||
name=fe_name,
|
||||
hostname=f"{fe_name}.local",
|
||||
frontend_ip=ip,
|
||||
frontend_port=int(port),
|
||||
protocol='http',
|
||||
use_ssl='ssl' in fe_content,
|
||||
enabled=True
|
||||
)
|
||||
|
||||
db.session.add(vhost)
|
||||
db.session.flush() # Get vhost.id
|
||||
|
||||
# Parse backend servers
|
||||
be_pattern = rf'backend\s+{re.escape(backend_name)}\s*\n(.*?)(?=\nbackend|\Z)'
|
||||
be_match = re.search(be_pattern, config_content, re.DOTALL)
|
||||
|
||||
if be_match:
|
||||
servers_pattern = r'server\s+(\S+)\s+([^\s:]+):(\d+)'
|
||||
servers = re.findall(servers_pattern, be_match.group(1))
|
||||
|
||||
for srv_name, srv_ip, srv_port in servers:
|
||||
server = BackendServer(
|
||||
vhost_id=vhost.id,
|
||||
name=srv_name,
|
||||
ip_address=srv_ip,
|
||||
port=int(srv_port),
|
||||
enabled=True
|
||||
)
|
||||
db.session.add(server)
|
||||
|
||||
vhost_count += 1
|
||||
|
||||
db.session.commit()
|
||||
print(f"[MIGRATION] Successfully imported {vhost_count} vhosts!", flush=True)
|
||||
return vhost_count
|
||||
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
print(f"[MIGRATION] Error: {e}", flush=True)
|
||||
return 0
|
||||
Reference in New Issue
Block a user