dgd.py 10.9 KB
Newer Older
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
DynamoGraphDeployment helpers -- backend switch, restart, readiness.

Ported from sweep.sh functions: dgd_switch_backend, dgd_restart_frontend,
dgd_restart_graph, dgd_wait_all_ready.
"""

from __future__ import annotations

import json
import random
import subprocess
import time
import urllib.error
import urllib.request

from sweep_k8s.kubectl import (
    delete_pod,
    get_json,
    get_pod_name,
    patch_json,
    patch_merge,
    run_kubectl,
    wait_for_pod_deletion,
    wait_pod,
)

# Tokenizer backend name mapping for DGD env vars
TOKENIZER_BACKEND_MAP = {
    "hf": "default",
    "default": "default",
    "fast": "fast",
    "fastokens": "fast",
}


def dgd_label_selector(dgd_name: str, component_type: str) -> str:
    """Build a label selector for DGD-managed pods."""
    return (
        f"nvidia.com/dynamo-graph-deployment-name={dgd_name},"
        f"nvidia.com/dynamo-component-type={component_type}"
    )


def wait_model_ready(
    endpoint: str,
    model_name: str,
    max_wait: int = 300,
    namespace: str = "",
) -> None:
    """Wait for a model to be registered at the frontend /v1/models endpoint.

    Tries direct HTTP first. If the endpoint is not reachable from localhost
    (in-cluster DNS), falls back to kubectl run to check from inside the cluster.
    """
    print(f"  Waiting for model '{model_name}' at http://{endpoint}/v1/models...")
    waited = 0
    while True:
        # Try direct HTTP (works if endpoint is port-forwarded or localhost)
        try:
            req = urllib.request.Request(
                f"http://{endpoint}/v1/models",
                headers={"Accept": "application/json"},
            )
            with urllib.request.urlopen(req, timeout=10) as resp:
                data = json.loads(resp.read().decode())
                models = data.get("data", [])
                if any(m.get("id") == model_name for m in models):
                    print(f"  Model ready (waited {waited}s)")
                    return
        except (urllib.error.URLError, json.JSONDecodeError, OSError, ValueError):
            pass

        # Fallback: kubectl-based check for in-cluster endpoints
        if namespace and _check_model_via_kubectl(endpoint, model_name, namespace):
            print(f"  Model ready via kubectl (waited {waited}s)")
            return

        time.sleep(5)
        waited += 5
        if waited >= max_wait:
            print(f"ERROR: Model not ready after {max_wait}s")
            raise TimeoutError(f"Model '{model_name}' not ready after {max_wait}s")
        if waited % 15 == 0:
            print(f"  Still waiting ({waited}s / {max_wait}s)...")


def _check_model_via_kubectl(
    endpoint: str,
    model_name: str,
    namespace: str,
) -> bool:
    """Check model readiness by running curl from inside the cluster."""
    pod_name = f"model-check-{int(time.time())}-{random.randint(0, 9999)}"
    try:
        result = subprocess.run(
            [
                "kubectl",
                "run",
                pod_name,
                "--rm",
                "-i",
                "--restart=Never",
                "-n",
                namespace,
                "--quiet",
                "--image=curlimages/curl:latest",
                "--",
                "-sf",
                f"http://{endpoint}/v1/models",
            ],
            capture_output=True,
            text=True,
            timeout=20,
        )
        if result.returncode == 0 and result.stdout.strip():
            data = json.loads(result.stdout)
            models = data.get("data", [])
            return any(m.get("id") == model_name for m in models)
    except (subprocess.SubprocessError, json.JSONDecodeError, OSError):
        pass
    return False


def dgd_wait_all_ready(
    dgd_name: str,
    namespace: str,
    endpoint: str,
    model_name: str,
    max_wait: int = 300,
) -> None:
    """Wait for all DGD worker pods to be Ready, then wait for model endpoint."""
    print("  Waiting for all worker pods to be Ready...")
    retries = 3
    for attempt in range(retries):
        try:
            wait_pod(
                dgd_label_selector(dgd_name, "worker"),
                namespace,
                timeout=max_wait,
            )
            break
        except subprocess.TimeoutExpired:
            raise
        except subprocess.CalledProcessError as e:
            if attempt < retries - 1:
                print(f"  kubectl error (attempt {attempt + 1}/{retries}), retrying...")
                time.sleep(5)
            else:
                raise RuntimeError(
                    f"Worker pods not ready after {retries} retries: {e}"
                ) from e

    wait_model_ready(endpoint, model_name, max_wait, namespace=namespace)


def dgd_switch_backend(
    dgd_name: str,
    namespace: str,
    endpoint: str,
    model_name: str,
    backend: str,
) -> None:
    """Switch tokenizer backend on a DynamoGraphDeployment.

    Patches the DGD spec to set DYN_TOKENIZER_BACKEND; the Grove operator
    recreates the frontend pod automatically.
    """
    mapped_backend = TOKENIZER_BACKEND_MAP.get(backend, backend)
    print(
        f"\n--- Switching DGD tokenizer backend -> {mapped_backend} (dgd={dgd_name}) ---"
    )

    # Find the index of DYN_TOKENIZER_BACKEND in the Frontend env array
    try:
        dgd_json = get_json("dgd", dgd_name, namespace)
        env_list = (
            dgd_json.get("spec", {})
            .get("services", {})
            .get("Frontend", {})
            .get("extraPodSpec", {})
            .get("mainContainer", {})
            .get("env", [])
        )
        idx = None
        for i, env_var in enumerate(env_list):
            if env_var.get("name") == "DYN_TOKENIZER_BACKEND":
                idx = i
                break
    except Exception:
        idx = None

    # Capture the current frontend pod name BEFORE patching so we track
    # the right pod for deletion (avoids racing with the operator).
    old_pod = get_pod_name(
        dgd_label_selector(dgd_name, "frontend"),
        namespace,
    )

    if idx is not None:
        patch_json(
            "dgd",
            dgd_name,
            namespace,
            [
                {
                    "op": "replace",
                    "path": f"/spec/services/Frontend/extraPodSpec/mainContainer/env/{idx}/value",
                    "value": mapped_backend,
                }
            ],
        )
    else:
        patch_json(
            "dgd",
            dgd_name,
            namespace,
            [
                {
                    "op": "add",
                    "path": "/spec/services/Frontend/extraPodSpec/mainContainer/env/-",
                    "value": {"name": "DYN_TOKENIZER_BACKEND", "value": mapped_backend},
                }
            ],
        )

    print("  DGD patched -- waiting for frontend pod replacement...")
    if old_pod:
        print(f"  Waiting for old pod {old_pod} to terminate...")
        wait_for_pod_deletion(old_pod, namespace, timeout=120)

    # Wait for new frontend pod to be Ready
    print("  Waiting for new frontend pod to be Ready...")
    wait_pod(
        dgd_label_selector(dgd_name, "frontend"),
        namespace,
        timeout=300,
    )

    dgd_wait_all_ready(dgd_name, namespace, endpoint, model_name)


def dgd_restart_frontend(
    dgd_name: str,
    namespace: str,
    endpoint: str,
    model_name: str,
) -> None:
    """Restart only the frontend component to reset metrics counters."""
    print("  Restarting frontend pod to reset metrics counters...")

    old_pod = get_pod_name(
        dgd_label_selector(dgd_name, "frontend"),
        namespace,
    )

    if old_pod:
        delete_pod(old_pod, namespace, grace_period=5)
        print(f"  Waiting for old pod {old_pod} to terminate...")
        # Wait for delete
        try:
            run_kubectl(
                ["wait", "pod", old_pod, "--for=delete", "--timeout=90s"],
                namespace=namespace,
                check=False,
            )
        except Exception:
            pass

    print("  Waiting for new frontend pod to be Ready...")
    wait_pod(
        dgd_label_selector(dgd_name, "frontend"),
        namespace,
        timeout=300,
    )

    dgd_wait_all_ready(dgd_name, namespace, endpoint, model_name)


def dgd_restart_graph(
    dgd_name: str,
    namespace: str,
    endpoint: str,
    model_name: str,
) -> None:
    """Trigger a full DGD restart through spec.restart.

    Every run starts from a clean graph deployment state.
    """
    restart_id = f"bench-{time.strftime('%Y%m%d-%H%M%S')}-{random.randint(0, 9999)}"
    print(f"  Restarting full DGD deployment (id={restart_id})...")

    # Discover service names from the DGD spec so the restart order is correct
    # for any backend (mocker, vllm, trtllm, etc.)
    try:
        dgd_spec = get_json("dgd", dgd_name, namespace, timeout=60)
        services = list(dgd_spec.get("spec", {}).get("services", {}).keys())
        # Put workers before frontend: restart workers first, then frontend
        frontend_names = [s for s in services if s.lower() == "frontend"]
        worker_names = [s for s in services if s.lower() != "frontend"]
        restart_order = worker_names + frontend_names
    except Exception:
        restart_order = ["Frontend"]

    print(f"  Restart order: {restart_order}")

    patch_merge(
        "dgd",
        dgd_name,
        namespace,
        {
            "spec": {
                "restart": {
                    "id": restart_id,
                    "strategy": {
                        "type": "Sequential",
                        "order": restart_order,
                    },
                }
            }
        },
    )

    waited = 0
    phase = "pending"
    while True:
        try:
            state_json = get_json("dgd", dgd_name, namespace, timeout=60)
            restart_status = state_json.get("status", {}).get("restart", {})
            observed = restart_status.get("observedID", "")
            phase = restart_status.get("phase", "")

            if observed == restart_id:
                if phase == "Completed":
                    print(f"  DGD restart completed (waited {waited}s)")
                    break
                elif phase in ("Failed", "Superseded"):
                    raise RuntimeError(
                        f"DGD restart {restart_id} ended with phase={phase}"
                    )
        except (KeyError, TypeError):
            pass
        except (subprocess.TimeoutExpired, subprocess.CalledProcessError) as e:
            # Transient kubectl timeout -- retry
            print(f"  kubectl transient error, retrying... ({e.__class__.__name__})")

        time.sleep(5)
        waited += 5
        if waited >= 600:
            raise TimeoutError(f"Timed out waiting for DGD restart {restart_id}")
        print(f"  Waiting for DGD restart ({waited}s / 600s)... phase={phase}")

    dgd_wait_all_ready(dgd_name, namespace, endpoint, model_name)