File size: 1,721 Bytes
39cb716 | 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 | """Small runtime helpers for the isolated M2RL execution directory."""
from __future__ import annotations
import hashlib
import json
import os
import re
import tempfile
from pathlib import Path
def require_allocation():
job = os.environ.get('SLURM_JOB_ID', '')
cgroup = Path('/proc/self/cgroup').read_text()
if not job.isdigit() or not re.search(r'(?:/|^)job_' + job + r'(?:/|$)', cgroup):
raise RuntimeError('M2RL sustained work requires a real Slurm cgroup')
if not os.environ.get('SLURM_CPUS_PER_TASK') or not os.environ.get('SLURM_MEM_PER_NODE'):
raise RuntimeError('Explicit CPU and memory allocation required')
return {'job_id': job, 'cgroup': cgroup.strip(),
'cpus': os.environ['SLURM_CPUS_PER_TASK'],
'memory_mb': os.environ['SLURM_MEM_PER_NODE']}
def sha256(path):
digest = hashlib.sha256()
with open(path, 'rb') as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(chunk)
return digest.hexdigest()
def atomic_json(path, value):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix=path.name + '.', dir=path.parent)
try:
with os.fdopen(fd, 'w') as stream:
json.dump(value, stream, indent=2, ensure_ascii=False, allow_nan=False)
stream.write('\n')
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
directory = os.open(path.parent, os.O_DIRECTORY)
try:
os.fsync(directory)
finally:
os.close(directory)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
|