GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — FrontierCS-2/scripts/deploy/cli.py at main · FrontierCS/FrontierCS-2 Expand file tree/ Copy pathcli.pyMore file actions 1577 lines (1528 loc) · 60.5 KB / Copy pathcli.pyFile metadata and controls1577 lines (1528 loc) · 60.5 KB 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 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 """Guarded fresh-account installer for the executable FrontierCS2 Preview profile. The site file is deliberately non-secret. AWS CLI, Terraform, Docker, and kubectl receive credentials through their ordinary local credential chains. """ from __future__ import annotations import argparse import base64 import ipaddress import json import os import re import shutil import subprocess import sys from pathlib import Path from typing import Any, Mapping, Sequence from task_selection import TaskSelection, requirements from task_selection import select_tasks as select_tasks from .acceptance import ( run_gpu_smoke, run_smoke, runtime_admission_preflight, verify_runtime, ) from .api_routes import ( api_policy_patch, verify_api_route_reader_rbac, verify_api_routes, ) from .config import ( CPU_MACHINE_ENV, cpu_machine_management_env, read_and_validate, render_bundle, state_directory, validate_verifier_node_allowlists, validate_verifier_placement_required_task_ids, ) from .gateway_preservation import read_gateway_snapshot from .images import ( build_runtime_images, cached_registry_image, load_runtime_images, source_tree_sha256, ) from .infra import ( DIGEST_RE, MANAGEMENT_SERVICE, PLATFORM_NAMESPACE, REGISTRY_SERVICE, REPOSITORY_ROOT, TASK_CATALOG_PATH, DeployError, api_cidrs, api_json, atomic_write, aws_identity, canonical_json, canonical_object_sha256, command_environment, dataset_seed_names, deploy_bootstrap, deploy_litellm, ensure_admission_control_maps, executable, gateway_artifact_retention_init, kubectl_apply, kubernetes_environment, load_json, management_api_routes_rbac, management_diagnostic_source_mount, management_diagnostics_rbac, management_result_resources, modal_observer_rbac, platform_labels, platform_outputs, port_forward, render_runtime_manifest, run_command, runtime_source_commit, state_bucket_exists, terraform_apply_plan, terraform_init_and_validate, terraform_plan, update_kubeconfig, validate_api_cidrs, ) from .publication import ( load_task_selection, seed_tasks, ) from .runtime_reference_compat import ( preserve_reviewed_public_images, require_reviewed_route_only_patches, reviewed_retention_transition, ) from .unchanged_management import ( require_driver_only_patches, require_unchanged_observer, unchanged_native_management, ) def modal_credentials( config: Mapping[str, Any], selection: TaskSelection | None = None ) -> dict[str, str]: if selection is None: _, selection = load_task_selection(config) if not any( requirements(definition)["modal_gpu"] for definition in selection.definitions.values() ): return {} data = {} for variable, key in ( ("MODAL_TOKEN_ID", "token-id"), ("MODAL_TOKEN_SECRET", "token-secret"), ): value = os.environ.get(variable, "").strip() if not value or "\n" in value or "\r" in value: raise DeployError( f"GPU Preview requires {variable} in the operator environment" ) data[key] = base64.b64encode(value.encode()).decode() return data def deploy_modal_credentials(config: Mapping[str, Any], kubeconfig: Path) -> None: data = modal_credentials(config) if not data: return name = config["modal"]["credentials_secret"] command = [executable("kubectl"), "-n", PLATFORM_NAMESPACE] environment = command_environment(kubernetes_environment(kubeconfig)) # Capture and suppress API error bodies: they may echo a submitted Secret. existing = subprocess.run( command + ["get", "secret", name, "--ignore-not-found", "-o", "json"], env=environment, capture_output=True, text=True, timeout=60, check=False, ) if existing.returncode: raise DeployError("Could not inspect the named platform Modal Secret") if existing.stdout.strip(): if json.loads(existing.stdout).get("data") != data: raise DeployError( "Platform Modal Secret differs; rotate credentials after active Runs finish" ) return document = { "apiVersion": "v1", "kind": "Secret", "type": "Opaque", "metadata": { "name": name, "namespace": PLATFORM_NAMESPACE, "labels": platform_labels(config, "frontier-modal-credentials"), }, "data": data, } created = subprocess.run( command + ["create", "-f", "-"], env=environment, input=canonical_json(document), capture_output=True, timeout=60, check=False, ) if created.returncode: raise DeployError("Could not create the named platform Modal Secret") readback = subprocess.run( command + ["get", "secret", name, "-o", "json"], env=environment, capture_output=True, text=True, timeout=60, check=False, ) if readback.returncode or json.loads(readback.stdout).get("data") != data: raise DeployError("Platform Modal Secret readback failed") def require_idle_runtime(base: str) -> None: # Filter server-side so a paginated history cannot hide a live Run. for state in ("QUEUED", "STARTING", "RUNNING", "FINALIZING"): rows = api_json(base, "GET", f"/api/v1/runs?state={state}&limit=1") if not isinstance(rows, list) or rows: raise DeployError(f"runtime upgrade requires zero {state} Runs") # runtime_upgrade_patches(cpu_machines=KEEP): leave the CPU machine settings as they are. KEEP = object() def runtime_upgrade_patches( configmap: Mapping[str, Any], deployment: Mapping[str, Any], images: Mapping[str, Any], *, litellm_cidr: str | None = None, gateway_artifact_retention: bool = False, kubernetes_api_cidrs: Sequence[str] | None = None, cluster_name: str | None = None, region: str | None = None, large_verifier_results: bool = False, verifier_node_allowlists: list | None = None, verifier_placement_required_task_ids: list | None = None, cpu_machines: Mapping[str, Any] | None | object = KEEP, reviewed_public_repair: bool = False, ) -> tuple[list, list, dict]: """Update immutable runtime pins and the optional Preview gateway wiring.""" data = dict(configmap["data"]) if data.get("MANAGEMENT_DRIVER_BACKENDS") != "local-k8s": raise DeployError( "runtime upgrade requires the existing local-k8s Preview profile" ) containers = deployment["spec"]["template"]["spec"]["containers"] indices = [i for i, c in enumerate(containers) if c["name"] == "management"] if len(indices) != 1: raise DeployError("runtime upgrade requires one Management container") data["MANAGEMENT_DRIVER_IMAGE"] = images["driver"]["reference"] cm_patch = [ { "op": "test", "path": "/metadata/resourceVersion", "value": configmap["metadata"]["resourceVersion"], }, { "op": "replace", "path": "/data/MANAGEMENT_DRIVER_IMAGE", "value": data["MANAGEMENT_DRIVER_IMAGE"], }, ] if verifier_node_allowlists is not None: validate_verifier_node_allowlists(verifier_node_allowlists) key = "MANAGEMENT_VERIFIER_NODE_ALLOWLISTS" if any( entry.get("name") == key for entry in containers[indices[0]].get("env", []) ): raise DeployError("verifier placement rejects direct environment overrides") if verifier_node_allowlists: value = json.dumps( verifier_node_allowlists, sort_keys=True, separators=(",", ":") ) data[key] = value cm_patch.append({"op": "add", "path": "/data/" + key, "value": value}) elif key in data: del data[key] cm_patch.append({"op": "remove", "path": "/data/" + key}) if verifier_placement_required_task_ids is not None: validate_verifier_placement_required_task_ids( verifier_placement_required_task_ids ) key = "MANAGEMENT_VERIFIER_PLACEMENT_REQUIRED_TASK_IDS" if any( entry.get("name") == key for entry in containers[indices[0]].get("env", []) ): raise DeployError( "required verifier placement rejects direct environment overrides" ) if verifier_placement_required_task_ids: value = json.dumps( sorted(verifier_placement_required_task_ids), separators=(",", ":") ) data[key] = value cm_patch.append({"op": "add", "path": "/data/" + key, "value": value}) elif key in data: del data[key] cm_patch.append({"op": "remove", "path": "/data/" + key}) if cpu_machines is not KEEP: # The site's execution.cpu_machines, or None when it has none: absent means the keys # are absent, never a default. if any( entry.get("name") in CPU_MACHINE_ENV for entry in containers[indices[0]].get("env", []) ): raise DeployError( "CPU machine settings reject direct environment overrides" ) wanted = ( {} if cpu_machines is None else cpu_machine_management_env(cpu_machines) ) for key in CPU_MACHINE_ENV: if key in wanted: cm_patch.append( { "op": "replace" if key in data else "add", "path": "/data/" + key, "value": wanted[key], } ) data[key] = wanted[key] elif key in data: del data[key] cm_patch.append({"op": "remove", "path": "/data/" + key}) if cluster_name is not None or region is not None: if ( not isinstance(cluster_name, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,99}", cluster_name) or not isinstance(region, str) or not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-[0-9]", region) or data.get("MANAGEMENT_DRIVER_MODE") != "kubernetes" ): raise DeployError( "Infrastructure observation requires a cluster, region and kubernetes mode" ) settings = { "MANAGEMENT_EKS_STATUS_CLUSTER": cluster_name, "MANAGEMENT_EKS_STATUS_REGION": region, } legacy = ( "MANAGEMENT_EKS_STATUS_PATH", "MANAGEMENT_EKS_STATUS_NODEGROUPS", "MANAGEMENT_EKS_STATUS_MAX_AGE_SECONDS", ) if any( entry.get("name") in {*settings, *legacy} for entry in containers[indices[0]].get("env", []) ): raise DeployError( "Infrastructure observation rejects direct environment overrides" ) for key in legacy: if key in data: del data[key] cm_patch.append({"op": "remove", "path": "/data/" + key}) for key, value in settings.items(): data[key] = value cm_patch.append({"op": "add", "path": "/data/" + key, "value": value}) if kubernetes_api_cidrs is not None: data["MANAGEMENT_KUBERNETES_API_CIDRS"] = ",".join( sorted(validate_api_cidrs(kubernetes_api_cidrs)) ) cm_patch.append( { "op": "add", "path": "/data/MANAGEMENT_KUBERNETES_API_CIDRS", "value": data["MANAGEMENT_KUBERNETES_API_CIDRS"], } ) if litellm_cidr is not None: network = ipaddress.ip_network(litellm_cidr, strict=True) if ( network.version != 4 or network.prefixlen != 32 or not network.network_address.is_private ): raise DeployError("LiteLLM destination must be one private IPv4 /32") data["MANAGEMENT_LITELLM_SERVICE_CIDR"] = litellm_cidr if "MANAGEMENT_LITELLM_SERVICE_CIDR" in data: data["MANAGEMENT_LITELLM_KEY_WORKER_IMAGE"] = images["management"]["reference"] for key in ( "MANAGEMENT_LITELLM_SERVICE_CIDR", "MANAGEMENT_LITELLM_KEY_WORKER_IMAGE", ): cm_patch.append({"op": "add", "path": "/data/" + key, "value": data[key]}) retention_init = None if gateway_artifact_retention: pod = deployment["spec"]["template"]["spec"] management = containers[indices[0]] volumes = {v["name"]: v for v in pod.get("volumes", [])} mounts = { v["name"]: v for v in management.get("volumeMounts", []) if v.get("mountPath") in ("/var/lib/frontier", "/var/lib/frontier-local") } if ( volumes.get("data", {}).get("persistentVolumeClaim", {}).get("claimName") != "frontier-management-data" or mounts.get("data", {}).get("mountPath") != "/var/lib/frontier" or mounts.get("data", {}).get("readOnly", False) or mounts.get("objects", {}).get("mountPath") != "/var/lib/frontier-local" or mounts.get("objects", {}).get("readOnly") is not True or volumes.get("objects", {}) .get("persistentVolumeClaim", {}) .get("claimName") in (None, "frontier-management-data") ): raise DeployError( "gateway retention requires distinct Management data and read-only object mounts" ) security = pod.get("securityContext", {}) if ( security.get("runAsUser") != 65532 or security.get("runAsGroup") != 65532 or security.get("fsGroup") != 65532 ): raise DeployError( "gateway retention requires the existing Management UID/GID65532" ) settings = { "MANAGEMENT_GATEWAY_ARTIFACT_SOURCE_ROOT": "/var/lib/frontier-local/artifacts", "MANAGEMENT_GATEWAY_ARTIFACT_RETAINED_ROOT": "/var/lib/frontier/gateway-terminal-retained", } if any(entry.get("name") in settings for entry in management.get("env", [])): raise DeployError("gateway retention rejects direct environment overrides") for key, value in settings.items(): if key in data and data[key] != value: raise DeployError("gateway retention existing root differs") data[key] = value cm_patch.append({"op": "add", "path": "/data/" + key, "value": value}) expected_old = gateway_artifact_retention_init(management["image"]) retention_init = [] observed = 0 for existing in pod.get("initContainers", []): if existing.get("name") == expected_old["name"]: observed += 1 normalized = dict(existing) # Kubernetes defaults these fields on readback; the initializer # has no termination-message override or output contract. for key, value in ( ("terminationMessagePath", "/dev/termination-log"), ("terminationMessagePolicy", "File"), ): if normalized.get(key) == value: normalized.pop(key) compatible = reviewed_public_repair and reviewed_retention_transition( normalized, expected_old, images["management"]["reference"] ) if observed > 1 or (normalized != expected_old and not compatible): raise DeployError("gateway retention existing init differs") retention_init.append( gateway_artifact_retention_init(images["management"]["reference"]) ) else: retention_init.append(existing) if not observed: retention_init.append( gateway_artifact_retention_init(images["management"]["reference"]) ) annotations = dict( deployment["spec"]["template"]["metadata"].get("annotations", {}) ) annotations["frontier.dev/config-sha256"] = canonical_object_sha256(data) deploy_patch = [ { "op": "test", "path": "/metadata/resourceVersion", "value": deployment["metadata"]["resourceVersion"], }, { "op": "replace", "path": f"/spec/template/spec/containers/{indices[0]}/image", "value": images["management"]["reference"], }, { "op": "add", "path": "/spec/template/metadata/annotations", "value": annotations, }, ] if large_verifier_results: pod = deployment["spec"]["template"]["spec"] temporary = [ (index, volume) for index, volume in enumerate(pod.get("volumes", [])) if volume.get("name") == "tmp" ] mounts = [ mount for mount in containers[indices[0]].get("volumeMounts", []) if mount.get("name") == "tmp" ] if ( len(temporary) != 1 or len(mounts) != 1 or mounts[0].get("mountPath") != "/tmp" or mounts[0].get("readOnly", False) or "emptyDir" not in temporary[0][1] or temporary[0][1]["emptyDir"].get("medium", "") != "" ): raise DeployError( "large verifier results require one disk-backed Management /tmp" ) temporary_index, _ = temporary[0] deploy_patch[-1:-1] = [ { "op": "add", "path": f"/spec/template/spec/containers/{indices[0]}/resources", "value": management_result_resources(), }, { "op": "add", "path": f"/spec/template/spec/volumes/{temporary_index}/emptyDir/sizeLimit", "value": management_result_resources()["limits"]["ephemeral-storage"], }, ] if retention_init is not None: deploy_patch.insert( -1, { "op": "add", "path": "/spec/template/spec/initContainers", "value": retention_init, }, ) volume, mount = management_diagnostic_source_mount( volumes["objects"]["persistentVolumeClaim"]["claimName"] ) # Kubelet tracks one CSI volume per PVC; both paths must share its name. legacy_volume = {**volume, "name": "diagnostic-source"} legacy_mount = {**mount, "name": "diagnostic-source"} aliases = [v for v in pod["volumes"] if v["name"] == "diagnostic-source"] if aliases and aliases != [legacy_volume]: raise DeployError("diagnostic source existing mount or volume differs") expected_claim = volume["persistentVolumeClaim"]["claimName"] for existing in pod["volumes"]: if ( existing["name"] not in ("objects", "diagnostic-source") and existing.get("persistentVolumeClaim", {}).get("claimName") == expected_claim ): raise DeployError( "diagnostic source has an unexpected duplicate PVC alias" ) for container in [*pod["containers"], *pod.get("initContainers", [])]: for existing in container.get("volumeMounts", []): if existing["name"] == "diagnostic-source" and ( container is not management or existing != legacy_mount ): raise DeployError( "diagnostic source legacy alias has another consumer" ) if existing["name"] == "objects" and not existing.get( "readOnly", False ): if container is not management or existing != mount: raise DeployError( "diagnostic source would make another object mount writable" ) artifact_mounts = [ m for m in management["volumeMounts"] if m.get("mountPath") == mount["mountPath"] ] if artifact_mounts not in ([], [mount], [legacy_mount]): raise DeployError( "diagnostic source mount path already occupied or differs" ) new_volumes = [ volume if v["name"] == "objects" else v for v in pod["volumes"] if v["name"] != "diagnostic-source" ] new_mounts = [ mount if m.get("mountPath") == mount["mountPath"] else m for m in management["volumeMounts"] ] if not artifact_mounts: new_mounts.append(mount) for path, value in ( ("/spec/template/spec/volumes", new_volumes), ( f"/spec/template/spec/containers/{indices[0]}/volumeMounts", new_mounts, ), ): deploy_patch.insert( -1, {"op": "add", "path": path, "value": value}, ) if reviewed_public_repair: require_reviewed_route_only_patches(configmap, deployment, data, deploy_patch) return cm_patch, deploy_patch, data def modal_observer_upgrade_manifest( config: Mapping[str, Any], configmap: Mapping[str, Any], deployment: Mapping[str, Any], ) -> bytes | None: items = modal_observer_rbac(config) if not items: return None data = configmap["data"] pod = deployment["spec"]["template"]["spec"] if ( data.get("MANAGEMENT_NAMESPACE") != PLATFORM_NAMESPACE or data.get("MANAGEMENT_MODAL_CREDENTIALS_SECRET") != config["modal"]["credentials_secret"] or pod.get("serviceAccountName") != "frontier-management" ): raise DeployError( "Modal observer existing namespace, Secret or ServiceAccount differs from site configuration" ) return canonical_json({"apiVersion": "v1", "kind": "List", "items": items}) def infrastructure_role_patch(role: Mapping[str, Any]) -> tuple[list, list]: """Preserve existing authority while adding read-only node observation.""" rules = list(role["rules"]) rule = {"apiGroups": [""], "resources": ["nodes"], "verbs": ["get", "list"]} if rule not in rules: rules.append(rule) return [ {"op": "test", "path": "/metadata/uid", "value": role["metadata"]["uid"]}, { "op": "test", "path": "/metadata/resourceVersion", "value": role["metadata"]["resourceVersion"], }, {"op": "replace", "path": "/rules", "value": rules}, ], rules def upgrade_runtime(config: Mapping[str, Any], output: Path, kubeconfig: Path) -> None: """Upgrade an idle deployed site without re-running bootstrap or seeding.""" load_task_selection(config, require_resolved=True) gateway_before = read_gateway_snapshot(kubeconfig) images = load_runtime_images(config) copy_tool = executable(os.environ.get("FRONTIER_REGISTRY_COPY_TOOL", "crane")) environment = kubernetes_environment(kubeconfig) kubectl = [executable("kubectl"), "-n", PLATFORM_NAMESPACE] def get(kind: str, name: str) -> dict: return json.loads( run_command( kubectl + ["get", kind, name, "-o", "json"], environment=environment, capture=True, timeout=60, ) ) with port_forward(kubeconfig, MANAGEMENT_SERVICE, 8080) as port: require_idle_runtime(f"http://127.0.0.1:{port}") cm = get("configmap", "frontier-management-config") deployment = get("deployment", "frontier-management") unchanged_management = unchanged_native_management(config, cm, deployment, images) reviewed_public_repair = ( False if unchanged_management else preserve_reviewed_public_images(config, cm, deployment, images) ) if not reviewed_public_repair: with port_forward(kubeconfig, REGISTRY_SERVICE, 5000) as port: if unchanged_management: if ( cached_registry_image( port, unchanged_management, images["management"]["digest"] ) != images["management"]["digest"] ): raise DeployError( "unchanged Management manifest is unavailable or differs" ) for name in ( ("driver",) if unchanged_management else ("management", "driver") ): source = config["images"][name] repository = f"frontier/{name}" tag = "git-" + runtime_source_commit(config, name)[:20] if cached_registry_image(port, repository, source["digest"]) is None: run_command( [ copy_tool, "copy", "--platform", "linux/amd64", "--jobs", "2", source["reference"], f"127.0.0.1:{port}/{repository}:{tag}", ], timeout=1800, ) if ( cached_registry_image(port, repository, source["digest"]) != source["digest"] ): raise DeployError( "runtime mirror did not preserve the source manifest" ) endpoint = ( f"{config['network']['registry_cluster_ip']}:5000/{repository}" ) images[name] = { "tag": endpoint + ":" + tag, "digest": source["digest"], "reference": endpoint + "@" + source["digest"], "source_sha256": source["digest"], } receipt_dir = output / ("runtime-upgrade-" + config["application"]["commit"][:12]) receipt_dir.mkdir(parents=True, exist_ok=True) os.chmod(receipt_dir, 0o700) outputs = platform_outputs(config) cidrs = api_cidrs( config, outputs, kubeconfig, receipt_path=receipt_dir / "api-routes.json" ) role = get("clusterrole", "frontier-management-preview") role_patch, expected_rules = infrastructure_role_patch(role) observer_manifest = modal_observer_upgrade_manifest(config, cm, deployment) if ( deployment["spec"]["template"]["spec"].get("serviceAccountName") != "frontier-management" ): raise DeployError("diagnostics upgrade requires the Management ServiceAccount") cm_patch, deploy_patch, expected_data = runtime_upgrade_patches( cm, deployment, images, litellm_cidr=config["network"]["litellm_cluster_ip"] + "/32", gateway_artifact_retention=True, kubernetes_api_cidrs=cidrs, cluster_name=outputs["cluster_name"], region=config["site"]["aws_region"], large_verifier_results=True, verifier_node_allowlists=config["execution"].get( "verifier_node_allowlists", [] ), verifier_placement_required_task_ids=config["execution"].get( "verifier_placement_required_task_ids", [] ), cpu_machines=config["execution"].get("cpu_machines"), reviewed_public_repair=reviewed_public_repair, ) preserved_observer = [] if unchanged_management: require_driver_only_patches(cm, deployment, expected_data, deploy_patch) if expected_rules != role["rules"]: raise DeployError( "unchanged Management upgrade has extra infrastructure changes" ) if observer_manifest is not None: for expected in json.loads(observer_manifest)["items"]: live = get(expected["kind"], expected["metadata"]["name"]) require_unchanged_observer(expected, live) preserved_observer.append((expected, live)) observer_manifest = None # Already exact: leave these resources untouched. atomic_write( receipt_dir / "gateway-before.json", canonical_json(gateway_before), mode=0o600 ) diagnostics_path = receipt_dir / "management-diagnostics-rbac.json" atomic_write( diagnostics_path, canonical_json( { "apiVersion": "v1", "kind": "List", "items": management_diagnostics_rbac(config), } ), mode=0o600, ) diagnostics_command = kubectl + [ "apply", "--server-side", "--field-manager=frontier-deploy", "-f", str(diagnostics_path), ] run_command( diagnostics_command + ["--dry-run=server"], environment=environment, timeout=60 ) api_rbac_path = receipt_dir / "management-api-routes-rbac.json" atomic_write( api_rbac_path, canonical_json( {"apiVersion": "v1", "kind": "List", "items": management_api_routes_rbac()} ), mode=0o600, ) api_rbac_command = [ executable("kubectl"), "apply", "--server-side", "--field-manager=frontier-deploy", "-f", str(api_rbac_path), ] run_command( api_rbac_command + ["--dry-run=server"], environment=environment, timeout=60 ) observer_command = None if observer_manifest is not None: observer_path = receipt_dir / "modal-observer-rbac.json" atomic_write(observer_path, observer_manifest, mode=0o600) observer_command = kubectl + [ "apply", "--server-side", "--field-manager=frontier-deploy", "-f", str(observer_path), ] run_command( observer_command + ["--dry-run=server"], environment=environment, timeout=60 ) for name, body in ( ("configmap-before", cm), ("deployment-before", deployment), ("configmap-patch", cm_patch), ("deployment-patch", deploy_patch), ("clusterrole-before", role), ("clusterrole-patch", role_patch), ): atomic_write(receipt_dir / (name + ".json"), canonical_json(body), mode=0o600) commands = [] policy_specs = {} old_cidrs = cm["data"].get("MANAGEMENT_KUBERNETES_API_CIDRS", "").split(",") for name in ( "frontier-management-boundary", "frontier-storage-controller-boundary", ): before = get("networkpolicy", name) patch, policy_specs[name] = api_policy_patch(before, cidrs, old_cidrs) atomic_write( receipt_dir / (name + "-before.json"), canonical_json(before), mode=0o600 ) path = receipt_dir / (name + "-patch.json") atomic_write(path, canonical_json(patch), mode=0o600) command = kubectl + [ "patch", "networkpolicy", name, "--type=json", "--patch-file", str(path), ] run_command(command + ["--dry-run=server"], environment=environment, timeout=60) commands.append(command) for kind, name in ( ("clusterrole", "frontier-management-preview"), ("configmap", "frontier-management-config"), ("deployment", "frontier-management"), ): command = kubectl + [ "patch", kind, name, "--type=json", "--patch-file", str(receipt_dir / (kind + "-patch.json")), ] run_command(command + ["--dry-run=server"], environment=environment, timeout=60) commands.append(command) with port_forward(kubeconfig, MANAGEMENT_SERVICE, 8080) as port: require_idle_runtime(f"http://127.0.0.1:{port}") if read_gateway_snapshot(kubeconfig) != gateway_before: raise DeployError("LiteLLM gateway changed before runtime upgrade") if api_cidrs(config, outputs, kubeconfig) != cidrs: raise DeployError( "Kubernetes API destinations changed before upgrade; no patches applied" ) for expected, before in preserved_observer: if get(expected["kind"], expected["metadata"]["name"]) != before: raise DeployError( "unchanged Management Modal observer changed before upgrade" ) if observer_command is not None: run_command(observer_command, environment=environment, timeout=60) run_command(diagnostics_command, environment=environment, timeout=60) run_command(api_rbac_command, environment=environment, timeout=60) verify_api_route_reader_rbac(kubeconfig) for command in commands: run_command(command, environment=environment, timeout=60) run_command( kubectl + ["rollout", "status", "deployment/frontier-management", "--timeout=10m"], environment=environment, timeout=660, ) after_role = get("clusterrole", "frontier-management-preview") if ( after_role["metadata"]["uid"] != role["metadata"]["uid"] or after_role["rules"] != expected_rules ): raise DeployError( "Infrastructure observation role changed during runtime upgrade" ) for name, expected in policy_specs.items(): if get("networkpolicy", name)["spec"] != expected: raise DeployError( "Kubernetes API policy readback differs from reviewed patch" ) verify_api_routes(config, outputs, kubeconfig) after_cm = get("configmap", "frontier-management-config") after_deployment = get("deployment", "frontier-management") if after_cm["data"] != expected_data: raise DeployError("Management ConfigMap changed during runtime upgrade") expected_spec = json.loads(json.dumps(deployment["spec"])) i = next( i for i, c in enumerate(expected_spec["template"]["spec"]["containers"]) if c["name"] == "management" ) expected_spec["template"]["spec"]["containers"][i]["image"] = images["management"][ "reference" ] for patch in deploy_patch: if patch["path"] == "/spec/template/spec/initContainers": expected_spec["template"]["spec"]["initContainers"] = patch["value"] elif patch["path"] == "/spec/template/spec/volumes": expected_spec["template"]["spec"]["volumes"] = patch["value"] elif patch["path"] == f"/spec/template/spec/containers/{i}/volumeMounts": expected_spec["template"]["spec"]["containers"][i]["volumeMounts"] = patch[ "value" ] elif patch["path"] == f"/spec/template/spec/containers/{i}/resources": expected_spec["template"]["spec"]["containers"][i]["resources"] = patch[ "value" ] elif patch["path"].startswith("/spec/template/spec/volumes/") and patch[ "path" ].endswith("/emptyDir/sizeLimit"): volume_index = int(patch["path"].split("/")[5]) expected_spec["template"]["spec"]["volumes"][volume_index]["emptyDir"][ "sizeLimit" ] = patch["value"] expected_spec["template"]["metadata"]["annotations"] = deploy_patch[-1]["value"] actual_spec = json.loads(json.dumps(after_deployment["spec"])) for init in actual_spec["template"]["spec"].get("initContainers", []): if init.get("name") == "gateway-artifact-retention": for key, value in ( ("terminationMessagePath", "/dev/termination-log"), ("terminationMessagePolicy", "File"), ): if init.get(key) == value: init.pop(key) if actual_spec != expected_spec: raise DeployError( "Management Deployment changed outside the runtime image upgrade" ) with port_forward(kubeconfig, MANAGEMENT_SERVICE, 8080) as port: api_json(f"http://127.0.0.1:{port}", "GET", "/healthz") require_idle_runtime(f"http://127.0.0.1:{port}") gateway_after = read_gateway_snapshot(kubeconfig) atomic_write( receipt_dir / "gateway-after.json", canonical_json(gateway_after), mode=0o600 ) if gateway_after != gateway_before: raise DeployError("LiteLLM gateway changed during runtime upgrade") atomic_write( state_directory(config) / "runtime-images.json", canonical_json(images), mode=0o600, ) atomic_write( receipt_dir / "accepted.json", canonical_json( { "application_commit": config["application"]["commit"], "runtime_source_commits": { role: runtime_source_commit(config, role) for role in ("management", "driver") }, "images": {k: images[k] for k in ("management", "driver")}, "management_generation": after_deployment["metadata"]["generation"], "readback": "PASS", "kubernetes_api_cidrs": cidrs, "api_routes_receipt_sha256": canonical_object_sha256( load_json(receipt_dir / "api-routes.json") ), } ), mode=0o600, ) def storage_controller_upgrade_patch( deployment: Mapping[str, Any], image: str, cidr: str ) -> tuple[list, dict]: network = ipaddress.ip_network(cidr, strict=True) if network.version != 4 or network.prefixlen != 32: raise DeployError("local registry access requires an exact IPv4 /32") expected = json.loads(json.dumps(deployment["spec"])) containers = expected["template"]["spec"]["containers"] indices = [ i for i, container in enumerate(containers) if container["name"] == "controller" ] if len(indices) != 1: raise DeployError("expected one storage-controller container") index = indices[0] container = containers[index] container["image"] = image environment = [ entry for entry in container.get("env", []) if entry["name"] != "FRONTIER_REGISTRY_SERVICE_CIDR" ] environment.append( {"name": "FRONTIER_REGISTRY_SERVICE_CIDR", "value": str(network)} ) container["env"] = environment return [ { "op": "test", "path": "/metadata/resourceVersion", "value": deployment["metadata"]["resourceVersion"], }, { "op": "replace", "path": f"/spec/template/spec/containers/{index}/image", "value": image, |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |