a-cloud-all/.devops/scripts/init/mysql.py

107 lines
3.4 KiB
Python
Raw Permalink Normal View History

2026-01-10 15:15:45 +08:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MySQL 初始化模块
"""
import os
import subprocess
import shutil
from pathlib import Path
import sys
# 添加父目录到路径
sys.path.insert(0, str(Path(__file__).parent.parent))
from log import Logger
def init_mysql(project_root, pre_deploy_commands=None):
"""
初始化 MySQL
参数
project_root: 项目根目录
pre_deploy_commands: 预部署命令列表可选
返回
bool: 成功返回 True失败返回 False
"""
try:
project_root = Path(project_root).resolve()
Logger.separator()
Logger.info("开始初始化 MySQL")
Logger.separator()
Logger.info(f"项目根目录: {project_root}")
# 定义路径
sql_dir = project_root / "sql"
target_dir = project_root / "docker" / "mysql" / "db"
docker_dir = project_root / "docker"
# 复制 SQL 脚本
Logger.info("复制 SQL 脚本到 MySQL 初始化目录")
Logger.info(f"源目录: {sql_dir}")
Logger.info(f"目标目录: {target_dir}")
target_dir.mkdir(parents=True, exist_ok=True)
# 如果提供了预部署命令,从中提取 SQL 文件名
if pre_deploy_commands:
for cmd in pre_deploy_commands:
# 解析命令cp sql/xxx.sql docker/mysql/db/
if cmd.startswith('cp ') and '.sql' in cmd:
parts = cmd.split()
if len(parts) >= 2:
source_path = parts[1] # sql/xxx.sql
sql_file = Path(source_path).name
source_file = project_root / source_path
if source_file.exists():
Logger.info(f"复制文件: {sql_file}")
shutil.copy2(source_file, target_dir / sql_file)
else:
Logger.warn(f"SQL 文件不存在: {source_file}")
else:
# 默认的 SQL 文件列表(向后兼容)
sql_files = [
"ry_20250523.sql",
"ry_config_20250902.sql"
]
for sql_file in sql_files:
source_file = sql_dir / sql_file
if source_file.exists():
Logger.info(f"复制文件: {sql_file}")
shutil.copy2(source_file, target_dir / sql_file)
else:
Logger.warn(f"SQL 文件不存在: {source_file}")
Logger.info("目标目录内容:")
for item in target_dir.iterdir():
Logger.info(f" - {item.name}")
# 构建并启动 MySQL 容器
Logger.separator()
Logger.info("构建 MySQL 镜像")
Logger.separator()
Logger.info(f"执行目录: {docker_dir}")
2026-01-10 15:21:06 +08:00
if not Logger.run_command("docker-compose build --no-cache ruoyi-mysql", docker_dir):
2026-01-10 15:15:45 +08:00
Logger.error("MySQL 镜像构建失败")
return False
Logger.info("MySQL 镜像构建成功")
2026-01-10 15:21:06 +08:00
if not Logger.run_command("docker-compose up -d ruoyi-mysql", docker_dir):
2026-01-10 15:15:45 +08:00
Logger.error("MySQL 容器启动失败")
return False
Logger.info("MySQL 容器启动成功")
Logger.info("MySQL 初始化完成")
return True
except Exception as e:
Logger.error(f"MySQL 初始化异常: {e}")
return False