|
| 1 | +# Copyright 2026 FlagOS Contributors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Shared lifecycle helpers for opt-in runner diagnostics.""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import math |
| 20 | +import os |
| 21 | +import re |
| 22 | +import shlex |
| 23 | +from typing import Protocol |
| 24 | + |
| 25 | +ACTIVE_RUN_ID_FILENAME = "diagnostics.active_run_id" |
| 26 | +_RUN_ID_PATTERN = re.compile(r"^[A-Za-z0-9_.-]+$") |
| 27 | + |
| 28 | + |
| 29 | +class DiagnosticLaunchConfig(Protocol): |
| 30 | + enabled: bool |
| 31 | + |
| 32 | + def command_exit_actions(self, node_rank: int) -> list[str]: ... |
| 33 | + |
| 34 | + |
| 35 | +def active_run_id_file(pids_dir: str) -> str: |
| 36 | + """Return the stable file used to find the currently active diagnostic run.""" |
| 37 | + |
| 38 | + return os.path.join(str(pids_dir), ACTIVE_RUN_ID_FILENAME) |
| 39 | + |
| 40 | + |
| 41 | +def read_active_run_id(path: str) -> str | None: |
| 42 | + """Read and validate the active diagnostic run id.""" |
| 43 | + |
| 44 | + try: |
| 45 | + with open(path, encoding="utf-8") as file_obj: |
| 46 | + run_id = file_obj.read().strip() |
| 47 | + except OSError: |
| 48 | + return None |
| 49 | + |
| 50 | + if not _RUN_ID_PATTERN.fullmatch(run_id): |
| 51 | + return None |
| 52 | + return run_id |
| 53 | + |
| 54 | + |
| 55 | +def active_run_id_setup_lines(path: str, run_id: str, node_rank: int) -> list[str]: |
| 56 | + """Atomically publish one run id from node zero when its run script starts.""" |
| 57 | + |
| 58 | + if node_rank != 0: |
| 59 | + return [] |
| 60 | + if not _RUN_ID_PATTERN.fullmatch(run_id): |
| 61 | + raise ValueError(f"Invalid diagnostics run id: {run_id!r}") |
| 62 | + |
| 63 | + qpath = shlex.quote(path) |
| 64 | + qdir = shlex.quote(os.path.dirname(path)) |
| 65 | + qrun_id = shlex.quote(run_id) |
| 66 | + return [ |
| 67 | + f"mkdir -p {qdir}", |
| 68 | + f"diagnostics_run_id_tmp={qpath}.$$.tmp", |
| 69 | + f"printf '%s\\n' {qrun_id} > \"$diagnostics_run_id_tmp\"", |
| 70 | + f'mv -f "$diagnostics_run_id_tmp" {qpath}', |
| 71 | + ] |
| 72 | + |
| 73 | + |
| 74 | +def active_run_id_cleanup_action(path: str, run_id: str) -> str: |
| 75 | + """Remove the active marker only when it still belongs to this run.""" |
| 76 | + |
| 77 | + qpath = shlex.quote(path) |
| 78 | + qrun_id = shlex.quote(run_id) |
| 79 | + return ( |
| 80 | + f'if [ -f {qpath} ] && [ \\"\\$(cat {qpath})\\" = {qrun_id} ]; ' |
| 81 | + f"then rm -f {qpath}; fi" |
| 82 | + ) |
| 83 | + |
| 84 | + |
| 85 | +def active_run_id_cleanup_lines(path: str, run_id: str) -> list[str]: |
| 86 | + """Return direct shell lines that clear matching active state during stop.""" |
| 87 | + |
| 88 | + qpath = shlex.quote(path) |
| 89 | + qrun_id = shlex.quote(run_id) |
| 90 | + return [ |
| 91 | + f'if [ -f {qpath} ] && [ "$(cat {qpath})" = {qrun_id} ]; then', |
| 92 | + f" rm -f {qpath}", |
| 93 | + "fi", |
| 94 | + ] |
| 95 | + |
| 96 | + |
| 97 | +def diagnostic_command_body( |
| 98 | + node_rank: int, |
| 99 | + *configs: DiagnosticLaunchConfig, |
| 100 | + active_run_id_path: str = "", |
| 101 | + active_run_id: str = "", |
| 102 | +) -> str: |
| 103 | + """Write monitor completion markers and clear active state on normal exit.""" |
| 104 | + |
| 105 | + actions = [ |
| 106 | + action |
| 107 | + for config in configs |
| 108 | + if config.enabled |
| 109 | + for action in config.command_exit_actions(node_rank) |
| 110 | + ] |
| 111 | + if node_rank == 0 and active_run_id_path and active_run_id: |
| 112 | + actions.append(active_run_id_cleanup_action(active_run_id_path, active_run_id)) |
| 113 | + if not actions: |
| 114 | + return "$cmd; sync" |
| 115 | + return f"$cmd; rc=\\$?; {'; '.join(dict.fromkeys(actions))}; sync; exit \\$rc" |
| 116 | + |
| 117 | + |
| 118 | +def stop_process_shell_lines( |
| 119 | + pid_file: str, |
| 120 | + process_marker: str, |
| 121 | + *, |
| 122 | + timeout_s: float = 5.0, |
| 123 | + poll_interval_s: float = 0.1, |
| 124 | +) -> list[str]: |
| 125 | + """Safely terminate one recorded diagnostic process with a bounded wait.""" |
| 126 | + |
| 127 | + attempts = max(1, math.ceil(timeout_s / poll_interval_s)) |
| 128 | + qpid_file = shlex.quote(pid_file) |
| 129 | + qmarker = shlex.quote(process_marker) |
| 130 | + return [ |
| 131 | + f"if [ -f {qpid_file} ]; then", |
| 132 | + f' diagnostics_pid="$(cat {qpid_file})"', |
| 133 | + ' if [[ "$diagnostics_pid" =~ ^[0-9]+$ ]] && ' |
| 134 | + f'ps -p "$diagnostics_pid" -o args= 2>/dev/null | grep -F -- {qmarker} >/dev/null; then', |
| 135 | + ' kill "$diagnostics_pid" 2>/dev/null || true', |
| 136 | + f" for ((diagnostics_wait=0; diagnostics_wait<{attempts}; diagnostics_wait++)); do", |
| 137 | + ' kill -0 "$diagnostics_pid" 2>/dev/null || break', |
| 138 | + f" sleep {poll_interval_s:g}", |
| 139 | + " done", |
| 140 | + ' if kill -0 "$diagnostics_pid" 2>/dev/null; then', |
| 141 | + ' kill -KILL "$diagnostics_pid" 2>/dev/null || true', |
| 142 | + " fi", |
| 143 | + " fi", |
| 144 | + f" rm -f {qpid_file}", |
| 145 | + "fi", |
| 146 | + ] |
| 147 | + |
| 148 | + |
| 149 | +def wait_for_file_removal_shell_lines( |
| 150 | + path: str, |
| 151 | + *, |
| 152 | + timeout_s: float = 10.0, |
| 153 | + poll_interval_s: float = 0.1, |
| 154 | +) -> list[str]: |
| 155 | + """Wait for node zero to finish stopping a shared diagnostic process.""" |
| 156 | + |
| 157 | + attempts = max(1, math.ceil(timeout_s / poll_interval_s)) |
| 158 | + qpath = shlex.quote(path) |
| 159 | + return [ |
| 160 | + f"for ((diagnostics_wait=0; diagnostics_wait<{attempts}; diagnostics_wait++)); do", |
| 161 | + f" [ ! -f {qpath} ] && break", |
| 162 | + f" sleep {poll_interval_s:g}", |
| 163 | + "done", |
| 164 | + ] |
0 commit comments