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"
+94
View File
@@ -0,0 +1,94 @@
# Synology CI foundation
This additive `gitea-ci` component creates only the Gitea build runner. It does
not activate automatic production apply, change Gitea itself, recreate Device
Core, open a port or modify application databases. Track activation in
DCPLATFORM-37; the canonical runner extension belongs to DCPLATFORM-21.
Initial policy: Device Core push to main automatically qualifies, then deploys
once the separate production controller and recurring release contract have
been accepted. Later repositories receive explicit registrations/policies.
## Reviewed contract
- Root: `/volume1/docker/nodedc-gitea-ci`.
- Compose project: `nodedc-gitea-ci`; selected service: `build-runner`.
- Three fixed data files: Compose, runner config, versioned descriptor.
- Runner and Node images use official Linux amd64 manifest digests (not mutable
tags), resolved from Docker Hub on 2026-09-29. The deploy runner pulls exactly
these two digests. No repository-provided image names or commands.
- Runner: 0.5 CPU, 512 MiB RAM, 128 PIDs, readonly root filesystem. Build jobs:
one at a time, 1 CPU, 2 GiB RAM, 256 PIDs, no privileged mode, no host bind
mounts, no host execution label and no Docker socket in job containers.
- No published ports or host networking. Runner cache and metrics listeners
are disabled. Communication uses outbound HTTPS to the existing Gitea.
- Only the trusted runner daemon mounts the Docker socket. That daemon is
privileged infrastructure even with dropped Linux capabilities: access to
Docker is host authority. It is not passed to repository jobs.
- The first worker is registered for `SILVER/NODEDC_DEVICE_CORE`; sharing with
other repositories requires a reviewed enrollment/registry transition.
## Enrollment, separately from the artifact
Use the authenticated Gitea API to obtain the Device Core repository runner
registration token. Do not copy a personal Git token into the runner.
Prepare `/volume1/docker/nodedc-deploy/runtime/gitea-ci/enrollment.pending.json`
as a private regular single-link file (mode 0600), containing only the exact
repository identity and its registration token. Never put this file in Git,
inbox, artifact payload, logs, Ops text or chat. The canonical runner imports
the token into a root-owned runtime file and mounts it readonly. Gitea creates
the persistent `/data/.runner` identity on first start. Its content is secret.
The bootstrap accepts no existing installed CI descriptor or CI container.
Preflight also checks at least 8 GiB free disk and 3 GiB currently available
memory. If that capacity is unavailable, review smaller fixed limits or another
worker placement; do not bypass the preflight.
## Build and install
From a clean Platform commit:
```sh
python3 -m unittest discover -s infra/gitea-ci -p 'test_*.py'
python3 infra/gitea-ci/build_artifact.py --patch-id gitea-ci-bootstrap-v1-<unique-id> --source-commit <full-sha> --output-dir <output-dir>
```
The first use requires promotion of the reviewed root runner through the
separate atomic administrative gate and fresh `verify-install`. Stage the
immutable `.tgz` in the canonical inbox and inspect its lifecycle. Obtain a
fresh `nodedc-deploy plan`, review exact scope, then apply that artifact once.
`apply` snapshots the source partition and identities of all preexisting
containers. Acceptance checks the pinned image, Compose identity, mounts,
resource limits, privileges and absence of port publications. It requires
registration plus ten seconds of stable daemon operation and unchanged
preexisting container identities. All secrets and application data are outside
the artifact/backup source partition.
If startup or acceptance fails, rollback removes only `build-runner` and
restores only the three source paths. Runner registration and enrollment are
preserved for diagnosis. A failed attempt may leave an offline registration in
Gitea; do not create another token or delete persistent identity blindly.
The global failed-artifact replay rule remains in force.
After `deploy-ok`, verify online registration and a real qualification job via
Gitea API/UI. This is separate functional acceptance; do not ask an operator
to re-prove Docker/runtime checks with NAS shell commands. Do not describe the
runner bootstrap or a green build as a completed automatic production deploy.
## Validation baseline
Installed predecessor confirmed by the operator on 2026-09-29:
`f21936f131365bd3993e2d746e332538d628ba50ef62c1cce833161171ffde47`,
Python 3.8.15, `verify-install-ok`. This matches Platform commit
`11b73e64681f83aa2ebfd89ef266d3be2869f7e1`. The older SMB runner copy is not the
installed authority. Historical Gitea recovery guards remain unchanged.
Tests cover deterministic packaging, exact runtime/payload boundaries, secret
file handling, bootstrap reuse rejection, preserved container identity, real
synthetic-host apply receipts, and failed-health source rollback with runtime
registration retained. Existing Platform/Device/Gitea regression suites are
also required before promotion.
References: [official runner configuration](https://docs.gitea.com/runner/configuration/),
[Docker installation](https://docs.gitea.com/runner/installation/docker/).
+11
View File
@@ -0,0 +1,11 @@
{
"schemaVersion": "nodedc.gitea-ci.bootstrap.v1",
"releaseId": "__PATCH_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
}
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Build the immutable, data-only Gitea CI bootstrap artifact from a clean commit."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import re
import subprocess
import tarfile
ROOT = Path(__file__).resolve().parents[2]
SOURCE = Path(__file__).resolve().parent
ENTRIES = ("docker-compose.gitea-ci.yml", "runner.yaml", "deployment/bootstrap-v1.json")
def bundle(patch_id, source=SOURCE):
if not re.fullmatch(r"gitea-ci-bootstrap-v1-[a-zA-Z0-9._-]{1,65}", patch_id):
raise ValueError("invalid_bootstrap_identity")
descriptor = json.loads((source / "bootstrap-v1.json").read_text())
if descriptor["releaseId"] != "__PATCH_ID__":
raise ValueError("bootstrap_template_identity_mismatch")
descriptor["releaseId"] = patch_id
files = {
"manifest.env": ("id=" + patch_id + "\ncomponent=gitea-ci\ntype=app-overlay\n").encode(),
"files.txt": ("\n".join(ENTRIES) + "\n").encode(),
"payload/docker-compose.gitea-ci.yml": (source / ENTRIES[0]).read_bytes(),
"payload/runner.yaml": (source / ENTRIES[1]).read_bytes(),
"payload/deployment/bootstrap-v1.json": (json.dumps(descriptor, indent=2) + "\n").encode(),
}
result = io.BytesIO()
with gzip.GzipFile(fileobj=result, mode="wb", filename="", mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode="w", format=tarfile.USTAR_FORMAT) as archive:
for name, content in sorted(files.items()):
info = tarfile.TarInfo(name)
info.size = len(content)
info.mode = 0o644
info.mtime = 0
archive.addfile(info, io.BytesIO(content))
return result.getvalue()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--patch-id", required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--source-commit", required=True)
args = parser.parse_args()
actual = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
if not re.fullmatch(r"[a-f0-9]{40}", args.source_commit) or actual != args.source_commit:
raise SystemExit("source_commit_mismatch")
dirty = subprocess.check_output(["git", "status", "--porcelain"], cwd=ROOT, text=True).strip()
if dirty:
raise SystemExit("clean_committed_source_required")
data = bundle(args.patch_id)
args.output_dir.mkdir(parents=True, exist_ok=True)
path = args.output_dir / ("nodedc-gitea-ci-" + args.patch_id + ".tgz")
with path.open("xb") as output:
output.write(data)
print(json.dumps({
"artifact": str(path.resolve()), "patchId": args.patch_id,
"component": "gitea-ci", "sourceCommit": actual,
"sha256": hashlib.sha256(data).hexdigest(), "entries": ENTRIES,
"services": ["build-runner"], "publishedPorts": [],
"productionDeployEnabled": False,
}))
if __name__ == "__main__":
main()
@@ -0,0 +1,41 @@
services:
build-runner:
image: docker.io/gitea/runner@sha256:05e100d9c2268fb300f929cab014e9930591a2d66822454e175c1099d1464b14
platform: linux/amd64
pull_policy: never
restart: unless-stopped
read_only: true
cpus: 0.5
mem_limit: 512m
pids_limit: 128
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
tmpfs:
- /tmp:rw,nosuid,nodev,size=134217728
environment:
HOME: /data
XDG_CACHE_HOME: /data/.cache
CONFIG_FILE: /config/runner.yaml
GITEA_INSTANCE_URL: https://git.dcserve.ru
GITEA_RUNNER_NAME: synology-device-core-build
GITEA_RUNNER_REGISTRATION_TOKEN_FILE: /run/secrets/registration-token
volumes:
- type: bind
source: /volume1/docker/nodedc-gitea-ci/runner.yaml
target: /config/runner.yaml
read_only: true
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-gitea-ci/data
target: /data
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-gitea-ci/secrets/registration-token
target: /run/secrets/registration-token
read_only: true
bind: {create_host_path: false}
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
read_only: true
bind: {create_host_path: false}
+26
View File
@@ -0,0 +1,26 @@
log:
level: info
runner:
file: /data/.runner
capacity: 1
timeout: 1h
shutdown_timeout: 45m
insecure: false
fetch_interval: 5s
env_file: ""
envs:
NODE_OPTIONS: --max-old-space-size=1536
labels:
- nodedc-node22-build:docker://docker.io/library/node@sha256:9887ee8a5e5aa4fb02e09f03cdf81ef1b52184665549836fe3943eb0c2eaefdb
cache:
enabled: false
container:
network: ""
privileged: false
options: --cpus=1 --memory=2g --memory-swap=2g --pids-limit=256 --cap-drop=ALL --security-opt=no-new-privileges
valid_volumes: []
docker_host: "-"
force_pull: false
bind_workdir: false
metrics:
enabled: false
+232
View File
@@ -0,0 +1,232 @@
import copy
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import io
import importlib.machinery
import importlib.util
import json
from pathlib import Path
import tarfile
import tempfile
import unittest
from unittest import mock
import build_artifact
SOURCE = Path(__file__).resolve().parent
loader = importlib.machinery.SourceFileLoader("gitea_ci_runner_test", str(SOURCE.parent / "deploy-runner/nodedc-deploy"))
spec = importlib.util.spec_from_loader(loader.name, loader)
RUNNER = importlib.util.module_from_spec(spec)
loader.exec_module(RUNNER)
def container_info():
return {
"Config": {"Image": RUNNER.GITEA_CI_IMAGE, "Labels": {
"com.docker.compose.project": "nodedc-gitea-ci",
"com.docker.compose.service": "build-runner",
}},
"State": {"Running": True},
"HostConfig": {
"PortBindings": {}, "NetworkMode": "nodedc-gitea-ci_default",
"ReadonlyRootfs": True, "Memory": 512 * 1024 ** 2,
"NanoCpus": 500000000, "PidsLimit": 128,
"CapDrop": ["ALL"], "SecurityOpt": ["no-new-privileges:true"],
},
"NetworkSettings": {"Ports": {}},
"Mounts": [{"Destination": dest, "Source": source, "RW": rw, "Type": "bind"}
for dest, source, rw in [
("/config/runner.yaml", str(RUNNER.GITEA_CI_ROOT / "runner.yaml"), False),
("/data", str(RUNNER.GITEA_CI_ROOT / "data"), True),
("/run/secrets/registration-token", str(RUNNER.GITEA_CI_ROOT / "secrets/registration-token"), False),
("/var/run/docker.sock", "/var/run/docker.sock", False),
]],
}
class BootstrapTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name).resolve()
self.patch = "gitea-ci-bootstrap-v1-test-001"
self.artifact = self.root / "bootstrap.tgz"
self.artifact.write_bytes(build_artifact.bundle(self.patch))
self.extracted = self.root / "extracted"
self.extracted.mkdir()
def load(self):
return RUNNER.load_artifact(self.artifact, self.extracted)
def test_deterministic_data_bundle_accepted_by_canonical_runner(self):
self.assertEqual(self.artifact.read_bytes(), build_artifact.bundle(self.patch))
manifest, entries, _ = self.load()
self.assertEqual(manifest["component"], "gitea-ci")
self.assertEqual(tuple(entries), RUNNER.GITEA_CI_ENTRIES)
self.assertEqual(RUNNER.component_services("gitea-ci", entries), ("build-runner",))
self.assertEqual(RUNNER.component_builds("gitea-ci", entries), ())
self.assertTrue(RUNNER.component_compose_no_deps("gitea-ci", entries))
with tarfile.open(self.artifact) as archive:
self.assertEqual(len(archive.getmembers()), 5)
self.assertTrue(all(m.isfile() and m.mode == 0o644 for m in archive))
def test_changed_ports_or_privileges_in_source_are_rejected(self):
_, entries, payload = self.load()
compose = payload / RUNNER.GITEA_CI_ENTRIES[0]
compose.write_text(compose.read_text() + ' ports: ["9999:9999"]\n')
with self.assertRaisesRegex(RUNNER.DeployError, "immutable configuration"):
RUNNER.validate_gitea_ci_payload(payload, entries, self.patch)
def test_partial_update_and_production_activation_are_rejected(self):
_, entries, payload = self.load()
with self.assertRaisesRegex(RUNNER.DeployError, "entry set"):
RUNNER.validate_gitea_ci_payload(payload, entries[:1], self.patch)
descriptor_path = payload / RUNNER.GITEA_CI_ENTRIES[2]
descriptor = json.loads(descriptor_path.read_text())
descriptor["productionDeployEnabled"] = True
descriptor_path.write_text(json.dumps(descriptor))
with self.assertRaisesRegex(RUNNER.DeployError, "descriptor mismatch"):
RUNNER.validate_gitea_ci_payload(payload, entries, self.patch)
def test_credentials_hooks_and_extra_services_are_not_payload_paths(self):
for path in ("secrets/token", "data/.runner", "install.sh", "other.yml", "controller.py"):
with self.subTest(path=path), self.assertRaises(RUNNER.DeployError):
RUNNER.allowed_payload_path("gitea-ci", path)
def test_runtime_accepts_exact_isolated_daemon(self):
RUNNER.accept_gitea_ci_container(container_info())
def test_runtime_rejects_port_privilege_unbounded_memory_or_wrong_service(self):
for field, value in (
("PortBindings", {"8080/tcp": [{"HostPort": "8080"}]}),
("PublishAllPorts", True), ("NetworkMode", "host"),
("Privileged", True), ("Memory", 0), ("NanoCpus", 0),
("PidsLimit", 0), ("CapAdd", ["SYS_ADMIN"]),
("CapDrop", []), ("SecurityOpt", []),
):
info = container_info()
info["HostConfig"][field] = value
with self.subTest(field=field), self.assertRaises(RUNNER.DeployError):
RUNNER.accept_gitea_ci_container(info)
def test_runtime_rejects_production_volume_mount(self):
info = container_info()
info["Mounts"].append({"Destination": "/production", "Source": "/volume1/docker/nodedc-device-plane", "RW": True, "Type": "bind"})
with self.assertRaisesRegex(RUNNER.DeployError, "mount boundary"):
RUNNER.accept_gitea_ci_container(info)
def test_enrollment_must_be_private_and_is_not_logged_in_error(self):
pending = self.root / "enrollment.json"
pending.write_text(json.dumps({"repository": "SILVER/NODEDC_DEVICE_CORE", "token": "sensitive" * 6}))
with mock.patch.object(RUNNER, "GITEA_CI_ENROLLMENT", pending):
pending.chmod(0o644)
with self.assertRaisesRegex(RUNNER.DeployError, "private regular"):
RUNNER.read_gitea_ci_enrollment()
pending.chmod(0o600)
self.assertEqual(RUNNER.read_gitea_ci_enrollment(), "sensitive" * 6)
pending.write_text('{"token":"sensitive", malformed')
with self.assertRaises(RUNNER.DeployError) as error:
RUNNER.read_gitea_ci_enrollment()
self.assertNotIn("sensitive", str(error.exception))
def test_symlink_enrollment_rejected(self):
actual = self.root / "actual"
actual.write_text("secret")
link = self.root / "link"
link.symlink_to(actual)
with mock.patch.object(RUNNER, "GITEA_CI_ENROLLMENT", link):
with self.assertRaises(RUNNER.DeployError):
RUNNER.read_gitea_ci_enrollment()
def test_preflight_rejects_reusing_bootstrap_for_an_installed_release(self):
(self.root / RUNNER.GITEA_CI_ENTRIES[0]).write_text("installed")
with mock.patch.object(RUNNER, "GITEA_CI_ROOT", self.root):
with self.assertRaisesRegex(RUNNER.DeployError, "versioned upgrade"):
RUNNER.preflight_gitea_ci()
def test_inventory_preserves_only_non_ci_container_identities(self):
old = {"Image": "old", "State": {"Running": True, "StartedAt": "before"}, "Config": {"Labels": {}}}
own = copy.deepcopy(old)
own["Config"]["Labels"]["com.docker.compose.project"] = "nodedc-gitea-ci"
with mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=["old", "own"]), mock.patch.object(RUNNER, "inspect_container", side_effect=[old, own]):
self.assertEqual(RUNNER.gitea_ci_inventory(), {"old": {"image": "old", "startedAt": "before", "running": True}})
def test_rollback_removes_only_ci_service_and_restores_only_source(self):
with mock.patch.object(RUNNER, "stop_and_remove_compose_services") as stop, mock.patch.object(RUNNER, "restore_overlay_source") as restore, mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=[]):
RUNNER.rollback_gitea_ci(self.root, self.root / "backup", RUNNER.GITEA_CI_ENTRIES, "stamp", True)
stop.assert_called_once_with("gitea-ci", ("build-runner",))
restore.assert_called_once_with(self.root, self.root / "backup", RUNNER.GITEA_CI_ENTRIES, "stamp")
def apply_in_synthetic_host(self, fail_health=False):
host = self.root / "host"
host.mkdir()
names = {name: host / name.lower() for name in (
"INBOX", "APPLIED_DIR", "FAILED_DIR", "BACKUPS_DIR", "STATE_DIR", "TMP_DIR", "RUNTIME_DIR",
)}
for directory in names.values():
directory.mkdir()
names.update({
"STATE_FILE": names["STATE_DIR"] / "applied.jsonl",
"FAILED_STATE_FILE": names["STATE_DIR"] / "failed.jsonl",
"LOCK_DIR": names["STATE_DIR"] / "deploy.lock",
"DOCKER": Path("/usr/bin/true"),
})
app = host / "gitea-ci"
registry = {**RUNNER.COMPONENTS["gitea-ci"], "payload_root": app,
"compose_root": app, "compose_files": (app / "docker-compose.gitea-ci.yml",)}
candidate = names["INBOX"] / "candidate.tgz"
candidate.write_bytes(self.artifact.read_bytes())
def start_runtime(*args):
self.assertEqual(args, ("gitea-ci", list(RUNNER.GITEA_CI_ENTRIES), ("build-runner",)))
(app / "data").mkdir()
(app / "data" / "registration-marker").write_text("preserve-on-rollback")
with ExitStack() as stack:
for name, value in names.items():
stack.enter_context(mock.patch.object(RUNNER, name, value))
stack.enter_context(mock.patch.dict(RUNNER.COMPONENTS, {"gitea-ci": registry}))
stack.enter_context(mock.patch.object(RUNNER, "require_root"))
stack.enter_context(mock.patch.object(RUNNER.os, "chown"))
stack.enter_context(mock.patch.object(RUNNER, "preflight_gitea_ci", return_value={}))
stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_inventory", return_value={}))
stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=[]))
stack.enter_context(mock.patch.object(RUNNER, "run_component_runtime", side_effect=start_runtime))
stop = stack.enter_context(mock.patch.object(RUNNER, "stop_and_remove_compose_services"))
stack.enter_context(mock.patch.object(RUNNER, "accept_gitea_ci",
side_effect=RUNNER.DeployError("synthetic health failure") if fail_health else None))
output = stack.enter_context(redirect_stdout(io.StringIO()))
stack.enter_context(redirect_stderr(io.StringIO()))
if fail_health:
with self.assertRaisesRegex(RUNNER.DeployError, "synthetic health failure"):
RUNNER.apply_artifact(candidate)
stop.assert_called_once_with("gitea-ci", ("build-runner",))
else:
RUNNER.apply_artifact(candidate)
stop.assert_not_called()
return names, app, candidate, output.getvalue()
def test_apply_records_commit_independent_artifact_receipt_only_after_acceptance(self):
paths, app, candidate, output = self.apply_in_synthetic_host()
self.assertFalse(candidate.exists())
row = json.loads(paths["STATE_FILE"].read_text())
self.assertEqual(row["status"], "ok")
self.assertEqual(row["component"], "gitea-ci")
self.assertTrue((paths["APPLIED_DIR"] / candidate.name).is_file())
self.assertTrue((paths["BACKUPS_DIR"] / row["backup_id"] / "ci-runtime-before.json").is_file())
self.assertIn("deploy-ok", output)
self.assertTrue((app / "runner.yaml").is_file())
def test_failed_health_restores_source_preserves_registration_and_archives_failure(self):
paths, app, candidate, output = self.apply_in_synthetic_host(fail_health=True)
self.assertFalse(paths["STATE_FILE"].exists())
row = json.loads(paths["FAILED_STATE_FILE"].read_text())
self.assertEqual(row["rollback_status"], "ok:gitea-ci-bootstrap")
self.assertTrue((paths["FAILED_DIR"] / row["artifact"]).is_file())
self.assertFalse((app / "runner.yaml").exists())
self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback")
self.assertNotIn("deploy-ok", output)
if __name__ == "__main__":
unittest.main()