File size: 4,062 Bytes
06bf615
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/usr/bin/env python3
"""Hugging Face Jobs entrypoint for the AWS Steam GPU Launch Kit.

This runs *inside* a Hub Job. It fetches this repo from the Hub, then either
validates it (no credentials needed) or deploys it (AWS credentials injected as
Hub secrets, so nothing long-lived is written to disk in the repo or the image).

MODE=validate  -> static checks only, no AWS calls
MODE=deploy    -> validate, then run launch.sh on Hub compute
MODE=diagnose  -> validate, then run the SSM diagnostic against an existing host

Environment:
  LAUNCHKIT_REPO   default Allszn/aws-steam-gpu-launchkit
  LAUNCHKIT_REV    branch, tag or revision (default: main)
  MODE             validate | deploy | diagnose   (default: validate)
  plus everything launch.sh reads: INSTANCE_TYPE, KEY_NAME, ADMIN_CIDR,
  GAME_VOLUME_GIB, ARTIFACT_BUCKET, STACK_NAME, AWS_REGION, INSTANCE_ID
"""

from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path


DEFAULT_REPO = "Allszn/aws-steam-gpu-launchkit"


def log(msg: str) -> None:
    print(f"[hf-job] {msg}", flush=True)


def fetch(repo_id: str, revision: str | None, token: str | None) -> Path:
    from huggingface_hub import snapshot_download

    log(f"fetching {repo_id}@{revision or 'main'} from the Hub")
    path = snapshot_download(
        repo_id=repo_id,
        repo_type="dataset",
        revision=revision,
        token=token,
        allow_patterns=[
            "cloudformation/*",
            "scripts/*",
            "iam/*",
            "ssm/*",
            "launch.sh",
            "launch.py",
            "README.md",
        ],
    )
    root = Path(path)
    log(f"artifacts at {root}")
    for f in sorted(root.rglob("*")):
        if f.is_file():
            log(f"  {f.relative_to(root)}  ({f.stat().st_size} bytes)")
    return root


def run(cmd: list[str], cwd: Path, env: dict[str, str]) -> int:
    log(f"$ {' '.join(cmd)}")
    proc = subprocess.run(cmd, cwd=str(cwd), env=env, text=True)
    return proc.returncode


def main() -> int:
    repo_id = os.environ.get("LAUNCHKIT_REPO", DEFAULT_REPO)
    revision = os.environ.get("LAUNCHKIT_REV") or None
    mode = os.environ.get("MODE", "validate").strip().lower()
    token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")

    root = fetch(repo_id, revision, token)

    env = dict(os.environ)
    env.setdefault("AWS_REGION", "us-east-1")

    # ------------------------------------------------------------------ step 1
    log("step 1/2 - static validation (no AWS credentials required)")
    rc = run([sys.executable, "scripts/validate.py", "--root", ".", "--pretty"], root, env)
    if rc != 0:
        log("validation FAILED - refusing to proceed to an AWS deploy")
        return rc

    if mode == "validate":
        log("done. Set MODE=deploy to apply, or MODE=diagnose to inspect a running host.")
        return 0

    # ------------------------------------------------------------------ step 2
    if not (env.get("AWS_ACCESS_KEY_ID") or env.get("AWS_PROFILE")):
        log("no AWS credentials found in the environment.")
        log("pass them as Hub secrets, for example:")
        log("  --secrets AWS_ACCESS_KEY_ID --secrets AWS_SECRET_ACCESS_KEY --secrets AWS_REGION")
        return 2

    launch = root / "launch.sh"
    launch.chmod(0o755)

    if mode == "diagnose":
        instance_id = env.get("INSTANCE_ID")
        if not instance_id:
            log("MODE=diagnose requires INSTANCE_ID")
            return 2
        log(f"step 2/2 - running the SSM diagnostic against {instance_id}")
        return run(
            [
                "aws", "ssm", "send-command",
                "--document-name", "SteamGpu-Diagnose",
                "--instance-ids", instance_id,
                "--comment", "launchkit diagnose via Hugging Face Job",
            ],
            root, env,
        )

    log("step 2/2 - deploying via launch.sh on Hub compute")
    return run(["bash", str(launch)], root, env)


if __name__ == "__main__":
    sys.exit(main())