|
| 1 | +import subprocess |
| 2 | +from importlib.metadata import version |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +import click |
| 6 | +import rich |
| 7 | +from rich.box import ROUNDED |
| 8 | +from rich.panel import Panel |
| 9 | + |
| 10 | +from codegen.cli.auth.session import CodegenSession |
| 11 | +from codegen.cli.workspace.decorators import requires_init |
| 12 | + |
| 13 | + |
| 14 | +@click.command(name="start") |
| 15 | +@requires_init |
| 16 | +@click.option("--platform", "-t", type=click.Choice(["linux/amd64", "linux/arm64", "linux/amd64,linux/arm64"]), default="linux/amd64,linux/arm64", help="Target platform(s) for the Docker image") |
| 17 | +@click.option("--port", "-p", type=int, default=8000) |
| 18 | +@click.option("--detached", "-d", is_flag=True, default=False, help="Starts up the server as detached background process") |
| 19 | +def start_command(session: CodegenSession, port: int, platform: str, detached: bool): |
| 20 | + """Starts a local codegen server""" |
| 21 | + codegen_version = version("codegen") |
| 22 | + rich.print(codegen_version) |
| 23 | + repo_root = Path(__file__).parent.parent.parent.parent.parent.parent |
| 24 | + dockerfile_path = repo_root / "Dockerfile-runner" |
| 25 | + |
| 26 | + # Build the Docker image |
| 27 | + rich.print("[bold blue]Building Docker image...[/bold blue]") |
| 28 | + build_cmd = [ |
| 29 | + "docker", |
| 30 | + "buildx", |
| 31 | + "build", |
| 32 | + "--platform", |
| 33 | + platform, |
| 34 | + "-f", |
| 35 | + str(dockerfile_path), |
| 36 | + "-t", |
| 37 | + "codegen-runner", |
| 38 | + "--load", |
| 39 | + str(repo_root), |
| 40 | + ] |
| 41 | + rich.print(f"build_cmd: {str.join(' ', build_cmd)}") |
| 42 | + |
| 43 | + try: |
| 44 | + subprocess.run(build_cmd, check=True) |
| 45 | + |
| 46 | + # Run the Docker container |
| 47 | + rich.print("[bold blue]Starting Docker container...[/bold blue]") |
| 48 | + run_mode = "-d" if detached else "-it" |
| 49 | + entry_point = f'"uv run --frozen uvicorn codegen.runner.sandbox.server:app --host 0.0.0.0 --port {port}"' |
| 50 | + run_cmd = ["docker", "run", run_mode, "-p", f"8000:{port}", "codegen-runner", entry_point] |
| 51 | + |
| 52 | + rich.print(f"run_cmd: {str.join(' ', run_cmd)}") |
| 53 | + subprocess.run(run_cmd, check=True) |
| 54 | + |
| 55 | + rich.print(Panel(f"[green]Server started successfully![/green]\nAccess the server at: [bold]http://0.0.0.0:{port}[/bold]", box=ROUNDED, title="Codegen Server")) |
| 56 | + |
| 57 | + except subprocess.CalledProcessError as e: |
| 58 | + rich.print(f"[bold red]Error:[/bold red] Failed to {e.cmd[0]} Docker container") |
| 59 | + raise click.Abort() |
| 60 | + except Exception as e: |
| 61 | + rich.print(f"[bold red]Error:[/bold red] {e!s}") |
| 62 | + raise click.Abort() |
0 commit comments