ci(release): publish versioned installer bundles (#315)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 18m50s
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 9m14s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 18m50s
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 9m14s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Refs #314 ## Résumé - Réduit les builds d’images aux graphes réellement touchés; les PR ne publient aucune image. Les pushes `main` publient seulement les images affectées sur Docker Hub; un tag semver produit la version et les tags d’images. - Le job de release réutilise les images déjà vérifiées. Gitea reçoit le ZIP Central versionné et les seuls assets nécessaires aux mises à jour Agent signées, sans couches Docker, archive serveur ou métadonnées internes CI. - Les installateurs Central `.sh` et `.ps1` résolvent une release stable, vérifient le digest du ZIP et exécutent le script épinglé à cette version. La simulation offline couvre le bootstrap Linux et le bundle contient les scripts Windows versionnés. - Aligne l’IHM et la maquette Penpot sur les choix Linux/Windows/Docker, commandes copiables et état de release indisponible. Ajoute les skills de synchronisation UI/Penpot, avec ouverture et authentification Penpot obligatoires dans Orca. ## Validation locale - La CI restaure toujours la solution en mode verrouillé pour l’audit NuGet, puis ne compile que les projets de tests concernés et les projets source affectés non couverts par ces tests. Les changements globaux gardent le build complet. Le plan Agent/Web est couvert par les contrats CI. - `python3 scripts/ci/test_ci.py` : 27 tests OK (publication offline, sélection conditionnelle des images, parseur PowerShell si disponible). - `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --filter FullyQualifiedName~SiteDetailTests --no-restore` : 12 tests OK. - `bash -n` sur les scripts shell modifiés, parseur PowerShell sur `install/install-server.ps1`, et `git diff --check` : OK. - Recette Compose construite depuis la source : healthz 200, racine non authentifiée 302, endpoint release sans configuration 502. Projet et tag d’image uniques supprimés puis absence vérifiée. - Simulation release offline : bundle versionné, digest, signature ECDSA, set exact de 7 assets Gitea et absence de rebuild d’images dans le job de publication. ## CI distante - CI Gitea du commit `da89cdff2d8c2a7a9339bfc8640502ede9c6d739` : run #880 entièrement vert; tests .NET/E2E, build et scan serveur OK; builds Agent CPU/GPU et publication release ignorés sur cette PR. ## Limites Pas de vrai run de tag, de publication Docker Hub/Gitea, de runner distant ni d’installation Windows sur hôte réel. Les secrets de publication restent requis seulement pour les événements de publication. L’issue #314 reste ouverte pour ces preuves externes et ne doit pas être fermée par cette PR. ## Maquette Maquette Heimdall Penpot mise à jour : https://penpot.tordais.cc/#/workspace?team-id=073c6639-4451-8006-8008-e66329727382&file-id=aadb42b1-1e8d-8014-8008-7dc15de6e3ff&page-id=127dfd1c-12b5-80f7-8008-79c6fda854a1 Reviewed-on: #315 Co-authored-by: Arnaud Dartois <admin@tordais.cc>
This commit was merged in pull request #315.
This commit is contained in:
1 parent
374b7f267f
commit
24a2400610
29 files changed
+964
-296
No files matched your search
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline acceptance for packaging, release notes, and publication with synthetic doubles."""
|
||||
"""Offline acceptance for one tagged image and installer release with synthetic doubles."""
|
||||
import base64
|
||||
import email
|
||||
import hashlib
|
||||
@@ -67,14 +67,22 @@ args = sys.argv[1:]
|
||||
log = os.environ['OFFLINE_DOCKER_LOG']
|
||||
with open(log, 'a') as f: f.write(json.dumps(args) + '\n')
|
||||
if args[:1] == ['build']:
|
||||
target = args[args.index('-t') + 1]
|
||||
sys.exit(0)
|
||||
sys.exit(12) # Release publication must reuse the scanned image builds.
|
||||
if args[:2] == ['login', 'docker.io']:
|
||||
if sys.stdin.read().strip() != os.environ['DOCKERHUB_TOKEN'] or os.environ.get('DOCKERHUB_USERNAME') != 'offline-user':
|
||||
sys.exit(11)
|
||||
sys.exit(0)
|
||||
if args[:2] == ['manifest', 'inspect']:
|
||||
sys.exit(1) # Simulate absent remote tags; never call a registry.
|
||||
if args[:2] == ['compose', 'version']:
|
||||
marker = os.environ.get('OFFLINE_STOP_COMPOSE_MARKER')
|
||||
if marker:
|
||||
try:
|
||||
open(marker, 'x').close()
|
||||
except FileExistsError:
|
||||
sys.exit(37)
|
||||
print('Docker Compose version v2.offline')
|
||||
sys.exit(0)
|
||||
if args[:1] == ['pull']:
|
||||
sys.exit(0) # Synthetic registry pull; never contact Docker Hub.
|
||||
if args[:1] == ['tag']:
|
||||
sys.exit(0)
|
||||
if args[:1] == ['push']:
|
||||
@@ -87,7 +95,10 @@ if args[:2] == ['image', 'inspect']:
|
||||
digest = os.environ['OFFLINE_AGENT_DIGEST']
|
||||
else:
|
||||
digest = os.environ['OFFLINE_SERVER_DIGEST']
|
||||
print(image + '@' + digest)
|
||||
if '--format' in args and 'RepoDigests' in args[args.index('--format') + 1]:
|
||||
print(image + '@' + digest)
|
||||
elif '--format' in args and 'org.opencontainers.image.revision' in args[args.index('--format') + 1]:
|
||||
print(os.environ['OFFLINE_COMMIT'])
|
||||
sys.exit(0)
|
||||
if args[:1] == ['save']:
|
||||
from pathlib import Path
|
||||
@@ -112,6 +123,28 @@ sys.exit(12)
|
||||
docker_path = fakebin / 'docker'
|
||||
docker_path.write_text(docker_stub)
|
||||
docker_path.chmod(0o700)
|
||||
curl_stub = r'''#!/usr/bin/env python3
|
||||
import hashlib, json, os, shutil, sys
|
||||
args = sys.argv[1:]
|
||||
url = next(value for value in args if value.startswith('https://'))
|
||||
output = args[args.index('--output') + 1]
|
||||
with open(os.environ['OFFLINE_CURL_LOG'], 'a') as log:
|
||||
log.write(url + '\n')
|
||||
if url.endswith('/releases/latest'):
|
||||
payload = json.dumps({'tag_name':'1.2.3','assets':[{
|
||||
'name':'heimdall-installers-1.2.3.zip',
|
||||
'digest':'sha256:' + hashlib.sha256(open(os.environ['OFFLINE_INSTALLER_ZIP'],'rb').read()).hexdigest(),
|
||||
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip'}]}).encode()
|
||||
open(output, 'wb').write(payload)
|
||||
elif url == 'https://release.test/heimdall-installers-1.2.3.zip':
|
||||
shutil.copyfile(os.environ['OFFLINE_INSTALLER_ZIP'], output)
|
||||
else:
|
||||
sys.exit(22)
|
||||
'''
|
||||
curl_path = fakebin / 'curl'
|
||||
curl_path.write_text(curl_stub)
|
||||
curl_path.chmod(0o700)
|
||||
curl_log = temp / 'installer-bootstrap-urls.txt'
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_args):
|
||||
@@ -142,9 +175,11 @@ sys.exit(12)
|
||||
elif path.endswith('/commits/synthetic-merge-commit/pull'):
|
||||
self._json(200, {'number': 42, 'merged': True, 'title': 'Offline acceptance feature',
|
||||
'html_url': 'https://gitea.test/pulls/42'})
|
||||
elif path.endswith('/branches/main'):
|
||||
self._json(200, {'commit': {'id': commit}})
|
||||
elif path.endswith('/releases/tags/ci-' + commit):
|
||||
elif path.endswith('/releases/latest'):
|
||||
self._json(200, {'tag_name': '1.2.3', 'assets': [{
|
||||
'name': 'heimdall-installers-1.2.3.zip',
|
||||
'browser_download_url': 'https://release.test/heimdall-installers-1.2.3.zip'}]})
|
||||
elif path.endswith('/releases/tags/1.2.3'):
|
||||
self._json(404, {'message': 'not found'})
|
||||
elif path.endswith('/releases/7301/assets'):
|
||||
self._json(200, [])
|
||||
@@ -159,10 +194,10 @@ sys.exit(12)
|
||||
body = self.rfile.read(int(self.headers.get('Content-Length', '0')))
|
||||
if path.endswith('/releases'):
|
||||
release = json.loads(body)
|
||||
assert release['tag_name'] == 'ci-' + subprocess.check_output(
|
||||
['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
assert release['tag_name'] == '1.2.3'
|
||||
assert release['name'] == '1.2.3'
|
||||
assert release['draft'] is True
|
||||
assert release['prerelease'] is True
|
||||
assert release['prerelease'] is False
|
||||
assert 'Offline acceptance feature' in release['body']
|
||||
assert release['target_commitish'] == subprocess.check_output(
|
||||
['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
@@ -193,7 +228,11 @@ sys.exit(12)
|
||||
path = urlsplit(self.path).path
|
||||
body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', '0'))))
|
||||
if path.endswith('/releases/7301'):
|
||||
assert set(release_state['assets']) >= {'agent-update-manifest.json', 'agent-update-manifest.sig'}
|
||||
assert set(release_state['assets']) >= {
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig',
|
||||
'heimdall-installers-1.2.3.zip'}
|
||||
assert 'heimdall-web-portable-1.2.3.tar.gz' not in release_state['assets']
|
||||
assert not ({'provenance.json', 'image-digests.txt', 'SHA256SUMS'} & set(release_state['assets']))
|
||||
release_state['release']['draft'] = body['draft']
|
||||
release_state['release']['prerelease'] = body['prerelease']
|
||||
self._json(200, release_state['release'])
|
||||
@@ -215,7 +254,7 @@ sys.exit(12)
|
||||
'SSL_CERT_FILE': str(cert),
|
||||
'NO_PROXY': '127.0.0.1,localhost',
|
||||
'no_proxy': '127.0.0.1,localhost',
|
||||
'BUILD_REF': 'refs/heads/main',
|
||||
'BUILD_REF': 'refs/tags/1.2.3',
|
||||
'BUILD_REPOSITORY': REPOSITORY,
|
||||
'BUILD_RUN_ID': 'offline-acceptance',
|
||||
'BUILD_SERVER_URL': origin,
|
||||
@@ -228,14 +267,45 @@ sys.exit(12)
|
||||
'OFFLINE_SERVER_DIGEST': SERVER_DIGEST,
|
||||
'OFFLINE_AGENT_DIGEST': AGENT_DIGEST,
|
||||
'OFFLINE_GPU_DIGEST': GPU_AGENT_DIGEST,
|
||||
'OFFLINE_COMMIT': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip(),
|
||||
'RELEASE_NOTES_FILE': str(artifacts_dir/'release-notes.md'),
|
||||
'RELEASE_TAG': '1.2.3',
|
||||
})
|
||||
run(['bash', 'scripts/ci/package.sh'], cwd=ROOT, env=env, label='package.sh')
|
||||
with __import__('zipfile').ZipFile(ROOT / 'artifacts/packages/heimdall-installers-1.2.3.zip') as bundle:
|
||||
package_server_script = bundle.read('install/install-server.sh').decode()
|
||||
assert 'PACKAGE_RELEASE_VERSION="1.2.3"' in package_server_script, package_server_script[:1200]
|
||||
launcher_env = env.copy()
|
||||
launcher_env.update({
|
||||
'HEIMDALL_RELEASE_API_URL': origin + '/api/v1/repos/' + REPOSITORY + '/releases',
|
||||
'OFFLINE_CURL_LOG': str(curl_log),
|
||||
'OFFLINE_INSTALLER_ZIP': str(ROOT / 'artifacts/packages/heimdall-installers-1.2.3.zip'),
|
||||
'OFFLINE_STOP_COMPOSE_MARKER': str(temp / 'compose-version-probe'),
|
||||
'TMPDIR': str(temp),
|
||||
})
|
||||
launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
|
||||
env=launcher_env, capture_output=True, text=True)
|
||||
launcher_output = launcher.stdout + launcher.stderr
|
||||
assert launcher.returncode == 37 and (temp / 'compose-version-probe').exists(), (
|
||||
f'installer bootstrap exit={launcher.returncode}; URLs={curl_log.read_text() if curl_log.exists() else "<none>"}; '
|
||||
+ launcher_output[-2000:])
|
||||
bootstrap_urls = curl_log.read_text().splitlines()
|
||||
assert bootstrap_urls == [
|
||||
launcher_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
]
|
||||
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
env['GITEA_TOKEN'] = RELEASE_TOKEN
|
||||
env['BEFORE_SHA'] = commit + '^'
|
||||
env['CURRENT_SHA'] = commit
|
||||
run([sys.executable, 'scripts/ci/release-notes.py'], cwd=ROOT, env=env, label='release-notes.py')
|
||||
for component in ('server', 'agent', 'agent-gpu'):
|
||||
main_env = env.copy()
|
||||
main_env['BUILD_REF'] = 'refs/heads/main'
|
||||
run(['bash', 'scripts/ci/push-images.sh', component], cwd=ROOT, env=main_env,
|
||||
label=f'push-images.sh {component} main')
|
||||
run(['bash', 'scripts/ci/push-images.sh', component], cwd=ROOT, env=env,
|
||||
label=f'push-images.sh {component} tag')
|
||||
run(['bash', 'scripts/ci/publish.sh'], cwd=ROOT, env=env, label='publish.sh')
|
||||
|
||||
packages = ROOT / 'artifacts/packages'
|
||||
@@ -245,49 +315,69 @@ sys.exit(12)
|
||||
signature = temp / 'manifest.sig'
|
||||
signature.write_bytes(release_state['assets']['agent-update-manifest.sig'])
|
||||
manifest = json.loads(manifest_bytes)
|
||||
assert manifest['version'] == '0.0.0-ci.' + commit[:12]
|
||||
assert manifest['version'] == '1.2.3'
|
||||
assert manifest['containerImage'] == 'eltruncho/heimdall-agent'
|
||||
assert manifest['containerImageDigest'] == AGENT_DIGEST
|
||||
assert manifest['containerImageGpu'] == 'eltruncho/heimdall-agent-gpu'
|
||||
assert manifest['containerImageGpuDigest'] == GPU_AGENT_DIGEST
|
||||
provenance = json.loads(release_state['assets']['provenance.json'])
|
||||
assert provenance['commit'] == commit and provenance['ref'] == 'refs/heads/main'
|
||||
provenance = json.loads((packages / 'provenance.json').read_text())
|
||||
assert provenance['commit'] == commit and provenance['ref'] == 'refs/tags/1.2.3'
|
||||
agent_image = json.loads(release_state['assets']['agent-image.json'])
|
||||
assert agent_image == {'digest': AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent'}
|
||||
gpu_agent_image = json.loads(release_state['assets']['agent-image-gpu.json'])
|
||||
assert gpu_agent_image == {'digest': GPU_AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent-gpu'}
|
||||
for platform, digest in manifest['assets'].items():
|
||||
archive = f'heimdall-agent-{platform}-0.0.0-ci.{commit[:12]}.tar.gz'
|
||||
archive = f'heimdall-agent-{platform}-1.2.3.tar.gz'
|
||||
assert hashlib.sha256(release_state['assets'][archive]).hexdigest() == digest
|
||||
subprocess.run(['openssl', 'dgst', '-sha256', '-verify', str(public_key),
|
||||
'-signature', str(signature), str(packages / 'agent-update-manifest.json')],
|
||||
check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
checksums = release_state['assets']['SHA256SUMS'].decode().splitlines()
|
||||
checksums = (packages / 'SHA256SUMS').read_text().splitlines()
|
||||
for line in checksums:
|
||||
digest, filename = line.split(maxsplit=1)
|
||||
filename = filename.lstrip('* ')
|
||||
assert filename in release_state['assets'], f'missing checksum asset {filename}'
|
||||
assert hashlib.sha256(release_state['assets'][filename]).hexdigest() == digest, filename
|
||||
image_digests = release_state['assets']['image-digests.txt'].decode().splitlines()
|
||||
assert len(image_digests) == 6
|
||||
assert sum(AGENT_DIGEST in item for item in image_digests) == 2
|
||||
assert sum(GPU_AGENT_DIGEST in item for item in image_digests) == 2
|
||||
docker_calls = [json.loads(line) for line in docker_log.read_text().splitlines()]
|
||||
assert sum(call[:1] == ['build'] for call in docker_calls) == 3
|
||||
pushes = {call[1] for call in docker_calls if call[:1] == ['push']}
|
||||
assert len(pushes) == 6
|
||||
assert pushes == {
|
||||
f'eltruncho/heimdall:sha-{commit}', f'eltruncho/heimdall:0.0.0-ci.{commit[:12]}',
|
||||
f'eltruncho/heimdall-agent:sha-{commit}', f'eltruncho/heimdall-agent:0.0.0-ci.{commit[:12]}',
|
||||
f'eltruncho/heimdall-agent-gpu:sha-{commit}', f'eltruncho/heimdall-agent-gpu:0.0.0-ci.{commit[:12]}',
|
||||
assert (packages / filename).is_file(), f'missing package checksum input {filename}'
|
||||
assert hashlib.sha256((packages / filename).read_bytes()).hexdigest() == digest, filename
|
||||
image_digests = (packages / 'image-digests.txt').read_text().splitlines()
|
||||
assert len(image_digests) == 3
|
||||
assert sum(AGENT_DIGEST in item for item in image_digests) == 1
|
||||
assert sum(GPU_AGENT_DIGEST in item for item in image_digests) == 1
|
||||
with __import__('zipfile').ZipFile(packages/'heimdall-installers-1.2.3.zip') as bundle:
|
||||
assert 'install/install-server.sh' in bundle.namelist()
|
||||
assert 'install/install-server.ps1' in bundle.namelist()
|
||||
assert 'docker/docker-compose.yml' in bundle.namelist()
|
||||
server_script = bundle.read('install/install-server.sh').decode()
|
||||
windows_script = bundle.read('install/install-server.ps1').decode()
|
||||
assert '/raw/tag/1.2.3' in server_script
|
||||
assert 'eltruncho/heimdall:1.2.3' in server_script
|
||||
assert 'PACKAGE_RELEASE_VERSION="1.2.3"' in server_script
|
||||
assert "PackageReleaseVersion = '1.2.3'" in windows_script
|
||||
assert 'install/install-agent.sh' in bundle.namelist()
|
||||
assert 'install/install-agent.ps1' in bundle.namelist()
|
||||
expected_release_assets = {
|
||||
'heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig',
|
||||
'agent-image.json', 'agent-image-gpu.json',
|
||||
*[f'heimdall-agent-{platform}-1.2.3.tar.gz' for platform in manifest['assets']],
|
||||
}
|
||||
assert sum(call[:1] == ['login'] for call in docker_calls) == 1
|
||||
assert set(release_state['assets']) == expected_release_assets
|
||||
assert not ({'provenance.json', 'image-digests.txt', 'SHA256SUMS'} & set(release_state['assets']))
|
||||
docker_calls = [json.loads(line) for line in docker_log.read_text().splitlines()]
|
||||
assert sum(call[:1] == ['build'] for call in docker_calls) == 0
|
||||
pushes = {call[1] for call in docker_calls if call[:1] == ['push']}
|
||||
assert len(pushes) == 9
|
||||
for image in ('eltruncho/heimdall', 'eltruncho/heimdall-agent', 'eltruncho/heimdall-agent-gpu'):
|
||||
assert f'{image}:sha-{commit}' in pushes
|
||||
assert f'{image}:latest' in pushes
|
||||
assert f'{image}:1.2.3' in pushes
|
||||
assert sum(call[:1] == ['login'] for call in docker_calls) == 7
|
||||
assert release_state['release']['draft'] is False
|
||||
assert release_state['release']['prerelease'] is False
|
||||
assert len(release_state['assets']) >= 9
|
||||
assert len(release_state['assets']) == len(expected_release_assets)
|
||||
assert release_state['authorized'] >= 7
|
||||
print(f'Offline release simulation passed: package archives, P-256 signature, {len(release_state["assets"])} published assets, checksums, CPU/GPU image digests, and six simulated pushes.')
|
||||
assert sum(call[:1] == ['push'] for call in docker_calls if call[0] != 'login') == 12
|
||||
print(f'Offline version release simulation passed: installer ZIP, Agent archives, P-256 signature, {len(release_state["assets"])} Gitea assets, immutable image refs, and selective Docker Hub tags.')
|
||||
print('No real Docker CLI, Docker Hub registry, or Gitea server was contacted.')
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
set -euo pipefail
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -qq
|
||||
apt-get install -y --no-install-recommends ca-certificates curl git python3 unzip postgresql-client docker.io docker-compose-v2
|
||||
apt-get install -y --no-install-recommends ca-certificates curl git jq python3 unzip postgresql-client docker.io docker-compose-v2
|
||||
# Fail explicitly if a runner cannot provide the required Docker build service.
|
||||
docker version --format '{{.Server.Version}}'
|
||||
docker compose version
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build only the projects selected by test-plan.py after solution restore."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PLAN = ROOT / "artifacts" / "tests" / "plan.json"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
plan = json.loads(PLAN.read_text())
|
||||
targets = plan.get("build_projects")
|
||||
if not isinstance(targets, list) or any(not isinstance(target, str) for target in targets):
|
||||
raise SystemExit("Test plan has an invalid build_projects list")
|
||||
if not targets:
|
||||
print("No .NET build targets selected")
|
||||
return
|
||||
|
||||
for target in targets:
|
||||
path = ROOT / target
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"Build target does not exist: {target}")
|
||||
print(f"Building affected target: {target}", flush=True)
|
||||
subprocess.run(
|
||||
["dotnet", "build", target, "-c", "Release", "--no-restore", "-m:2"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Set Gitea workflow outputs for validation and affected container images."""
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
|
||||
def changed_paths() -> list[str]:
|
||||
event = os.environ.get("EVENT_NAME", "")
|
||||
ref = os.environ.get("REF", "")
|
||||
if event == "push" and ref.startswith("refs/tags/"):
|
||||
tag = ref.removeprefix("refs/tags/")
|
||||
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:[.-][0-9A-Za-z.-]+)?", tag):
|
||||
raise SystemExit("Release tags must be MAJOR.MINOR.PATCH with an optional prerelease suffix")
|
||||
return ["*"]
|
||||
if event == "pull_request":
|
||||
base = os.environ["PR_BASE_SHA"]
|
||||
return subprocess.check_output(
|
||||
["git", "diff", "--name-only", f"{base}...HEAD"], text=True
|
||||
).splitlines()
|
||||
before = os.environ.get("PUSH_BEFORE_SHA", "")
|
||||
current = os.environ.get("CURRENT_SHA", "HEAD")
|
||||
if before and before != "0" * 40:
|
||||
return subprocess.check_output(
|
||||
["git", "diff", "--name-only", before, current], text=True
|
||||
).splitlines()
|
||||
return ["*"]
|
||||
|
||||
|
||||
def under(path: str, *prefixes: str) -> bool:
|
||||
return any(path == prefix or path.startswith(prefix.rstrip("/") + "/") for prefix in prefixes)
|
||||
|
||||
|
||||
def scope_for(paths: list[str]) -> dict[str, bool]:
|
||||
all_images = "*" in paths
|
||||
validation_prefixes = ("src/", "tests/", "scripts/ci/", "docker/", "install/", "models/")
|
||||
validation_files = {
|
||||
"Heimdall.slnx", "global.json", ".dockerignore", ".env.example", "Makefile",
|
||||
"GitVersion.yml", "GitVersion.Agent.yml", "Directory.Packages.props", "NuGet.Config",
|
||||
}
|
||||
run_validation = all_images or any(
|
||||
under(path, *validation_prefixes) or path in validation_files or
|
||||
path.startswith(".gitea/workflows/") or path.startswith("Directory.Build.")
|
||||
for path in paths
|
||||
)
|
||||
|
||||
# Shared projects included by both Docker build graphs.
|
||||
shared = {
|
||||
"global.json", "Directory.Packages.props", "NuGet.Config", "GitVersion.yml",
|
||||
}
|
||||
shared_image_change = all_images or any(
|
||||
path in shared or path.startswith("Directory.Build.") for path in paths
|
||||
)
|
||||
server = shared_image_change or any(
|
||||
under(path, "src/Heimdall.Web", "src/Heimdall.Infrastructure",
|
||||
"src/Heimdall.Application", "src/Heimdall.Domain",
|
||||
"src/Heimdall.Domain.Primitives", "src/Heimdall.Contracts")
|
||||
or path == "docker/Dockerfile" or under(path, "install")
|
||||
for path in paths
|
||||
)
|
||||
agent_projects = (
|
||||
"src/Heimdall.Agent", "src/Heimdall.Application", "src/Heimdall.Domain",
|
||||
"src/Heimdall.Domain.Primitives", "src/Heimdall.Contracts", "src/Heimdall.Mdns",
|
||||
)
|
||||
agent_common = any(
|
||||
under(path, *agent_projects) or path == "models/yolov8n.onnx"
|
||||
for path in paths
|
||||
)
|
||||
agent = shared_image_change or agent_common or any(
|
||||
path == "docker/Dockerfile.agent" or path == "GitVersion.Agent.yml"
|
||||
for path in paths
|
||||
)
|
||||
agent_gpu = shared_image_change or agent_common or any(
|
||||
path == "docker/Dockerfile.agent.gpu" or path == "GitVersion.Agent.yml"
|
||||
for path in paths
|
||||
)
|
||||
return {
|
||||
"run_validation": run_validation,
|
||||
"build_server": server,
|
||||
"build_agent": agent,
|
||||
"build_agent_gpu": agent_gpu,
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
output = os.environ.get("GITEA_OUTPUT")
|
||||
if not output:
|
||||
raise SystemExit("GITEA_OUTPUT is required")
|
||||
with open(output, "a", encoding="utf-8") as stream:
|
||||
for name, selected in scope_for(changed_paths()).items():
|
||||
stream.write(f"{name}={'true' if selected else 'false'}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,7 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
sha=$(git rev-parse HEAD)
|
||||
version=$(cat artifacts/version 2>/dev/null || printf '0.0.0-ci.%s' "${sha:0:12}")
|
||||
if [[ "${BUILD_REF:-}" == refs/tags/* ]]; then
|
||||
version=${BUILD_REF#refs/tags/}
|
||||
else
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
fi
|
||||
: "${BUILD_SERVER_URL:?Gitea server URL is required}"
|
||||
: "${BUILD_REPOSITORY:?Gitea repository is required}"
|
||||
source_url="${BUILD_SERVER_URL%/}/${BUILD_REPOSITORY}"
|
||||
|
||||
+53
-15
@@ -2,28 +2,66 @@
|
||||
set -euo pipefail
|
||||
sha=$(git rev-parse HEAD)
|
||||
ref=${BUILD_REF:-}
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
if [[ "$ref" == refs/tags/* ]]; then
|
||||
version=${ref#refs/tags/}
|
||||
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]] || {
|
||||
echo 'Release tags must be MAJOR.MINOR.PATCH with an optional prerelease suffix.' >&2; exit 2;
|
||||
}
|
||||
else
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
fi
|
||||
mkdir -p artifacts/packages
|
||||
for component in Web Agent; do
|
||||
rid=portable
|
||||
out="artifacts/publish/$component-$rid"
|
||||
dotnet publish "src/Heimdall.$component" -c Release --self-contained false \
|
||||
-p:RestoreLockedMode=true -p:Version="$version" -p:SourceRevisionId="$sha" -p:ContinuousIntegrationBuild=true -o "$out"
|
||||
if [[ "$component" == Agent ]]; then
|
||||
mkdir -p "$out/models"
|
||||
cp models/yolov8n.onnx "$out/models/"
|
||||
fi
|
||||
epoch=$(git show -s --format=%ct HEAD)
|
||||
tar --sort=name --mtime="@$epoch" --owner=0 --group=0 --numeric-owner -cf - -C "$out" . | gzip -n > "artifacts/packages/heimdall-${component,,}-$rid-$version.tar.gz"
|
||||
done
|
||||
component=Agent
|
||||
rid=portable
|
||||
out="artifacts/publish/$component-$rid"
|
||||
dotnet publish "src/Heimdall.Agent" -c Release --self-contained false \
|
||||
-p:RestoreLockedMode=true -p:Version="$version" -p:SourceRevisionId="$sha" -p:ContinuousIntegrationBuild=true -o "$out"
|
||||
mkdir -p "$out/models"
|
||||
cp models/yolov8n.onnx "$out/models/"
|
||||
epoch=$(git show -s --format=%ct HEAD)
|
||||
tar --sort=name --mtime="@$epoch" --owner=0 --group=0 --numeric-owner -cf - -C "$out" . | gzip -1 -n > "artifacts/packages/heimdall-agent-$rid-$version.tar.gz"
|
||||
python3 - "$version" "$ref" <<'PY'
|
||||
import os,sys,zipfile
|
||||
from datetime import datetime,timezone
|
||||
from pathlib import Path
|
||||
|
||||
version, ref = sys.argv[1:]
|
||||
epoch = int(__import__('subprocess').check_output(['git','show','-s','--format=%ct','HEAD'],text=True))
|
||||
stamp = datetime.fromtimestamp(max(epoch, 315532800), timezone.utc).timetuple()[:6]
|
||||
tag = version
|
||||
source_base = f"https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/tag/{tag}"
|
||||
files = [Path('install/install-server.sh'), Path('install/install-server.ps1')]
|
||||
files += sorted(Path('install').glob('*.sh'))
|
||||
files += sorted(Path('install').glob('*.ps1'))
|
||||
files += sorted(Path('install').glob('*.py'))
|
||||
files += sorted(Path('docker').glob('docker-compose*.yml'))
|
||||
files += sorted(Path('docker/scripts').glob('*')) if Path('docker/scripts').exists() else []
|
||||
archive = Path(f'artifacts/packages/heimdall-installers-{version}.zip')
|
||||
with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as bundle:
|
||||
for path in sorted(set(files)):
|
||||
if not path.is_file():
|
||||
continue
|
||||
data = path.read_bytes()
|
||||
if path.name in {'install-server.sh', 'install-server.ps1'} or path.name.startswith('docker-compose'):
|
||||
text = data.decode('utf-8')
|
||||
text = text.replace('https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main', source_base)
|
||||
text = text.replace('eltruncho/heimdall:latest', f'eltruncho/heimdall:{version}')
|
||||
text = text.replace('PACKAGE_RELEASE_VERSION="unversioned"', f'PACKAGE_RELEASE_VERSION="{version}"')
|
||||
text = text.replace("PackageReleaseVersion = 'unversioned'", f"PackageReleaseVersion = '{version}'")
|
||||
data = text.encode('utf-8')
|
||||
entry = zipfile.ZipInfo(path.as_posix(), stamp)
|
||||
entry.compress_type = zipfile.ZIP_DEFLATED
|
||||
entry.external_attr = (0o100755 if path.suffix in {'.sh', '.py'} else 0o100644) << 16
|
||||
bundle.writestr(entry, data)
|
||||
PY
|
||||
python3 - "$sha" "$version" "$ref" <<'PY'
|
||||
import json,os,sys
|
||||
from pathlib import Path
|
||||
Path('artifacts/packages/provenance.json').write_text(json.dumps({
|
||||
'commit':sys.argv[1], 'version':sys.argv[2], 'ref':sys.argv[3],
|
||||
'repository':os.environ.get('BUILD_REPOSITORY'), 'run_id':os.environ.get('BUILD_RUN_ID'),
|
||||
'targets':['Web/PWA','Agent'], 'rids':['portable-framework-dependent'],
|
||||
'targets':['Agent native updater'], 'rids':['portable-framework-dependent'],
|
||||
'runtime':'framework-dependent .NET 10', 'mobile_native':False}, indent=2)+'\n')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum *.tar.gz provenance.json > SHA256SUMS)
|
||||
(cd artifacts/packages && sha256sum *.tar.gz heimdall-installers-*.zip provenance.json > SHA256SUMS)
|
||||
printf '%s' "$version" > artifacts/version
|
||||
+12
-20
@@ -33,22 +33,19 @@ openssl ec -in "$signing_key" -noout -text 2>/dev/null | grep -q 'ASN1 OID: prim
|
||||
}
|
||||
openssl pkey -in "$signing_key" -pubout -out artifacts/packages/agent-release-public.pem
|
||||
(cd artifacts/packages && sha256sum agent-release-public.pem >> SHA256SUMS)
|
||||
[[ "$BUILD_REF" == refs/heads/main ]] || { echo 'Release publication is restricted to verified main merges' >&2; exit 1; }
|
||||
tag="ci-$sha"
|
||||
[[ "$BUILD_REF" == refs/tags/* ]] || { echo 'Release publication is restricted to version tags MAJOR.MINOR.PATCH' >&2; exit 1; }
|
||||
tag=${BUILD_REF#refs/tags/}
|
||||
python3 - "$sha" "$tag" <<'PY'
|
||||
import json,sys
|
||||
with open('artifacts/packages/provenance.json') as f:p=json.load(f)
|
||||
if p['commit'] != sys.argv[1] or p['version'] != '0.0.0-ci.' + sys.argv[1][:12] or p['ref'] != 'refs/heads/main':
|
||||
raise SystemExit('Artifact provenance does not match verified main commit')
|
||||
if p['commit'] != sys.argv[1] or p['version'] != sys.argv[2] or p['ref'] != 'refs/tags/' + sys.argv[2]:
|
||||
raise SystemExit('Artifact provenance does not match the verified version tag')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum --check SHA256SUMS)
|
||||
version=$(python3 -c 'import json;print(json.load(open("artifacts/packages/provenance.json"))["version"])')
|
||||
printf '%s' "$version" > artifacts/version
|
||||
bash scripts/ci/images.sh
|
||||
for image_component in server agent agent-gpu; do
|
||||
bash scripts/ci/security.sh "$image_component"
|
||||
done
|
||||
# No mutation is attempted until all credentials, provenance and local builds pass.
|
||||
# The three image jobs have already built, scanned and pushed this exact commit.
|
||||
# Pull only those immutable refs here; this job must not rebuild or rescan images.
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"; rm -f "$signing_key"' EXIT
|
||||
@@ -67,17 +64,12 @@ for component in server agent agent-gpu; do
|
||||
else
|
||||
image=$server_image
|
||||
fi
|
||||
for image_tag in "sha-$sha" "$version"; do
|
||||
if docker manifest inspect "$image:$image_tag" >/dev/null 2>&1; then
|
||||
docker pull "$image:$image_tag"
|
||||
revision=$(docker image inspect "$image:$image_tag" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')
|
||||
[[ "$revision" == "$sha" ]] || { echo 'Refusing to overwrite an image from another commit' >&2; exit 1; }
|
||||
else
|
||||
docker tag "heimdall-$component:ci-$sha" "$image:$image_tag"
|
||||
docker push "$image:$image_tag"
|
||||
fi
|
||||
docker image inspect "$image:$image_tag" --format '{{range .RepoDigests}}{{println .}}{{end}}' >> artifacts/image-digests.txt
|
||||
done
|
||||
docker pull "$image:sha-$sha"
|
||||
revision=$(docker image inspect "$image:sha-$sha" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')
|
||||
[[ "$revision" == "$sha" ]] || { echo 'Pulled image does not match the versioned source commit' >&2; exit 1; }
|
||||
digests=$(docker image inspect "$image:sha-$sha" --format '{{range .RepoDigests}}{{println .}}{{end}}')
|
||||
[[ "$(printf '%s\n' "$digests" | sed '/^$/d' | wc -l)" == 1 ]] || { echo 'Expected one registry digest for the immutable image tag' >&2; exit 1; }
|
||||
printf '%s\n' "$digests" >> artifacts/image-digests.txt
|
||||
done
|
||||
cp artifacts/image-digests.txt artifacts/packages/image-digests.txt
|
||||
(cd artifacts/packages && sha256sum image-digests.txt >> SHA256SUMS)
|
||||
|
||||
+18
-18
@@ -1,9 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
mode=${1:?Expected server, agent, agent-gpu or latest}
|
||||
case "$mode" in server|agent|agent-gpu|latest) ;; *) echo 'Usage: push-images.sh server|agent|agent-gpu|latest' >&2; exit 2 ;; esac
|
||||
mode=${1:?Expected server, agent or agent-gpu}
|
||||
case "$mode" in server|agent|agent-gpu) ;; *) echo 'Usage: push-images.sh server|agent|agent-gpu' >&2; exit 2 ;; esac
|
||||
sha=$(git rev-parse HEAD)
|
||||
if [[ "$mode" == latest ]]; then components=(server agent); else components=("$mode"); fi
|
||||
ref=${BUILD_REF:-}
|
||||
if [[ "$ref" == refs/tags/* ]]; then
|
||||
version=${ref#refs/tags/}
|
||||
else
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
fi
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
|
||||
@@ -17,19 +22,14 @@ repository() {
|
||||
: "${DOCKERHUB_USERNAME:?Docker Hub user is required}"
|
||||
: "${DOCKERHUB_TOKEN:?Docker Hub token is required}"
|
||||
printf '%s' "$DOCKERHUB_TOKEN" | docker login docker.io -u "$DOCKERHUB_USERNAME" --password-stdin
|
||||
if [[ "$mode" == latest ]]; then
|
||||
# Move mutable tags only after both independently built images passed their scans.
|
||||
for component in server agent; do
|
||||
docker pull "$(repository "$component"):sha-$sha"
|
||||
done
|
||||
for component in server agent; do
|
||||
repo=$(repository "$component")
|
||||
docker tag "$repo:sha-$sha" "$repo:latest"
|
||||
docker push "$repo:latest"
|
||||
done
|
||||
else
|
||||
repo=$(repository "$mode")
|
||||
docker image inspect "heimdall-$mode:ci-$sha" >/dev/null
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:sha-$sha"
|
||||
docker push "$repo:sha-$sha"
|
||||
repo=$(repository "$mode")
|
||||
docker image inspect "heimdall-$mode:ci-$sha" >/dev/null
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:sha-$sha"
|
||||
docker push "$repo:sha-$sha"
|
||||
if [[ "$ref" == refs/tags/* ]]; then
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:$version"
|
||||
docker push "$repo:$version"
|
||||
elif [[ "$ref" == refs/heads/main ]]; then
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:latest"
|
||||
docker push "$repo:latest"
|
||||
fi
|
||||
+19
-11
@@ -1,4 +1,4 @@
|
||||
"""Create/update the published Gitea release for one verified main commit."""
|
||||
"""Create/update the Gitea release for one verified version tag."""
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
@@ -10,7 +10,9 @@ import urllib.request
|
||||
base = os.environ['BUILD_SERVER_URL'] + '/api/v1/repos/' + os.environ['BUILD_REPOSITORY']
|
||||
token = os.environ['RELEASE_TOKEN']
|
||||
provenance = json.loads(Path('artifacts/packages/provenance.json').read_text())
|
||||
tag = 'ci-' + provenance['commit']
|
||||
tag = os.environ['RELEASE_TAG']
|
||||
if tag != provenance['version']:
|
||||
raise SystemExit('Release tag does not match the packaged application version')
|
||||
|
||||
def request(path, method='GET', body=None, content_type='application/json', missing=False):
|
||||
data = json.dumps(body).encode() if content_type == 'application/json' and body is not None else body
|
||||
@@ -26,12 +28,23 @@ def request(path, method='GET', body=None, content_type='application/json', miss
|
||||
raise SystemExit(f'Gitea release API failed: HTTP {error.code}') from None
|
||||
|
||||
release = request('/releases/tags/'+urllib.parse.quote(tag, safe=''), missing=True)
|
||||
package_files = sorted(path for path in Path('artifacts/packages').iterdir() if path.is_file())
|
||||
package_root = Path('artifacts/packages')
|
||||
installer_bundle = package_root / f'heimdall-installers-{tag}.zip'
|
||||
agent_archives = sorted(package_root.glob(f'heimdall-agent-*-{tag}.tar.gz'))
|
||||
required_assets = [installer_bundle, package_root / 'agent-release-public.pem',
|
||||
package_root / 'agent-update-manifest.json', package_root / 'agent-update-manifest.sig',
|
||||
package_root / 'agent-image.json', package_root / 'agent-image-gpu.json']
|
||||
if any(not path.is_file() for path in required_assets) or not agent_archives:
|
||||
raise SystemExit('Installer bundle or signed Agent update assets are missing')
|
||||
# CI provenance, image digests, and checksum bookkeeping stay in the build
|
||||
# artifacts. Gitea releases expose only the Central installer bundle and the
|
||||
# files Central/Agent need to verify and install native Agent updates.
|
||||
package_files = sorted([*required_assets, *agent_archives])
|
||||
if release is None:
|
||||
release = request('/releases', 'POST', {
|
||||
'tag_name': tag, 'target_commitish': provenance['commit'], 'name': provenance['version'],
|
||||
'draft': True, 'prerelease': True,
|
||||
'body': f"Automated continuous delivery for merge `{provenance['commit']}`.\n"
|
||||
'draft': True, 'prerelease': '-' in provenance['version'],
|
||||
'body': f"Automated Heimdall release `{provenance['version']}` from `{provenance['commit']}`.\n"
|
||||
f"Actions run: {provenance['run_id']}\n\n"
|
||||
'## Changes\n'
|
||||
+ Path(os.environ['RELEASE_NOTES_FILE']).read_text()})
|
||||
@@ -56,12 +69,7 @@ for path in package_files:
|
||||
request(f"/releases/{release['id']}/assets?name="+urllib.parse.quote(path.name),
|
||||
'POST', payload, 'multipart/form-data; boundary='+boundary)
|
||||
|
||||
main_branch = request('/branches/main')
|
||||
main_sha = main_branch.get('commit', {}).get('id') if main_branch else None
|
||||
if not main_sha:
|
||||
raise SystemExit('Could not verify current main commit before publishing the release')
|
||||
is_current_main = main_sha == provenance['commit']
|
||||
expected_prerelease = not is_current_main
|
||||
expected_prerelease = '-' in provenance['version']
|
||||
published = request(f"/releases/{release['id']}", 'PATCH', {
|
||||
'draft': False,
|
||||
'prerelease': expected_prerelease,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Generate release notes from pull requests merged by one main push."""
|
||||
"""Generate release notes from pull requests merged since the previous version tag."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
+38
-7
@@ -9,6 +9,8 @@ import xml.etree.ElementTree as ET
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TESTS = sorted(path for path in (ROOT / "tests").glob("*/*.csproj") if path.stem != "Heimdall.TestCommon")
|
||||
SOURCES = sorted((ROOT / "src").glob("*/*.csproj"))
|
||||
ALL_PROJECTS = [*SOURCES, *(ROOT / "tests").glob("*/*.csproj")]
|
||||
|
||||
|
||||
def references(project: Path) -> set[Path]:
|
||||
@@ -19,6 +21,30 @@ def references(project: Path) -> set[Path]:
|
||||
}
|
||||
|
||||
|
||||
def referenced_projects(project: Path, graph: dict[Path, set[Path]]) -> set[Path]:
|
||||
result: set[Path] = set()
|
||||
pending = list(graph.get(project, set()))
|
||||
while pending:
|
||||
dependency = pending.pop()
|
||||
if dependency in result:
|
||||
continue
|
||||
result.add(dependency)
|
||||
pending.extend(graph.get(dependency, set()))
|
||||
return result
|
||||
|
||||
|
||||
def build_targets(affected: set[Path], suites: list[str], graph: dict[Path, set[Path]],
|
||||
mode: str) -> list[str]:
|
||||
if mode == "all":
|
||||
return ["Heimdall.slnx"]
|
||||
|
||||
suite_projects = [project for project in TESTS if project.stem in suites]
|
||||
covered_sources = set().union(*(referenced_projects(project, graph) for project in suite_projects)) if suite_projects else set()
|
||||
targets = [*suite_projects, *(project for project in SOURCES
|
||||
if project.resolve() in affected and project.resolve() not in covered_sources)]
|
||||
return sorted({project.resolve().relative_to(ROOT).as_posix() for project in targets})
|
||||
|
||||
|
||||
def changed_files() -> list[str] | None:
|
||||
if os.environ.get("GITEA_EVENT_NAME") != "pull_request":
|
||||
return None
|
||||
@@ -31,11 +57,11 @@ def changed_files() -> list[str] | None:
|
||||
|
||||
def plan(changed: list[str] | None) -> dict[str, object]:
|
||||
if changed is None:
|
||||
return {"mode": "all", "changed": [], "suites": [p.stem for p in TESTS]}
|
||||
suites = [p.stem for p in TESTS]
|
||||
return {"mode": "all", "changed": [], "suites": suites,
|
||||
"build_projects": build_targets(set(), suites, {}, "all")}
|
||||
|
||||
all_paths = {p.resolve() for p in (ROOT / "src").glob("*/*.csproj")} | {
|
||||
p.resolve() for p in (ROOT / "tests").glob("*/*.csproj")
|
||||
}
|
||||
all_paths = {p.resolve() for p in ALL_PROJECTS}
|
||||
graph = {project: references(project) for project in all_paths}
|
||||
changed_projects: set[Path] = set()
|
||||
broad = False
|
||||
@@ -59,10 +85,12 @@ def plan(changed: list[str] | None) -> dict[str, object]:
|
||||
or name in {"readme.md", "AGENTS.md", ".gitea/PULL_REQUEST_TEMPLATE.md"}
|
||||
for name in changed
|
||||
):
|
||||
return {"mode": "affected", "changed": changed, "suites": []}
|
||||
return {"mode": "affected", "changed": changed, "suites": [], "build_projects": []}
|
||||
|
||||
if broad or (changed and not changed_projects):
|
||||
return {"mode": "all", "changed": changed, "suites": [p.stem for p in TESTS]}
|
||||
suites = [p.stem for p in TESTS]
|
||||
return {"mode": "all", "changed": changed, "suites": suites,
|
||||
"build_projects": build_targets(set(), suites, graph, "all")}
|
||||
|
||||
affected = set(changed_projects)
|
||||
while True:
|
||||
@@ -72,7 +100,9 @@ def plan(changed: list[str] | None) -> dict[str, object]:
|
||||
affected |= additions
|
||||
|
||||
suites = [p.stem for p in TESTS if p.resolve() in affected]
|
||||
return {"mode": "affected", "changed": changed, "suites": suites}
|
||||
projects = build_targets(affected, suites, graph, "affected")
|
||||
return {"mode": "affected", "changed": changed, "suites": suites,
|
||||
"build_projects": projects}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -81,3 +111,4 @@ if __name__ == "__main__":
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(json.dumps(result, indent=2) + "\n")
|
||||
print(f"Test plan: {result['mode']} — {', '.join(result['suites']) or 'no .NET suite'}")
|
||||
print(f"Build targets: {', '.join(result['build_projects']) or 'none'}")
|
||||
+113
-12
@@ -1,4 +1,4 @@
|
||||
"""Contract tests for security gates and automatic release uploads, without network."""
|
||||
"""Contract tests for security gates and versioned release uploads, without network."""
|
||||
import contextlib
|
||||
import io
|
||||
import importlib.util
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -15,6 +16,59 @@ from unittest.mock import patch
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
REPO_ROOT = ROOT.parent.parent
|
||||
|
||||
def load_change_scope():
|
||||
spec = importlib.util.spec_from_file_location('heimdall_change_scope', ROOT/'change_scope.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
class ChangeScopeTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.scope = load_change_scope().scope_for
|
||||
|
||||
def test_documentation_does_not_build_or_validate_images(self):
|
||||
self.assertEqual(self.scope(['docs/operations.md']), {
|
||||
'run_validation': False, 'build_server': False,
|
||||
'build_agent': False, 'build_agent_gpu': False,
|
||||
})
|
||||
|
||||
def test_ci_script_changes_validate_without_building_container_images(self):
|
||||
result = self.scope(['.gitea/workflows/build.yml', 'scripts/ci/change_scope.py'])
|
||||
self.assertTrue(result['run_validation'])
|
||||
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
|
||||
(False, False, False))
|
||||
|
||||
def test_server_only_change_selects_only_server_image(self):
|
||||
result = self.scope(['src/Heimdall.Web/Controllers/HealthController.cs'])
|
||||
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
|
||||
(True, False, False))
|
||||
|
||||
def test_agent_change_selects_cpu_and_gpu_images(self):
|
||||
result = self.scope(['src/Heimdall.Agent/Program.cs'])
|
||||
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
|
||||
(False, True, True))
|
||||
|
||||
def test_shared_project_selects_all_dependent_images(self):
|
||||
result = self.scope(['src/Heimdall.Application/Services/AgentService.cs'])
|
||||
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
|
||||
(True, True, True))
|
||||
|
||||
def test_version_tag_selects_every_image(self):
|
||||
self.assertTrue(all(self.scope(['*']).values()))
|
||||
|
||||
def test_version_tag_must_be_semver_before_build_jobs_start(self):
|
||||
with patch.dict(os.environ, {'EVENT_NAME': 'push', 'REF': 'refs/tags/not-a-version'}):
|
||||
with self.assertRaises(SystemExit):
|
||||
load_change_scope().changed_paths()
|
||||
|
||||
class PowerShellInstallerTests(unittest.TestCase):
|
||||
@unittest.skipUnless(shutil.which('pwsh'), 'PowerShell is not installed')
|
||||
def test_server_installer_has_valid_powershell_syntax(self):
|
||||
parser = "$tokens=$null; $errors=$null; [void][System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path 'install/install-server.ps1'), [ref]$tokens, [ref]$errors); if ($errors.Count) { $errors | ForEach-Object { Write-Error $_.Message }; exit 1 }"
|
||||
result = subprocess.run([shutil.which('pwsh'), '-NoProfile', '-Command', parser],
|
||||
cwd=REPO_ROOT, capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
class PwaAssetTests(unittest.TestCase):
|
||||
def test_manifest_raster_icons_exist_with_declared_dimensions(self):
|
||||
manifest = json.loads((REPO_ROOT/'src/Heimdall.Web/wwwroot/manifest.webmanifest').read_text())
|
||||
@@ -43,6 +97,12 @@ def load_test_plan():
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
def load_build_plan():
|
||||
spec = importlib.util.spec_from_file_location('heimdall_build_plan', ROOT/'build-plan.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
def load_efcore_policy():
|
||||
spec = importlib.util.spec_from_file_location('efcore_policy', ROOT/'check-efcore-usage.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -74,20 +134,54 @@ class TestPlanTests(unittest.TestCase):
|
||||
self.assertIn('Heimdall.E2E.Tests', suites)
|
||||
|
||||
def test_agent_change_does_not_run_unrelated_web_tests(self):
|
||||
suites = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])['suites']
|
||||
plan = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])
|
||||
suites = plan['suites']
|
||||
self.assertIn('Heimdall.Agent.Tests', suites)
|
||||
self.assertNotIn('Heimdall.Web.Tests', suites)
|
||||
self.assertIn('tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj', plan['build_projects'])
|
||||
self.assertFalse(any('Heimdall.Web' in target for target in plan['build_projects']))
|
||||
|
||||
def test_web_change_does_not_rebuild_agent(self):
|
||||
plan = load_test_plan().plan(['src/Heimdall.Web/Components/App.razor'])
|
||||
self.assertIn('Heimdall.Web.Tests', plan['suites'])
|
||||
self.assertFalse(any('Heimdall.Agent' in target for target in plan['build_projects']))
|
||||
self.assertFalse(any('Heimdall.slnx' == target for target in plan['build_projects']))
|
||||
|
||||
def test_solution_change_runs_all_and_docs_change_runs_none(self):
|
||||
planner = load_test_plan()
|
||||
self.assertEqual(len(planner.plan(['global.json'])['suites']), len(planner.TESTS))
|
||||
self.assertEqual(planner.plan(['docs/README.md'])['suites'], [])
|
||||
solution = planner.plan(['global.json'])
|
||||
self.assertEqual(len(solution['suites']), len(planner.TESTS))
|
||||
self.assertEqual(solution['build_projects'], ['Heimdall.slnx'])
|
||||
docs = planner.plan(['docs/README.md'])
|
||||
self.assertEqual(docs['suites'], [])
|
||||
self.assertEqual(docs['build_projects'], [])
|
||||
|
||||
def test_removed_backlog_file_does_not_skip_validation_as_docs_only(self):
|
||||
planner = load_test_plan()
|
||||
result = planner.plan(['todo.md'])
|
||||
self.assertEqual(result['mode'], 'all')
|
||||
self.assertEqual(len(result['suites']), len(planner.TESTS))
|
||||
self.assertEqual(result['build_projects'], ['Heimdall.slnx'])
|
||||
|
||||
class BuildPlanTests(unittest.TestCase):
|
||||
def test_builds_only_existing_targets_from_the_plan(self):
|
||||
builder = load_build_plan()
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary)
|
||||
target = 'tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj'
|
||||
project = root/target
|
||||
project.parent.mkdir(parents=True)
|
||||
project.write_text('<Project />')
|
||||
plan_path = root/'artifacts/tests/plan.json'
|
||||
plan_path.parent.mkdir(parents=True)
|
||||
plan_path.write_text(json.dumps({'build_projects':[target]}))
|
||||
builder.ROOT = root
|
||||
builder.PLAN = plan_path
|
||||
with patch('subprocess.run') as run, contextlib.redirect_stdout(io.StringIO()):
|
||||
builder.main()
|
||||
run.assert_called_once_with(
|
||||
['dotnet','build',target,'-c','Release','--no-restore','-m:2'],
|
||||
cwd=root, check=True)
|
||||
|
||||
class GpuAgentImageTests(unittest.TestCase):
|
||||
def test_cpu_default_stays_independent_of_nvidia_runtime(self):
|
||||
@@ -171,24 +265,31 @@ class ReleaseTests(unittest.TestCase):
|
||||
def fake_request(req, timeout):
|
||||
calls.append(req)
|
||||
if req.method == 'GET' and '/releases/tags/' in req.full_url:
|
||||
return Response(json.dumps({'id': 7, 'draft': False, 'tag_name': 'ci-abc123',
|
||||
return Response(json.dumps({'id': 7, 'draft': False, 'tag_name': '1.2.3',
|
||||
'html_url': 'https://example.test/releases/7'}).encode())
|
||||
if req.method == 'GET':
|
||||
return Response(b'[{"id":8,"name":"package.tar.gz"},{"id":9,"name":"provenance.json"}]')
|
||||
names = ['heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
|
||||
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']
|
||||
return Response(json.dumps([{'id':index+8,'name':name} for index,name in enumerate(names)]).encode())
|
||||
if req.method == 'DELETE': return Response(b'')
|
||||
return Response(b'{"id":9}')
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
directory = Path(temp)/'artifacts/packages'
|
||||
directory.mkdir(parents=True)
|
||||
(directory/'provenance.json').write_text(json.dumps({'commit':'abc123','run_id':'42','version':'0.0.0-ci.abc123'}))
|
||||
(directory/'package.tar.gz').write_bytes(b'archive')
|
||||
(directory/'provenance.json').write_text(json.dumps({'commit':'abc123','run_id':'42','version':'1.2.3'}))
|
||||
for name in ['heimdall-installers-1.2.3.zip', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
|
||||
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']:
|
||||
(directory/name).write_bytes(b'archive')
|
||||
(directory/'agent-release-public.pem').write_bytes(b'key')
|
||||
notes = Path(temp)/'release-notes.md'
|
||||
notes.write_text('- Feature from PR #3.\n')
|
||||
original = Path.cwd()
|
||||
try:
|
||||
os.chdir(temp)
|
||||
with patch.dict(os.environ, {'BUILD_SERVER_URL':'https://example.test',
|
||||
'BUILD_REPOSITORY':'owner/repo','BUILD_REF':'refs/heads/main','RELEASE_TOKEN':'dummy',
|
||||
'BUILD_REPOSITORY':'owner/repo','RELEASE_TAG':'1.2.3','RELEASE_TOKEN':'dummy',
|
||||
'RELEASE_NOTES_FILE':str(notes)}), \
|
||||
patch('urllib.request.urlopen', fake_request), contextlib.redirect_stdout(io.StringIO()):
|
||||
try:
|
||||
@@ -202,7 +303,7 @@ class ReleaseTests(unittest.TestCase):
|
||||
|
||||
def test_complete_published_release_is_not_mutated_on_rerun(self):
|
||||
calls = self.execute()
|
||||
self.assertTrue(any('/releases/tags/ci-abc123' in call.full_url for call in calls))
|
||||
self.assertTrue(any('/releases/tags/1.2.3' in call.full_url for call in calls))
|
||||
self.assertEqual([call.method for call in calls], ['GET', 'GET'])
|
||||
|
||||
class OfflineReleaseAcceptanceTests(unittest.TestCase):
|
||||
@@ -211,8 +312,8 @@ class OfflineReleaseAcceptanceTests(unittest.TestCase):
|
||||
[sys.executable, str(ROOT/'accept-release-offline.py')],
|
||||
cwd=REPO_ROOT, capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn('CPU/GPU image digests', result.stdout)
|
||||
self.assertIn('six simulated pushes', result.stdout)
|
||||
self.assertIn('installer ZIP', result.stdout)
|
||||
self.assertIn('selective Docker Hub tags', result.stdout)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user