Add bounded Gitea CI build runner bootstrap for Synology

This commit is contained in:
Codex
2026-09-29 13:26:20 +03:00
parent 11b73e6468
commit f775929093
7 changed files with 750 additions and 1 deletions
+274 -1
View File
@@ -42,6 +42,17 @@ STATE_FILE = STATE_DIR / "applied.jsonl"
FAILED_STATE_FILE = STATE_DIR / "failed.jsonl"
LOCK_DIR = STATE_DIR / "deploy.lock"
DOCKER = Path("/usr/local/bin/docker")
GITEA_CI_ROOT = Path("/volume1/docker/nodedc-gitea-ci")
GITEA_CI_ENROLLMENT = RUNTIME_DIR / "gitea-ci" / "enrollment.pending.json"
GITEA_CI_IMAGE = "docker.io/gitea/runner@sha256:05e100d9c2268fb300f929cab014e9930591a2d66822454e175c1099d1464b14"
GITEA_CI_JOB_IMAGE = "docker.io/library/node@sha256:9887ee8a5e5aa4fb02e09f03cdf81ef1b52184665549836fe3943eb0c2eaefdb"
GITEA_CI_ENTRIES = (
"docker-compose.gitea-ci.yml", "runner.yaml", "deployment/bootstrap-v1.json",
)
GITEA_CI_SOURCE_SHA256 = {
"docker-compose.gitea-ci.yml": "851d22ae9823c30508a552ec6abb7f547ceda671f3ca77552fb7032bc807ae09",
"runner.yaml": "8634e5427986423ccd8fe18e3bf5072c53addbf17f1efc1395b3a473671d78fe",
}
MAP_GATEWAY_SECRET_DIR = Path("/volume1/docker/nodedc-platform/secrets")
MAP_GATEWAY_SECRET_FILE = MAP_GATEWAY_SECRET_DIR / "map-gateway-admin-secret"
MAP_EGRESS_PROXY_SECRET_FILE = MAP_GATEWAY_SECRET_DIR / "map-egress-proxy-token"
@@ -3064,6 +3075,15 @@ COMPONENTS = {
# separately registers the third stateless service.
"services": ("device-control-core", "device-gateway"),
},
"gitea-ci": {
"payload_root": GITEA_CI_ROOT,
"compose_root": GITEA_CI_ROOT,
"compose_project": "nodedc-gitea-ci",
"compose_files": (GITEA_CI_ROOT / "docker-compose.gitea-ci.yml",),
"bootstrap_root": True,
"compose_no_deps": True,
"services": ("build-runner",),
},
"gitea": {
"payload_root": GITEA_ROOT,
"compose_root": GITEA_ROOT,
@@ -4901,6 +4921,11 @@ def allowed_payload_path(component, rel):
if reason:
die(f"path rejected: {rel}: {reason}")
if component == "gitea-ci":
if rel in GITEA_CI_ENTRIES or rel == "deployment":
return True
die("Gitea CI accepts only its exact bootstrap contract")
if component == "mission-core-map-access":
if rel == "access.json":
return True
@@ -11502,6 +11527,8 @@ def load_artifact(artifact, work_dir):
die(f"files.txt entry missing in payload: {rel}")
validate_payload_tree(manifest["component"], payload_dir, entries)
if manifest["component"] == "gitea-ci":
validate_gitea_ci_payload(payload_dir, entries, manifest["id"])
if manifest["component"] == "mission-core-map-access":
read_map_access_descriptor(payload_dir, entries)
if is_gitea_fresh_install_slice(manifest["component"], entries):
@@ -31361,6 +31388,214 @@ def rollback_map_access(root, backup_dir, entries, current_stamp):
die("Map access rollback policy verification failed")
def validate_gitea_ci_payload(payload_dir, entries, release_id):
if tuple(entries) != GITEA_CI_ENTRIES:
die("Gitea CI bootstrap entry set mismatch")
if not release_id.startswith("gitea-ci-bootstrap-v1-"):
die("Gitea CI bootstrap release identity mismatch")
for rel, expected in GITEA_CI_SOURCE_SHA256.items():
if sha256_file(payload_dir / rel) != expected:
die(f"Gitea CI immutable configuration mismatch: {rel}")
descriptor = read_strict_json(payload_dir / GITEA_CI_ENTRIES[2], "Gitea CI bootstrap")
if descriptor != {
"schemaVersion": "nodedc.gitea-ci.bootstrap.v1",
"releaseId": release_id,
"action": "bootstrap-build-runner",
"repository": "SILVER/NODEDC_DEVICE_CORE",
"instance": "https://git.dcserve.ru",
"runnerName": "synology-device-core-build",
"productionDeployEnabled": False,
"publishedPorts": [],
"capacity": 1,
}:
die("Gitea CI bootstrap descriptor mismatch")
return descriptor
def read_gitea_ci_enrollment():
try:
info = GITEA_CI_ENROLLMENT.lstat()
except FileNotFoundError:
die("Gitea CI separate runtime enrollment is missing")
if (not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077
or info.st_nlink != 1 or info.st_size > 2048):
die("Gitea CI enrollment must be a private regular single-link file")
for parent in GITEA_CI_ENROLLMENT.parents:
if parent.is_symlink():
die("Gitea CI enrollment path contains a symlink")
# Never include parser errors or the credential value in deploy output.
try:
value = json.loads(GITEA_CI_ENROLLMENT.read_text(encoding="utf-8"))
valid = (
isinstance(value, dict)
and set(value) == {"repository", "token"}
and value["repository"] == "SILVER/NODEDC_DEVICE_CORE"
and isinstance(value["token"], str)
and re.fullmatch(r"[A-Za-z0-9_-]{20,256}", value["token"])
)
except (ValueError, UnicodeError):
valid = False
if not valid:
die("Gitea CI enrollment format is invalid")
return value["token"]
def gitea_ci_container_ids(own=False):
command = [str(DOCKER), "ps", "-aq", "--no-trunc"]
if own:
command += ["--filter", "label=com.docker.compose.project=nodedc-gitea-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("Gitea CI Docker container identity is invalid")
return ids
def gitea_ci_inventory():
result = {}
for container_id in gitea_ci_container_ids():
info = inspect_container(container_id)
if info.get("Config", {}).get("Labels", {}).get("com.docker.compose.project") == "nodedc-gitea-ci":
continue
result[container_id] = {
"image": info.get("Image"),
"startedAt": info.get("State", {}).get("StartedAt"),
"running": info.get("State", {}).get("Running"),
}
return result
def preflight_gitea_ci():
for parent in (GITEA_CI_ROOT, *GITEA_CI_ROOT.parents):
if parent.is_symlink():
die("Gitea CI root contains a symlink")
if any((GITEA_CI_ROOT / rel).exists() for rel in GITEA_CI_ENTRIES):
die("Gitea CI bootstrap requires no installed release; use a versioned upgrade")
if gitea_ci_container_ids(own=True):
die("Gitea CI bootstrap requires no existing CI containers")
read_gitea_ci_enrollment()
if shutil.disk_usage(GITEA_CI_ROOT.parent).free < 8 * 1024 ** 3:
die("Gitea CI requires 8 GiB free disk before image preparation")
memory = {}
for line in Path("/proc/meminfo").read_text().splitlines():
parts = line.split()
if len(parts) >= 2:
memory[parts[0].rstrip(":")] = int(parts[1])
if memory.get("MemAvailable", 0) < 3 * 1024 ** 2:
die("Gitea CI requires 3 GiB available memory for its bounded first worker")
return gitea_ci_inventory()
def prepare_gitea_ci():
token = read_gitea_ci_enrollment()
for directory in (GITEA_CI_ROOT / "data", GITEA_CI_ROOT / "secrets"):
if directory.is_symlink():
die("Gitea CI runtime directory cannot be a symlink")
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
os.chown(str(directory), 0, 0)
directory.chmod(0o700)
target = GITEA_CI_ROOT / "secrets" / "registration-token"
if target.exists() or target.is_symlink():
info = target.lstat()
if (not stat.S_ISREG(info.st_mode) or info.st_uid != 0
or info.st_mode & 0o077 or info.st_nlink != 1
or target.read_text().strip() != token):
die("Gitea CI existing runtime enrollment differs")
else:
descriptor = os.open(str(target), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "w") as stream:
stream.write(token + "\n")
stream.flush()
os.fsync(stream.fileno())
# Image acquisition is fixed by the registered component, never by manifest.
for image in (GITEA_CI_IMAGE, GITEA_CI_JOB_IMAGE):
subprocess.run([str(DOCKER), "pull", "--platform", "linux/amd64", image], check=True)
inspect_local_image(image, "Gitea CI pinned image")
def accept_gitea_ci_container(info):
host = info.get("HostConfig", {})
config = info.get("Config", {})
if config.get("Image") != GITEA_CI_IMAGE or not info.get("State", {}).get("Running"):
die("Gitea CI runner image or running state mismatch")
labels = config.get("Labels", {})
if (labels.get("com.docker.compose.project") != "nodedc-gitea-ci"
or labels.get("com.docker.compose.service") != "build-runner"):
die("Gitea 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("Gitea 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("Gitea CI runner host isolation mismatch")
if any(value.startswith("GITEA_RUNNER_REGISTRATION_TOKEN=") for value in config.get("Env", [])):
die("Gitea CI registration token must remain file-backed")
if (host.get("Memory") != 512 * 1024 ** 2
or host.get("NanoCpus") != 500000000
or host.get("PidsLimit") != 128):
die("Gitea CI daemon resource limit mismatch")
expected_mounts = {
"/config/runner.yaml": (str(GITEA_CI_ROOT / "runner.yaml"), False),
"/data": (str(GITEA_CI_ROOT / "data"), True),
"/run/secrets/registration-token": (str(GITEA_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("Gitea CI daemon mount boundary mismatch")
def accept_gitea_ci():
deadline = time.monotonic() + 60
registration = GITEA_CI_ROOT / "data" / ".runner"
expected_image = inspect_local_image(GITEA_CI_IMAGE, "Gitea CI running image")
registered_since = None
while True:
ids = gitea_ci_container_ids(own=True)
if len(ids) != 1:
die("Gitea CI requires exactly one build-runner container")
info = inspect_container(ids[0])
accept_gitea_ci_container(info)
if info.get("Image") != expected_image or info.get("RestartCount", 0) != 0:
die("Gitea 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-device-core-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("Gitea CI runner registration did not complete")
time.sleep(2)
def rollback_gitea_ci(root, backup_dir, entries, current_stamp, runtime_started):
if runtime_started:
stop_and_remove_compose_services("gitea-ci", ("build-runner",))
restore_overlay_source(root, backup_dir, entries, current_stamp)
if gitea_ci_container_ids(own=True):
die("Gitea CI bootstrap rollback left a runner container")
# Preserve .runner and enrollment for diagnosis/retry. They are not app data
# and are never archived in the data-only source partition.
def plan_artifact(artifact):
validate_artifact_location(artifact)
ensure_layout()
@@ -31419,6 +31654,8 @@ def plan_artifact(artifact):
validate_gitea_compose_schema(payload_dir / GITEA_COMPOSE_REL)
if manifest["component"] == "mission-core-map-access":
preflight_map_access(payload_dir, entries)
if manifest["component"] == "gitea-ci":
preflight_gitea_ci()
reject_failed_artifact_replay(manifest, sha)
reject_terminal_engine_l2_failed_artifact(manifest, sha)
reject_terminal_device_plane_foundation_artifact(manifest, sha)
@@ -32002,6 +32239,14 @@ def plan_artifact(artifact):
print(f"component={component}")
print(f"type={manifest['type']}")
print(f"payload_root={root}")
if component == "gitea-ci":
print("ci_transition=bootstrap-build-runner;production_deploy=false")
print("ci_ports=none;cache=false;metrics=false;capacity=1")
print("ci_runner_limit=cpu:0.5,memory:512MiB;job_limit=cpu:1,memory:2GiB")
print(f"ci_runner_image={GITEA_CI_IMAGE}")
print(f"ci_job_image={GITEA_CI_JOB_IMAGE}")
print("ci_pull=exact-digests-only;registration=separate-runtime-enrollment")
print("ci_preserved=all-existing-containers,databases,volumes;rollback=bootstrap-source-and-runner-only")
if component == "mission-core-map-access":
print("access=local-forward:dctouch:127.0.0.1:18103")
print("runtime=sshd-scoped-reload;docker=untouched;cache=preserved")
@@ -36114,6 +36359,10 @@ def prepare_component_runtime(component, entries=None):
def run_component_runtime(component, entries, services):
if component == "gitea-ci":
prepare_gitea_ci()
run_compose(component, services, entries)
return
if component == "platform" and is_platform_provider_catalog_only(entries):
return
if component_artifact_only(component):
@@ -37532,6 +37781,11 @@ process.stdout.write('engine-l2-closed-loop:0.7.0:cas+safe-profile+external-plan
def run_healthchecks(component, entries=None, services=None):
if component == "gitea-ci":
if tuple(services or ()) != ("build-runner",):
die("Gitea CI service set mismatch")
accept_gitea_ci()
return
if component == "mission-core-map-access":
accept_map_access(component_root(component), entries)
return
@@ -38633,6 +38887,7 @@ def apply_artifact(artifact):
engine_backend_recreated = False
engine_backend_initial_mode = None
runtime_started = False
gitea_ci_before = None
current_stamp = stamp()
with DeployLock():
@@ -38677,6 +38932,8 @@ def apply_artifact(artifact):
services = component_services(component, entries)
if component == "mission-core-map-access":
preflight_map_access(payload_dir, entries)
if component == "gitea-ci":
gitea_ci_before = preflight_gitea_ci()
artifact_only = component_artifact_only(component)
defer_bootstrap_root = is_gitea_bootstrap_slice(
component,
@@ -39202,6 +39459,11 @@ def apply_artifact(artifact):
include_nginx_html = component == "engine" and component_publish_dist(component, entries)
create_backup(root, backup_dir, entries, include_nginx_html)
if component == "gitea-ci":
(backup_dir / "ci-runtime-before.json").write_text(
json.dumps(gitea_ci_before, sort_keys=True) + "\n",
encoding="utf-8",
)
if component == "mission-core-map-access":
backup_map_access(backup_dir)
if component == "device-plane":
@@ -39319,6 +39581,9 @@ def apply_artifact(artifact):
):
die("Engine L2 closed-loop app generation was not recreated")
run_healthchecks(component, entries, services)
if component == "gitea-ci":
if gitea_ci_inventory() != gitea_ci_before:
die("Gitea CI altered the preserved container inventory")
if is_device_plane_control_core_release_v4_slice(
component,
entries,
@@ -39390,7 +39655,15 @@ def apply_artifact(artifact):
and backup_dir is not None
and root is not None
):
if component == "mission-core-map-access":
if component == "gitea-ci":
try:
rollback_gitea_ci(root, backup_dir, entries, current_stamp, runtime_started)
if gitea_ci_inventory() != gitea_ci_before:
die("Gitea CI rollback preserved inventory mismatch")
rollback_status = "ok:gitea-ci-bootstrap"
except Exception as rollback_exc:
rollback_status = f"failed:{type(rollback_exc).__name__}"
elif component == "mission-core-map-access":
try:
rollback_map_access(root, backup_dir, entries, current_stamp)
rollback_status = "ok:mission-core-map-access"