okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bcf88b738
main
1"""Typed, owner-editable local operation recipes for saved serving profiles. 2 3Recipes contain no executable command text. Each kind routes to an existing 4Strata operation. This is a source-run store; Desktop must later use the same 5schema and operation authority rather than add a separate implementation. 6""" 7 8from __future__import annotations 9 10from strata_control .private_files import private_mkdir as _private_mkdir 11import hashlib 12import json 13import os 14import re 15import shlex 16import stat 17import subprocess 18import sys 19import tempfile 20import uuid 21from pathlib import Path 22 23from strata_control import profiles 24from strata_control .profiles import ProfileError 25from strata_control import posix_owner 26 27 28KINDS = frozenset ({"runtime.restart" ,"engine.calibrate.measure" ,"components.verify" }) 29MAX_BYTES = 64 * 1024 30 31 32def _identity (profile :str ,name :str )-> tuple [str ,str ]: 33if not profiles .PROFILE_ID .fullmatch (profile )or not profiles .PROFILE_ID .fullmatch (name ): 34raise ProfileError ("recipe profile and name must use lowercase letters, digits, _ or -" ) 35return profile ,name 36 37 38def _directory (profile :str ,* ,create :bool = False )-> Path : 39profiles .load (profile ) 40base = profiles .profile_dir () 41directory = base / ".ops" / profile 42for path in (base ,directory .parent ): 43if not path .exists ()and not path .is_symlink (): 44continue 45details = path .lstat () 46if not stat .S_ISDIR (details .st_mode ): 47raise ProfileError ("recipe directory must not be a symlink" ,5 ) 48if os .name == "posix" and (posix_owner .owner_only_wrong (path ,details )): 49raise ProfileError (posix_owner .owner_only_text ("recipe directory must be owner-only (mode 0700)" ,path ),5 ) 50if create : 51_private_mkdir (directory .parent ,exist_ok = True ) 52_private_mkdir (directory ,exist_ok = True ) 53if directory .exists ()or directory .is_symlink (): 54details = directory .lstat () 55if not stat .S_ISDIR (details .st_mode ): 56raise ProfileError ("recipe directory must not be a symlink" ,5 ) 57if os .name == "posix" and (posix_owner .owner_only_wrong (directory ,details )): 58raise ProfileError (posix_owner .owner_only_text ("recipe directory must be owner-only (mode 0700)" ,directory ),5 ) 59return directory 60 61 62def _path (profile :str ,name :str ,* ,create :bool = False )-> Path : 63_identity (profile ,name ) 64return _directory (profile ,create = create )/ f" { name } .json" 65 66 67def _lock_name (profile :str )-> str : 68return "ops" + hashlib .sha256 (profile .encode ("utf-8" )).hexdigest ()[:24 ] 69 70 71def _history_dir (profile :str ,name :str ,* ,create :bool = False )-> Path : 72root = _path (profile ,name ).parent / ".history" 73directory = root / name 74for path in (root ,directory ): 75if path .is_symlink (): 76raise ProfileError ("recipe history directory must not be a symlink" ,5 ) 77if create : 78_private_mkdir (root ,exist_ok = True ) 79_private_mkdir (directory ,exist_ok = True ) 80for path in (root ,directory ): 81if path .exists (): 82details = path .lstat () 83if not stat .S_ISDIR (details .st_mode )or (os .name == "posix" and 84 (posix_owner .owner_only_wrong (path ,details ))): 85raise ProfileError (posix_owner .owner_only_text ("recipe history directory must be owner-only" ,path ),5 ) 86return directory 87 88 89def _bytes (recipe :dict )-> bytes : 90return (json .dumps (recipe ,sort_keys = True ,indent = 2 ,ensure_ascii = False ,allow_nan = False )+ "\n" ).encode ("utf-8" ) 91 92 93def _validate (recipe :object ,profile :str ,name :str )-> dict : 94if not isinstance (recipe ,dict )or set (recipe )!= {"schema_version" ,"profile" ,"id" ,"kind" ,"params" }: 95raise ProfileError ("recipe needs schema_version, profile, id, kind and params" ) 96if type (recipe ["schema_version" ])is not int or recipe ["schema_version" ]!= 1 : 97raise ProfileError ("unsupported recipe schema version" ) 98if recipe ["profile" ]!= profile or recipe ["id" ]!= name : 99raise ProfileError ("recipe profile or ID does not match its file" ) 100kind ,params = recipe ["kind" ],recipe ["params" ] 101if not isinstance (kind ,str )or kind not in KINDS or not isinstance (params ,dict ): 102raise ProfileError ("recipe kind or parameters are unsupported" ) 103if kind == "runtime.restart" : 104if set (params )!= {"startup_wait_s" }or type (params ["startup_wait_s" ])is not int or \ 105not 1 <= params ["startup_wait_s" ]<= 600 : 106raise ProfileError ("restart recipe needs startup_wait_s in 1..600" ) 107elif kind == "engine.calibrate.measure" : 108directory = params .get ("report_dir" ) 109if set (params )!= {"report_dir" }or not isinstance (directory ,str )or not directory or "\x00" in directory or \ 110not Path (directory ).is_absolute (): 111raise ProfileError ("calibration recipe needs an absolute report_dir" ) 112elif set (params )- {"live" }or ("live" in params and type (params ["live" ])is not bool ): 113raise ProfileError ("component verification recipe accepts only live=true|false" ) 114return recipe 115 116 117def _default (profile :str ,name :str ,kind :str )-> dict : 118if not isinstance (kind ,str )or kind not in KINDS : 119raise ProfileError ("recipe kind is unsupported" ) 120if kind == "runtime.restart" : 121params = {"startup_wait_s" :300 } 122elif kind == "engine.calibrate.measure" : 123params = {"report_dir" :str (profiles .profile_dir ().resolve ()/ ".reports" )} 124else : 125params = {} 126return _validate ({"schema_version" :1 ,"profile" :profile ,"id" :name , 127"kind" :kind ,"params" :params },profile ,name ) 128 129 130def create (profile :str ,name :str ,kind :str )-> tuple [dict ,str ]: 131profile ,name = _identity (profile ,name ) 132value = _default (profile ,name ,kind ) 133path = _path (profile ,name ,create = True ) 134with profiles ._lock (_lock_name (profile )): 135flags = os .O_WRONLY | os .O_CREAT | os .O_EXCL 136if hasattr (os ,"O_NOFOLLOW" ): 137flags |= os .O_NOFOLLOW 138try : 139descriptor = os .open (path ,flags ,0o600 ) 140except FileExistsError : 141raise ProfileError (f"recipe { name !r } already exists" )from None 142try : 143with os .fdopen (descriptor ,"wb" )as stream : 144stream .write (_bytes (value )) 145stream .flush () 146os .fsync (stream .fileno ()) 147except BaseException : 148path .unlink (missing_ok = True ) 149raise 150return load (profile ,name ) 151 152 153def initialize (profile :str )-> list [str ]: 154profiles .load (profile ) 155defaults = (("restart" ,"runtime.restart" ), 156 ("calibrate" ,"engine.calibrate.measure" ), 157 ("check" ,"components.verify" )) 158for name ,kind in defaults : 159path = _path (profile ,name ) 160if path .exists ()or path .is_symlink (): 161saved ,_ = load (profile ,name ) 162if saved ["kind" ]!= kind : 163raise ProfileError (f"recipe { name !r } exists with a different kind; choose another name" ) 164created = [] 165for name ,kind in defaults : 166path = _path (profile ,name ) 167if not path .exists ()and not path .is_symlink (): 168try : 169create (profile ,name ,kind ) 170created .append (name ) 171except ProfileError as exc : 172if "already exists" not in str (exc ): 173raise 174saved ,_ = load (profile ,name ) 175if saved ["kind" ]!= kind : 176raise ProfileError (f"recipe { name !r } exists with a different kind; choose another name" ) 177return created 178 179 180def load (profile :str ,name :str )-> tuple [dict ,str ]: 181path = _path (profile ,name ) 182try : 183details = path .lstat () 184if not stat .S_ISREG (details .st_mode )or details .st_size > MAX_BYTES : 185raise ProfileError ("recipe must be a regular file under 64 KiB" ,5 ) 186if os .name == "posix" and (posix_owner .owner_only_wrong (path ,details )): 187raise ProfileError (posix_owner .owner_only_text ("recipe file must be owner-only (mode 0600)" ,path ),5 ) 188data = path .read_bytes () 189value = json .loads (data .decode ("utf-8-sig" )) 190except FileNotFoundError : 191raise ProfileError (f"recipe { name !r } is missing; use strata ops init --profile { profile } " ,5 )from None 192except (OSError ,UnicodeError ,ValueError )as exc : 193if isinstance (exc ,ProfileError ): 194raise 195raise ProfileError (f"cannot read recipe ( { type ( exc ). __name__ } )" ,5 )from None 196return _validate (value ,profile ,name ),profiles ._revision (data ) 197 198 199def list_recipes (profile :str )-> list [dict ]: 200directory = _directory (profile ) 201if not directory .exists (): 202return [] 203items = [] 204for path in sorted (directory .glob ("*.json" )): 205if profiles .PROFILE_ID .fullmatch (path .stem ): 206try : 207recipe ,revision = load (profile ,path .stem ) 208items .append ({"id" :path .stem ,"kind" :recipe ["kind" ],"revision" :revision }) 209except ProfileError as exc : 210items .append ({"id" :path .stem ,"error" :str (exc )}) 211return items 212 213 214def save (profile :str ,name :str ,proposed :dict ,expected_revision :str )-> tuple [dict ,str ]: 215_validate (proposed ,profile ,name ) 216with profiles ._lock (_lock_name (profile )): 217current ,revision = load (profile ,name ) 218if revision != expected_revision : 219raise ProfileError ("recipe changed during edit; reload it before saving" ,6 ) 220if current == proposed : 221return current ,revision 222path = _path (profile ,name ) 223old = path .read_bytes () 224if profiles ._revision (old )!= revision : 225raise ProfileError ("recipe changed during edit; reload it before saving" ,6 ) 226history_dir = _history_dir (profile ,name ,create = True ) 227backup = history_dir / f" { revision } .json" 228if backup .exists ()or backup .is_symlink (): 229details = backup .lstat () 230if not stat .S_ISREG (details .st_mode )or (os .name == "posix" and 231 (posix_owner .owner_only_wrong (backup ,details )))or \ 232backup .read_bytes ()!= old : 233raise ProfileError ("recipe history conflicts with the saved revision" ,5 ) 234else : 235profiles ._atomic (backup ,old ) 236profiles ._atomic (path ,_bytes (proposed )) 237return load (profile ,name ) 238 239 240def history (profile :str ,name :str )-> list [dict ]: 241_ ,current = load (profile ,name ) 242directory = _history_dir (profile ,name ) 243entries = [] 244if directory .exists (): 245for path in directory .glob ("*.json" ): 246if re .fullmatch (r"[0-9a-f]{16}" ,path .stem )and path .is_file ()and not path .is_symlink (): 247entries .append ({"revision" :path .stem ,"saved_at" :path .stat ().st_mtime }) 248return [{"revision" :current ,"current" :True }, 249* sorted ((item for item in entries if item ["revision" ]!= current ), 250key = lambda item :item ["saved_at" ],reverse = True )] 251 252 253def rollback (profile :str ,name :str ,target_revision :str )-> tuple [dict ,str ,str ]: 254if not re .fullmatch (r"[0-9a-f]{16}" ,target_revision ): 255raise ProfileError ("rollback target must be a full 16-character revision" ) 256_ ,current_revision = load (profile ,name ) 257path = _history_dir (profile ,name )/ f" { target_revision } .json" 258try : 259details = path .lstat () 260if not stat .S_ISREG (details .st_mode )or details .st_size > MAX_BYTES : 261raise ProfileError ("recipe history must be a regular file under 64 KiB" ,5 ) 262if os .name == "posix" and (posix_owner .owner_only_wrong (path ,details )): 263raise ProfileError (posix_owner .owner_only_text ("recipe history file must be owner-only" ,path ),5 ) 264data = path .read_bytes () 265if profiles ._revision (data )!= target_revision : 266raise ProfileError ("recipe history content does not match its revision" ,5 ) 267proposed = _validate (json .loads (data .decode ("utf-8" )),profile ,name ) 268except FileNotFoundError : 269raise ProfileError (f"recipe revision { target_revision } was not found" ,5 )from None 270except (OSError ,UnicodeError ,ValueError )as exc : 271if isinstance (exc ,ProfileError ): 272raise 273raise ProfileError (f"cannot read recipe history ( { type ( exc ). __name__ } )" ,5 )from None 274saved ,new_revision = save (profile ,name ,proposed ,current_revision ) 275return saved ,current_revision ,new_revision 276 277 278def propose_value (profile :str ,name :str ,assignment :str )-> tuple [dict ,str ]: 279current ,revision = load (profile ,name ) 280key ,separator ,raw = assignment .partition ("=" ) 281if not separator or not raw : 282raise ProfileError ("expected a typed recipe parameter as KEY=VALUE" ) 283kind = current ["kind" ] 284if kind == "runtime.restart" and key == "startup_wait_s" : 285try : 286value :object = int (raw ) 287except ValueError : 288raise ProfileError ("startup_wait_s must be a whole number" )from None 289elif kind == "engine.calibrate.measure" and key == "report_dir" : 290value = raw 291elif kind == "components.verify" and key == "live" and raw in ("true" ,"false" ): 292value = raw == "true" 293else : 294raise ProfileError ("parameter is not supported by this recipe kind" ) 295proposed = {** current ,"params" : {** current ["params" ],key :value }} 296return _validate (proposed ,profile ,name ),revision 297 298 299def edit (profile :str ,name :str )-> tuple [dict ,str ,str ]: 300current ,revision = load (profile ,name ) 301editor = os .environ .get ("VISUAL" )or os .environ .get ("EDITOR" ) 302if not editor : 303raise ProfileError ("set VISUAL or EDITOR, or use strata ops set" ) 304command = shlex .split (editor ,posix = os .name != "nt" ) 305if not command : 306raise ProfileError ("VISUAL or EDITOR is empty" ) 307descriptor ,temporary = tempfile .mkstemp (prefix = f". { name } -edit-" ,suffix = ".json" ,dir = _directory (profile )) 308keep = False 309try : 310with os .fdopen (descriptor ,"wb" )as stream : 311stream .write (_bytes (current )) 312result = subprocess .run ([* command ,temporary ],check = False ) 313if result .returncode : 314keep = True 315raise ProfileError (f"editor exited with status { result . returncode } ; draft kept at { temporary } " ,6 ) 316try : 317proposed = json .loads (Path (temporary ).read_text (encoding = "utf-8-sig" )) 318saved ,new_revision = save (profile ,name ,proposed ,revision ) 319except (OSError ,ValueError )as exc : 320keep = True 321code = exc .exit_code if isinstance (exc ,ProfileError )else 2 322raise ProfileError (f"invalid recipe edit ( { exc } ); draft kept at { temporary } " ,code )from None 323return saved ,revision ,new_revision 324finally : 325if not keep : 326Path (temporary ).unlink (missing_ok = True ) 327 328 329def plan (profile :str ,name :str )-> dict : 330recipe ,revision = load (profile ,name ) 331kind = recipe ["kind" ] 332if kind == "runtime.restart" : 333from strata_control import runtime 334preflight = runtime .plan_restart (profile ) 335profile_revision = preflight .get ("candidate_profile_revision" ) 336operation = {"ok" :preflight ["ok" ],"exit_code" :preflight .get ("exit_code" ,6 ), 337"preflight" :preflight ,"startup_wait_s" :recipe ["params" ]["startup_wait_s" ], 338"run_effects" : {"drain_current_instance" :True ,"start_new_instance" :True , 339"rollback_previous_launch_on_activation_failure" :True }} 340elif kind == "engine.calibrate.measure" : 341from strata_control import calibration 342preflight = calibration .preview (profile ) 343profile_revision = preflight ["profile_revision" ] 344operation = {"ok" :preflight ["component_preflight" ]["ok" ],"exit_code" :5 , 345"preflight" :preflight ,"report_dir" :recipe ["params" ]["report_dir" ], 346"run_effects" : {"start_engine_for_decode_sweep" :True ,"write_new_report" :True , 347"change_run_config" :False ,"requires_exclusive_acknowledgement" :True }} 348else : 349from strata_control .doctor import inspect as inspect_components 350path ,_ ,_ = profiles .resolve (profile ) 351live = recipe ["params" ].get ("live" ,False ) 352report = inspect_components (path ,profile_id = profile ,live = live ) 353profile_revision = profiles .load (profile )[1 ] 354operation = {"ok" :report ["ok" ],"exit_code" :5 ,"preflight" :report , 355"run_effects" : {"read_components" :True ,"query_host_gpus" :live ,"write_files" :False }} 356if profile_revision is not None and profile_revision != profiles .load (profile )[1 ]: 357raise ProfileError ("profile changed during recipe preview; retry" ,6 ) 358return {"profile" :profile ,"profile_revision" :profile_revision , 359"recipe" :name ,"recipe_revision" :revision , 360"kind" :kind ,"operation" :operation ,"would_execute" :False } 361 362 363def run (profile :str ,name :str ,* ,exclusive_ack :bool = False , 364expected_revision :str | None = None , 365expected_profile_revision :str | None = None , 366expected_owner_id :str | None = None , 367expected_instance_id :str | None = None , 368expected_source_sha256 :str | None = None )-> dict : 369recipe ,revision = load (profile ,name ) 370if expected_revision is not None and revision != expected_revision : 371raise ProfileError ("recipe changed after preview; plan it again before running" ,6 ) 372if expected_profile_revision is not None and profiles .load (profile )[1 ]!= expected_profile_revision : 373raise ProfileError ("profile changed after preview; plan it again before running" ,6 ) 374kind = recipe ["kind" ] 375if kind == "runtime.restart" : 376from strata_control import runtime 377if (expected_owner_id is None )!= (expected_instance_id is None ): 378raise ProfileError ("restart recipe needs both reviewed owner and instance IDs" ) 379if any (value is not None for value in (expected_owner_id ,expected_instance_id , 380expected_source_sha256 )): 381preflight = runtime .plan_restart (profile ) 382if not preflight ["ok" ]: 383raise ProfileError (preflight .get ("error" ,"restart preflight failed" ), 384preflight .get ("exit_code" ,6 )) 385if expected_owner_id is not None and preflight ["current_owner_id" ]!= expected_owner_id : 386raise ProfileError ("owner_changed_after_restart_plan" ,6 ) 387if expected_instance_id is not None and preflight ["current_instance_id" ]!= expected_instance_id : 388raise ProfileError ("instance_changed_after_restart_plan" ,6 ) 389if (expected_source_sha256 is not None and 390preflight ["candidate_source_sha256" ]!= expected_source_sha256 ): 391raise ProfileError ("source_changed_after_preview" ,6 ) 392elif any (value is not None for value in (expected_owner_id ,expected_instance_id , 393expected_source_sha256 )): 394raise ProfileError ("owner, instance and source preconditions require a restart recipe" ) 395if kind == "engine.calibrate.measure" and not exclusive_ack : 396raise ProfileError ("calibration recipe requires --exclusive for each run" ) 397from strata_control import journal 398profile_revision = profiles .load (profile )[1 ] 399record = journal .begin (profile ,name ,kind ,revision ,profile_revision , 400intent = dict (recipe ["params" ])) 401try : 402if kind == "runtime.restart" : 403from strata_control import runtime 404kwargs = {"startup_wait" :recipe ["params" ]["startup_wait_s" ]} 405if expected_profile_revision is not None : 406kwargs ["expected_profile_revision" ]= expected_profile_revision 407if expected_owner_id is not None : 408kwargs ["expected_owner_id" ]= expected_owner_id 409kwargs ["expected_instance_id" ]= expected_instance_id 410if expected_source_sha256 is not None : 411kwargs ["expected_source_sha256" ]= expected_source_sha256 412result = runtime .restart (profile ,** kwargs ) 413elif kind == "engine.calibrate.measure" : 414from strata_control import calibration 415directory = Path (recipe ["params" ]["report_dir" ]) 416_private_mkdir (directory ,exist_ok = True ) 417if not stat .S_ISDIR (directory .lstat ().st_mode ): 418raise ProfileError ("report_dir must be a directory, not a symlink" ,5 ) 419report_path = directory / f"calibration- { uuid . uuid4 (). hex } .json" 420report = calibration .measure (profile ,report_path ,exclusive_ack = True , 421say = lambda message :message ,file = sys .stderr )) 422result = {"ok" :True ,"report_path" :str (report_path ),"report" :report , 423"requires_review_before_apply" :True } 424else : 425from strata_control .doctor import inspect as inspect_components 426path ,_ ,_ = profiles .resolve (profile ) 427report = inspect_components (path ,profile_id = profile ,live = recipe ["params" ].get ("live" ,False )) 428result = {"ok" :report ["ok" ],"report" :report } 429except BaseException as exc : 430unknown = isinstance (exc , (KeyboardInterrupt ,SystemExit ))or \ 431 (isinstance (exc ,ProfileError )and exc .exit_code == 8 ) 432journal .finish (profile ,record ["operation_id" ],"completion_unknown" if unknown else "failed" , 433 {"error_type" :type (exc ).__name__ , 434"exit_code" :exc .exit_code if isinstance (exc ,ProfileError )else 130 if unknown else 6 }) 435raise 436journal .finish (profile ,record ["operation_id" ],"succeeded" if result ["ok" ]else "failed" , 437journal .compact_result (kind ,result )) 438return {"profile" :profile ,"recipe" :name ,"recipe_revision" :revision , 439"kind" :kind ,"operation_id" :record ["operation_id" ],"result" :result }