import yaml
import time
import subprocess

# 配置：延时秒数
DELAY_SECONDS = 10

def start_containers():
    try:
        # 1. 读取 compose 文件获取服务列表
        with open('docker-compose.yml', 'r') as f:
            compose_data = yaml.safe_load(f)
        
        services = list(compose_data.get('services', {}).keys())
        
        if not services:
            print("错误: 未在 docker-compose.yml 中找到任何服务。")
            return

        print(f"检测到 {len(services)} 个服务，将按顺序启动并延时 {DELAY_SECONDS}s...")

        # 2. 逐个启动服务
        for service in services:
            print(f"正在启动容器: {service} ...")
            # 使用 docker-compose up -d [服务名] 启动特定容器
            subprocess.run(["docker-compose", "up", "-d", service], check=True)
            
            # 最后一个容器启动后不需要等待
            if service != services[-1]:
                time.sleep(DELAY_SECONDS)
                print(f"等待 {DELAY_SECONDS}s...")

        print("\n所有容器已按序启动完成！")

    except FileNotFoundError:
        print("错误: 当前目录下找不到 docker-compose.yml")
    except Exception as e:
        print(f"运行出错: {e}")

if __name__ == "__main__":
    start_containers()
