2026-11-14 14:07:26 +08:00
|
|
|
"""Confined transfer storage and redacted telemetry for a remote business API."""
|
|
|
|
|
from contextlib import contextmanager
|
|
|
|
|
import json
|
|
|
|
|
import math
|
|
|
|
|
import os
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
import re
|
|
|
|
|
import uuid
|
|
|
|
|
|
|
|
|
|
from .gpu_policy import GpuPolicy
|
|
|
|
|
from .scheduling import read_runtime_policy
|
|
|
|
|
from .store import open_confined_file
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
INPUT_NAME = re.compile(r"([0-9a-f]{64})\.(png|jpg|jpeg|webp|bmp|wav|mp3|flac|m4a|ogg|aac|mp4|webm|mov)\Z")
|
|
|
|
|
_UUID = re.compile(r"GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\Z")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@contextmanager
|
|
|
|
|
def input_writer(workspace, name):
|
|
|
|
|
"""Anchor Linux operations to no-follow directory descriptors; publish on success."""
|
|
|
|
|
root = Path(workspace).resolve(strict=True)
|
|
|
|
|
directory = root / 'inputs' / 'llm-services'
|
|
|
|
|
temporary = '.upload-' + uuid.uuid4().hex
|
|
|
|
|
descriptors = []
|
|
|
|
|
stream = None
|
|
|
|
|
published = False
|
|
|
|
|
try:
|
|
|
|
|
if os.name == 'posix':
|
|
|
|
|
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
|
|
|
|
descriptors.append(os.open(root, flags))
|
|
|
|
|
for part in ('inputs', 'llm-services'):
|
|
|
|
|
try:
|
|
|
|
|
os.mkdir(part, mode=0o700, dir_fd=descriptors[-1])
|
|
|
|
|
except FileExistsError:
|
|
|
|
|
pass
|
|
|
|
|
descriptors.append(os.open(part, flags, dir_fd=descriptors[-1]))
|
|
|
|
|
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
|
|
|
|
|
0o600, dir_fd=descriptors[-1])
|
|
|
|
|
else:
|
|
|
|
|
# Local Windows tests use the same confinement and symlink rejection.
|
|
|
|
|
for parent in (root / 'inputs', directory):
|
|
|
|
|
if parent.is_symlink() or parent.resolve() != parent:
|
|
|
|
|
raise ValueError('Unsafe input directory')
|
|
|
|
|
parent.mkdir(mode=0o700, exist_ok=True)
|
|
|
|
|
descriptor = os.open(directory / temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
|
|
|
stream = os.fdopen(descriptor, 'wb')
|
|
|
|
|
yield stream, directory / name
|
|
|
|
|
stream.flush()
|
|
|
|
|
os.fsync(stream.fileno())
|
|
|
|
|
stream.close()
|
|
|
|
|
if descriptors:
|
|
|
|
|
# The path returned to the runner must still identify this directory.
|
|
|
|
|
actual = Path(os.readlink(f'/proc/self/fd/{descriptors[-1]}'))
|
|
|
|
|
if actual != directory:
|
|
|
|
|
raise ValueError('Input directory changed')
|
|
|
|
|
os.replace(temporary, name, src_dir_fd=descriptors[-1], dst_dir_fd=descriptors[-1])
|
|
|
|
|
os.fsync(descriptors[-1])
|
|
|
|
|
else:
|
|
|
|
|
if directory.resolve() != directory:
|
|
|
|
|
raise ValueError('Input directory changed')
|
|
|
|
|
os.replace(directory / temporary, directory / name)
|
|
|
|
|
published = True
|
|
|
|
|
finally:
|
|
|
|
|
if stream is not None:
|
|
|
|
|
stream.close()
|
|
|
|
|
try:
|
|
|
|
|
if not published:
|
|
|
|
|
if descriptors and len(descriptors) == 3:
|
|
|
|
|
os.unlink(temporary, dir_fd=descriptors[-1])
|
|
|
|
|
elif not descriptors:
|
|
|
|
|
(directory / temporary).unlink(missing_ok=True)
|
|
|
|
|
except FileNotFoundError:
|
|
|
|
|
pass
|
|
|
|
|
finally:
|
|
|
|
|
for descriptor in reversed(descriptors):
|
|
|
|
|
os.close(descriptor)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _scheduler(settings):
|
|
|
|
|
try:
|
|
|
|
|
with open_confined_file(settings.state_dir / 'gpu-scheduler.json', settings.workspace_root) as handle:
|
|
|
|
|
raw = handle.read(1024 * 1024 + 1)
|
|
|
|
|
if len(raw) > 1024 * 1024:
|
|
|
|
|
return None
|
|
|
|
|
value = json.loads(raw)
|
|
|
|
|
stamp = value['updated_at']
|
|
|
|
|
if type(stamp) not in (int, float) or not math.isfinite(stamp) or stamp < 0:
|
|
|
|
|
return None
|
|
|
|
|
state = value['state']
|
|
|
|
|
if state not in {'idle', 'waiting', 'leased', 'running', 'blocked'}:
|
|
|
|
|
return None
|
|
|
|
|
schema = value.get('schema_version', 1)
|
|
|
|
|
if type(schema) is not int or schema not in {1, 2}:
|
|
|
|
|
return None
|
|
|
|
|
result = {'schema_version': schema, 'updated_at': stamp,
|
|
|
|
|
'state': state, 'reason': 'memory' if 'memory' in str(value.get('reason', '')).lower() else None}
|
|
|
|
|
if result['schema_version'] == 2:
|
|
|
|
|
entries = value.get('active_jobs', [])
|
|
|
|
|
count = value.get('queued_count')
|
|
|
|
|
if (not isinstance(entries, list) or len(entries) > 1024 or
|
|
|
|
|
(count is not None and (type(count) is not int or not 0 <= count <= 10000000))):
|
|
|
|
|
return None
|
|
|
|
|
result.update(queued_count=count, active_jobs=[])
|
|
|
|
|
for entry in entries:
|
|
|
|
|
index, gpu_uuid = entry['gpu_index'], entry['gpu_uuid']
|
|
|
|
|
if type(index) is not int or not 0 <= index <= 1024 or not isinstance(gpu_uuid, str) or not _UUID.fullmatch(gpu_uuid):
|
|
|
|
|
return None
|
|
|
|
|
result['active_jobs'].append({'gpu_index': index, 'gpu_uuid': gpu_uuid,
|
|
|
|
|
'state': entry.get('state') if entry.get('state') in
|
|
|
|
|
{'running', 'preempting', 'blocked', 'launching'} else 'running',
|
|
|
|
|
'stage': entry.get('stage') if entry.get('stage') in
|
|
|
|
|
{'launching', 'executing', 'cleanup', 'model', 'upscale', 'collecting'} else None})
|
2026-11-26 21:06:27 +08:00
|
|
|
if 'members' in entry:
|
|
|
|
|
raw = entry['members']
|
|
|
|
|
if not isinstance(raw, list) or len(raw) not in (1, 2):
|
|
|
|
|
raise ValueError("Invalid GPU member list")
|
|
|
|
|
members = []
|
|
|
|
|
for member in raw:
|
|
|
|
|
idx, uuid = member['index'], member['uuid']
|
|
|
|
|
if (type(idx) is not int or not 0 <= idx <= 1024
|
|
|
|
|
or not isinstance(uuid, str) or not _UUID.fullmatch(uuid)
|
|
|
|
|
or any(m['index'] == idx or m['uuid'].lower() == uuid.lower() for m in members)):
|
|
|
|
|
raise ValueError("Invalid GPU member")
|
|
|
|
|
members.append({'index': idx, 'uuid': uuid})
|
|
|
|
|
if members[0] != {'index': index, 'uuid': gpu_uuid}:
|
|
|
|
|
raise ValueError("Invalid primary GPU member")
|
|
|
|
|
result['active_jobs'][-1]['members'] = members
|
2026-11-14 14:07:26 +08:00
|
|
|
elif result['schema_version'] == 1 and state == 'leased':
|
|
|
|
|
lease = value['lease']
|
|
|
|
|
index, gpu_uuid = lease['index'], lease['uuid']
|
|
|
|
|
if type(index) is not int or not 0 <= index <= 1024 or not isinstance(gpu_uuid, str) or not _UUID.fullmatch(gpu_uuid):
|
|
|
|
|
return None
|
|
|
|
|
result['lease'] = {'index': index, 'uuid': gpu_uuid}
|
|
|
|
|
elif result['schema_version'] != 1:
|
|
|
|
|
return None
|
|
|
|
|
return result
|
|
|
|
|
except (OSError, ValueError, TypeError, KeyError, AttributeError, RecursionError):
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def runtime_status(settings):
|
|
|
|
|
monitor = {'schema_version': 1, 'generated_at': None,
|
|
|
|
|
'error': 'gpu_monitor_unavailable', 'gpus': []}
|
|
|
|
|
policy = GpuPolicy(os.environ.get('LLM_GPU_STATUS_PATH', '/run/llm-gpu-policy/status.json')).describe()
|
|
|
|
|
if policy['generated_at'] is not None:
|
|
|
|
|
monitor.update(generated_at=policy['generated_at'], error=None,
|
|
|
|
|
gpus=[{key: gpu[key] for key in ('index', 'uuid', 'total_gib', 'free_gib', 'idle_since')} |
|
|
|
|
|
{'external_busy': bool(gpu['external_processes']), 'own_busy': bool(gpu['own_processes'])}
|
|
|
|
|
for gpu in policy['gpus']])
|
|
|
|
|
return {'schema_version': 1, 'monitor': monitor, 'scheduler': _scheduler(settings),
|
|
|
|
|
'runtime_policy': read_runtime_policy(settings.runtime_policy_file)}
|