# CMS owns one separately registered, repository-scoped build runner. CMS_CI_ROOT = Path('/volume1/docker/nodedc-cms-autodeploy') CMS_CI_ENROLLMENT = DEPLOY_ROOT / 'runner-install' / 'cms-ci-enrollment.pending.json' CMS_CI_IMAGE = GITEA_CI_IMAGE CMS_CI_JOB_IMAGE = GITEA_CI_JOB_IMAGE CMS_CI_ENTRIES = CMS_CI_V2_ENTRIES = CMS_CI_V3_ENTRIES = CMS_CI_V4_ENTRIES = ('deployment/dc-cms-autodeploy-v1.json','docker-compose.cms-ci.yml','runner.yaml') CMS_CI_SOURCE_SHA256 = __CMS_CI_HASHES__ def read_cms_ci_v2_input(runtime=False): """Read a bounded operator handoff or the private NAS copy, never SMB modes.""" path = (CMS_CI_ROOT / "secrets" / "registration-token" if runtime else CMS_CI_ENROLLMENT) for parent in path.parents: if parent.is_symlink(): die("CMS CI enrollment path contains a symlink") try: operator_uid = pwd.getpwnam("dctouch").pw_uid except KeyError: die("CMS CI staging account dctouch is missing") try: fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) except OSError: die("CMS CI enrollment input cannot be opened safely") with os.fdopen(fd, "rb") as stream: info = os.fstat(stream.fileno()) if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or not 1 <= info.st_size <= 2048 or info.st_uid not in ((0,) if runtime else (0, operator_uid)) or (runtime and stat.S_IMODE(info.st_mode) != 0o600)): die("CMS CI enrollment metadata rejected: " f"runtime={runtime};mode={stat.S_IMODE(info.st_mode):04o};" f"uid={info.st_uid};nlink={info.st_nlink};size={info.st_size}") raw = stream.read(2049) after = os.fstat(stream.fileno()) if (info.st_size, info.st_mtime_ns, info.st_ctime_ns) != ( after.st_size, after.st_mtime_ns, after.st_ctime_ns): die("CMS CI enrollment changed while reading") try: if runtime: token = raw.decode("ascii").strip() else: value = json.loads(raw) if (not isinstance(value, dict) or set(value) != {"repository", "token"} or value["repository"] != "SILVER/DC_CMS"): raise ValueError() token = value["token"] if not isinstance(token, str) or not re.fullmatch(r"[A-Za-z0-9_-]{20,256}", token): raise ValueError() except (ValueError, UnicodeError): die("CMS CI enrollment format is invalid") return token, info def preflight_cms_ci_v2_enrollment(): private = CMS_CI_ROOT / "secrets" / "registration-token" if CMS_CI_ENROLLMENT.exists() or CMS_CI_ENROLLMENT.is_symlink(): token, info = read_cms_ci_v2_input() if private.exists() or private.is_symlink(): if read_cms_ci_v2_input(runtime=True)[0] != token: die("CMS CI existing runtime enrollment differs") return f"import-staging;mode={stat.S_IMODE(info.st_mode):04o};uid={info.st_uid};nlink={info.st_nlink};size={info.st_size}" read_cms_ci_v2_input(runtime=True) return "reuse-root-private-runtime" def import_cms_ci_v2_enrollment(): """The v2 apply transition owns private creation; plan never changes rights.""" preflight_cms_ci_v2_enrollment() pending = CMS_CI_ENROLLMENT.exists() token, source_info = read_cms_ci_v2_input(runtime=not pending) directory = CMS_CI_ROOT / "secrets" directory.mkdir(mode=0o700, parents=True, exist_ok=True) if directory.is_symlink(): die("CMS CI private directory cannot be a symlink") os.chown(str(directory), 0, 0) directory.chmod(0o700) target = directory / "registration-token" if not target.exists(): fd, temporary = tempfile.mkstemp(prefix=".enrollment-", dir=str(directory)) try: with os.fdopen(fd, "w") as stream: os.fchown(stream.fileno(), 0, 0) os.fchmod(stream.fileno(), 0o600) stream.write(token + "\n") stream.flush() os.fsync(stream.fileno()) # Atomic publication without replacing an existing identity. os.link(temporary, str(target)) finally: os.unlink(temporary) if read_cms_ci_v2_input(runtime=True)[0] != token: die("CMS CI private enrollment import verification failed") for path in (directory, CMS_CI_ROOT): fd = os.open(str(path), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) try: os.fsync(fd) finally: os.close(fd) if pending: current = CMS_CI_ENROLLMENT.lstat() if (current.st_dev, current.st_ino, current.st_mtime_ns, current.st_size) != ( source_info.st_dev, source_info.st_ino, source_info.st_mtime_ns, source_info.st_size): die("CMS CI enrollment staging changed before cleanup") CMS_CI_ENROLLMENT.unlink() print("ci_enrollment=root-owned-private-runtime;staging=removed") return token def cms_ci_container_ids(own=False): command = [str(DOCKER), "ps", "-aq", "--no-trunc"] if own: command += ["--filter", "label=com.docker.compose.project=nodedc-cms-ci"] result = subprocess.run(command, capture_output=True, text=True, check=True) ids = result.stdout.split() if any(not re.fullmatch(r"[a-f0-9]{64}", value) for value in ids): die("CMS CI Docker container identity is invalid") return ids def cms_ci_inventory(): result = {} for container_id in cms_ci_container_ids(): info = inspect_container(container_id) if info.get("Config", {}).get("Labels", {}).get("com.docker.compose.project") == "nodedc-cms-ci": continue result[container_id] = { "image": info.get("Image"), "startedAt": info.get("State", {}).get("StartedAt"), "running": info.get("State", {}).get("Running"), } return result def cms_ci_check_affinity(pid, exact=False): if type(pid) is not int or pid < 0 or (exact and pid == 0): die("CMS CI CPU affinity process identity is invalid") try: available = os.sched_getaffinity(pid) except (AttributeError, OSError): die("CMS CI CPU affinity cannot be verified") valid = available == {7} if exact else 7 in available if not valid: die("CMS CI requires logical CPU7 affinity") def cms_ci_host_capabilities(entries): result = subprocess.run([str(DOCKER), "info", "--format", "{{json .}}"], capture_output=True, text=True, check=True, timeout=30) try: raw = json.loads(result.stdout) if not isinstance(raw, dict): raise ValueError() except ValueError: die("CMS CI Docker capability report is invalid") # Do not print registry/proxy configuration, host identity or Docker credentials. fields = ("ServerVersion", "KernelVersion", "OSType", "Architecture", "NCPU", "MemTotal", "MemoryLimit", "SwapLimit", "CpuCfsPeriod", "CpuCfsQuota", "CPUShares", "CPUSet", "PidsLimit", "CgroupVersion") report = {key: raw.get(key) for key in fields} print("ci_host=" + json.dumps(report, sort_keys=True, separators=(",", ":"))) required = ["MemoryLimit"] if tuple(entries) == CMS_CI_V4_ENTRIES: required += ["CPUShares", "CPUSet", "SwapLimit"] elif tuple(entries) == CMS_CI_V3_ENTRIES: required.append("PidsLimit") required.append("CPUShares") else: required += ["PidsLimit", "CpuCfsPeriod", "CpuCfsQuota", "SwapLimit"] missing = [name for name in required if raw.get(name) is not True] if missing: die("CMS CI host lacks required resource controls: " + ",".join(missing)) if raw.get("OSType") != "linux" or raw.get("Architecture") not in ("amd64", "x86_64"): die("CMS CI pinned worker requires Linux amd64") if tuple(entries) == CMS_CI_V4_ENTRIES: if type(raw.get("NCPU")) is not int or raw["NCPU"] < 8: die("CMS CI CPU7 profile requires at least eight logical CPUs") cms_ci_check_affinity(0) return report def accept_cms_ci_container(info, entries=CMS_CI_ENTRIES): host = info.get("HostConfig", {}) config = info.get("Config", {}) if config.get("Image") != CMS_CI_IMAGE or not info.get("State", {}).get("Running"): die("CMS CI runner image or running state mismatch") labels = config.get("Labels", {}) if (labels.get("com.docker.compose.project") != "nodedc-cms-ci" or labels.get("com.docker.compose.service") != "build-runner"): die("CMS CI runner Compose identity mismatch") if (host.get("PortBindings") or host.get("PublishAllPorts") or host.get("NetworkMode") in ("host", "none") or any(info.get("NetworkSettings", {}).get("Ports", {}).values())): die("CMS CI host network or published port rejected") if (host.get("Privileged") or host.get("CapAdd") or host.get("Devices") or not host.get("ReadonlyRootfs") or host.get("PidMode") or host.get("IpcMode") == "host" or host.get("CapDrop") != ["ALL"] or "no-new-privileges:true" not in host.get("SecurityOpt", [])): die("CMS CI runner host isolation mismatch") if any(value.startswith("GITEA_RUNNER_REGISTRATION_TOKEN=") for value in config.get("Env", [])): die("CMS CI registration token must remain file-backed") v4 = tuple(entries) == CMS_CI_V4_ENTRIES if v4 or tuple(entries) == CMS_CI_V3_ENTRIES: valid_cpu = (host.get("CpuShares") == 64 and not host.get("NanoCpus") and not host.get("CpuQuota") and not host.get("CpuPeriod")) else: valid_cpu = host.get("NanoCpus") == 500000000 valid_pids = host.get("PidsLimit") in (None, 0, -1) if v4 else host.get("PidsLimit") == 128 if v4: valid_cpu = valid_cpu and host.get("CpusetCpus") == "7" if host.get("MemorySwap") != 512 * 1024 ** 2: die("CMS CI daemon memory/swap limit mismatch") if (host.get("Memory") != 512 * 1024 ** 2 or not valid_cpu or not valid_pids): die("CMS CI daemon resource limit mismatch") if v4: cms_ci_check_affinity(info.get("State", {}).get("Pid"), exact=True) expected_mounts = { "/config/runner.yaml": (str(CMS_CI_ROOT / "runner.yaml"), False), "/data": (str(CMS_CI_ROOT / "data"), True), "/run/secrets/registration-token": (str(CMS_CI_ROOT / "secrets/registration-token"), False), "/var/run/docker.sock": ("/var/run/docker.sock", False), } actual = { mount.get("Destination"): (mount.get("Source"), mount.get("RW")) for mount in info.get("Mounts", []) if mount.get("Type") != "tmpfs" } if actual != expected_mounts: die("CMS CI daemon mount boundary mismatch") def accept_cms_ci(entries=CMS_CI_ENTRIES): deadline = time.monotonic() + 60 registration = CMS_CI_ROOT / "data" / ".runner" expected_image = inspect_local_image(CMS_CI_IMAGE, "CMS CI running image") registered_since = None while True: ids = cms_ci_container_ids(own=True) if len(ids) != 1: die("CMS CI requires exactly one build-runner container") info = inspect_container(ids[0]) accept_cms_ci_container(info, entries) if info.get("Image") != expected_image or info.get("RestartCount", 0) != 0: die("CMS CI image identity or restart count mismatch") if registration.is_file() and not registration.is_symlink(): try: value = json.loads(registration.read_text()) valid = (value.get("name") == "synology-cms-build" and value.get("address", "").rstrip("/") == "https://git.dcserve.ru" and value.get("id") and value.get("uuid") and value.get("token")) except (ValueError, UnicodeError): valid = False if valid: registration.chmod(0o600) if registered_since is None: registered_since = time.monotonic() if time.monotonic() - registered_since >= 10: print("ci_accept=registered-daemon;published_ports=none;production_deploy=false") return else: registered_since = None if time.monotonic() >= deadline: die("CMS CI runner registration did not complete") time.sleep(2) def capture_cms_ci_diagnostics(backup_dir): # Logs can contain tokens. Retain only fixed categories and counts, never raw text. report = {"containers": [], "rawLogsSaved": False} try: for container_id in cms_ci_container_ids(own=True): result = subprocess.run([str(DOCKER), "logs", "--tail", "60", container_id], capture_output=True, text=True, timeout=10) text = (result.stdout + result.stderr).lower() signatures = {"dns": ("no such host", "server misbehaving"), "tls": ("x509", "tls handshake"), "network": ("connection refused", "i/o timeout", "no route to host"), "actions-disabled-or-route": ("404", "not found"), "token-rejected": ("registration token", "unauthenticated"), "filesystem": ("permission denied", "read-only file system"), "configuration": ("unmarshal", "yaml:", "invalid config"), "registered": ("runner registered successfully",)} reasons = [key for key, patterns in signatures.items() if any(p in text for p in patterns)] report["containers"].append({"id": container_id, "categories": reasons or ["unclassified"], "logLines": len(text.splitlines())}) except Exception: report["diagnosticStatus"] = "unavailable" (backup_dir / "ci-startup-diagnostics.json").write_text(json.dumps(report, sort_keys=True) + "\n") print("ci_startup_diagnostics=" + json.dumps(report, sort_keys=True)) def preflight_cms_ci(): for path in (CMS_CI_ROOT,*CMS_CI_ROOT.parents): if path.is_symlink():die('CMS CI root contains a symlink') if any((CMS_CI_ROOT/rel).exists() for rel in CMS_CI_ENTRIES):die('CMS CI requires an uninstalled source partition') if cms_ci_container_ids(own=True):die('CMS CI already has a runner') cms_ci_host_capabilities(CMS_CI_V4_ENTRIES) require_gitea_actions_ping() preflight_cms_ci_v2_enrollment() # Existing Device Core CI already acquired these exact digests. No new pull. for image in (CMS_CI_IMAGE,CMS_CI_JOB_IMAGE):inspect_local_image(image,'CMS CI pinned image') if shutil.disk_usage(CMS_CI_ROOT.parent).free < 8*1024**3:die('CMS CI requires 8 GiB free disk') memory={line.split(':')[0]:int(line.split()[1]) for line in Path('/proc/meminfo').read_text().splitlines() if len(line.split())>=2} if memory.get('MemAvailable',0)<3*1024**2:die('CMS CI requires 3 GiB available memory') def apply_cms_ci(): import_cms_ci_v2_enrollment() data=CMS_CI_ROOT/'data' if data.is_symlink():die('CMS CI data cannot be a symlink') data.mkdir(mode=0o700,exist_ok=True);os.chown(str(data),0,0);data.chmod(0o700) subprocess.run(compose_base_cmd('dc-cms-autodeploy')+['up','-d','--no-build','--pull','never','--no-deps','build-runner'],cwd=str(CMS_CI_ROOT),check=True) accept_cms_ci(CMS_CI_V4_ENTRIES) def cms_ci_inventory_preserved(before): current=cms_ci_inventory() # A registered worker can create ephemeral CI job containers immediately. # Every preexisting container must retain its exact image and generation. return all(current.get(identity)==row for identity,row in before.items())