chore(deploy): switch publisher to Bash

This commit is contained in:
2026-11-23 16:22:43 +01:00
parent 18c1010f98
commit e46108fecc
4 changed files with 168 additions and 118 deletions

View File

@ -27,14 +27,14 @@ Le fichier `docker-compose.prod.yml` consomme quatre images publiées sous `gite
### Construction et publication ### Construction et publication
Depuis la racine, avec Python 3, Git et Docker/BuildKit disponibles : Depuis la racine, avec Bash, Git et Docker/BuildKit disponibles :
```sh ```sh
python3 scripts/publish-images.py --dry-run ./scripts/publish-images.sh --dry-run
python3 scripts/publish-images.py ./scripts/publish-images.sh
python3 scripts/publish-images.py --tag v1.2.0 --dry-run --push ./scripts/publish-images.sh --tag v1.2.0 --dry-run --push
# Après authentification séparée : publication explicite # Après authentification séparée : publication explicite
python3 scripts/publish-images.py --push ./scripts/publish-images.sh --push
``` ```
Sans `--tag`, le SHA Git HEAD complet est utilisé, jamais `latest`. Utiliser un checkout propre validé par Git : le script construit les fichiers présents, et ne vérifie pas leur propreté. Les quatre builds doivent réussir avant le premier push. Un échec de push peut laisser une publication partielle : ne déployer qu’après succès complet. `--dry-run` lit seulement HEAD et affiche le plan, sans appel Docker, build, téléchargement ni push. Les labels OCI source/revision/version identifient Tradarr et, pour Laya, son dépôt amont et son commit épinglé. Le tag commun reste la version de livraison Tradarr. Sans `--tag`, le SHA Git HEAD complet est utilisé, jamais `latest`. Utiliser un checkout propre validé par Git : le script construit les fichiers présents, et ne vérifie pas leur propreté. Les quatre builds doivent réussir avant le premier push. Un échec de push peut laisser une publication partielle : ne déployer qu’après succès complet. `--dry-run` lit seulement HEAD et affiche le plan, sans appel Docker, build, téléchargement ni push. Les labels OCI source/revision/version identifient Tradarr et, pour Laya, son dépôt amont et son commit épinglé. Le tag commun reste la version de livraison Tradarr.

View File

@ -1,64 +0,0 @@
#!/usr/bin/env python3
"""Build Tradarr images; publishing requires --push. No authentication handling."""
import argparse
import pathlib
import re
import subprocess
import sys
ROOT = pathlib.Path(__file__).resolve().parents[1]
REGISTRY = 'gitea.anthonybouteiller.ovh/blomios'
SOURCE = 'https://gitea.anthonybouteiller.ovh/blomios/Tradarr'
LAYA_REVISION = 'e150aa92a0d4059ac621875b39b620847cf1b88a'
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--tag', help='Image tag (default: full Git HEAD SHA)')
parser.add_argument('--push', action='store_true', help='Publish after all four builds succeed')
parser.add_argument('--dry-run', action='store_true', help='Show plan without building or pushing')
args = parser.parse_args(argv)
if args.tag is not None and not re.fullmatch(r'[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}', args.tag):
parser.error('Invalid image tag')
# Runtime read-only Git lookup; no Git mutation and no remote access.
revision = subprocess.run(['git', 'rev-parse', '--verify', 'HEAD'], cwd=ROOT,
check=True, capture_output=True, text=True).stdout.strip()
if not re.fullmatch(r'[0-9a-f]{40}', revision):
parser.error('Expected a full Git SHA-1 revision')
tag = args.tag or revision
commands = []
images = []
for name, context in [('backend', 'backend'), ('frontend', 'frontend'),
('scraper', 'scraper-service'), ('laya', None)]:
image = f'{REGISTRY}/tradarr-{name}:{tag}'
images.append(image)
upstream = name == 'laya'
labels = {'source': 'https://github.com/NandhaKishorM/laya' if upstream else SOURCE,
'revision': LAYA_REVISION if upstream else revision, 'version': tag}
command = ['docker', 'build', '--tag', image]
for key, value in labels.items():
command += ['--label', f'org.opencontainers.image.{key}={value}']
if upstream:
command += ['--build-arg', 'TORCH_INDEX=cpu']
command += [f'https://github.com/NandhaKishorM/laya.git#{LAYA_REVISION}'
if upstream else str(ROOT / context)]
commands.append(command)
if args.push:
commands += [['docker', 'push', image] for image in images]
for command in commands:
if args.dry_run:
print(' '.join(command))
else:
# Docker output is intentionally suppressed: build diagnostics can expose
# local files or registry credentials. Never print exception command/output.
subprocess.run(command, cwd=ROOT, check=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
print(f'{command[1]} completed: {command[3] if command[1] == "build" else command[2]}')
if __name__ == '__main__':
try:
main()
except (subprocess.CalledProcessError, OSError):
print('Image operation failed; stopped without further publication.', file=sys.stderr)
sys.exit(1)

89
scripts/publish-images.sh Executable file
View File

@ -0,0 +1,89 @@
#!/usr/bin/env bash
# Build all four images before optional publication. Authentication stays in Docker.
# Disable tracing even when invoked with bash -x: command output may contain secrets.
set +x
set -euo pipefail
usage() {
cat <<'HELP'
Usage: publish-images.sh [--tag TAG] [--dry-run] [--push]
--tag TAG Image tag (default: full Git HEAD SHA)
--dry-run Print the plan without executing Docker
--push Publish after all four builds succeed
-h, --help Show this help
HELP
}
fail() { printf '%s\n' "$1" >&2; exit 1; }
tag=''
tag_set=false
dry_run=false
push=false
while (($#)); do
case "$1" in
--tag)
(($# >= 2)) || fail 'Missing value for --tag'
tag=$2
tag_set=true
shift 2
;;
--dry-run) dry_run=true; shift ;;
--push) push=true; shift ;;
-h|--help) usage; exit 0 ;;
*) fail 'Unknown argument; use --help' ;;
esac
done
# ASCII Docker tag syntax; never echo rejected input.
export LC_ALL=C
if "$tag_set"; then
[[ $tag =~ ^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$ ]] || fail 'Invalid image tag'
fi
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)
cd -- "$root"
# Read-only runtime lookup; no mutation or remote Git operation.
revision=$(git rev-parse --verify HEAD 2>/dev/null) || fail 'Cannot resolve Git HEAD'
[[ $revision =~ ^[0-9a-f]{40}$ ]] || fail 'Expected a full Git SHA-1 revision'
if ! "$tag_set"; then tag=$revision; fi
readonly registry='gitea.anthonybouteiller.ovh/blomios'
readonly source='https://gitea.anthonybouteiller.ovh/blomios/Tradarr'
readonly laya_revision='e150aa92a0d4059ac621875b39b620847cf1b88a'
images=()
run() {
if "$dry_run"; then
printf '%q ' "$@"
printf '\n'
else
# Suppress Docker diagnostics; do not expose commands or credentials on failure.
"$@" >/dev/null 2>&1 || fail 'Image operation failed; stopped without further publication.'
fi
}
for name in backend frontend scraper laya; do
image="$registry/tradarr-$name:$tag"
images+=("$image")
image_source=$source
image_revision=$revision
context="$root/$name"
extra=()
case "$name" in
scraper) context="$root/scraper-service" ;;
laya)
image_source='https://github.com/NandhaKishorM/laya'
image_revision=$laya_revision
context="$image_source.git#$laya_revision"
extra=(--build-arg TORCH_INDEX=cpu)
;;
esac
run docker build --tag "$image" \
--label "org.opencontainers.image.source=$image_source" \
--label "org.opencontainers.image.revision=$image_revision" \
--label "org.opencontainers.image.version=$tag" \
"${extra[@]}" "$context"
if ! "$dry_run"; then printf 'build completed: %s\n' "$image"; fi
done
if "$push"; then
for image in "${images[@]}"; do
run docker push "$image"
if ! "$dry_run"; then printf 'push completed: %s\n' "$image"; fi
done
fi

View File

@ -1,62 +1,87 @@
import importlib.util """Exercise the shell CLI using local fake executables, never real Git/Docker."""
import json
import os
import pathlib import pathlib
import subprocess import subprocess
import tempfile
import unittest import unittest
from unittest.mock import patch
SCRIPT = pathlib.Path(__file__).with_name('publish-images.py') SCRIPT = pathlib.Path(__file__).with_name('publish-images.sh').resolve()
SHA = 'a' * 40
PIN = 'e150aa92a0d4059ac621875b39b620847cf1b88a'
PREFIX = 'gitea.anthonybouteiller.ovh/blomios/tradarr-'
class PublishTests(unittest.TestCase): class PublishTests(unittest.TestCase):
def invoke(self, args, fail='', sha=SHA):
with tempfile.TemporaryDirectory(prefix='publish tests ') as directory:
root = pathlib.Path(directory)
log = root / 'calls'
for name in ['git', 'docker']:
executable = root / name
executable.write_text('''#!/usr/bin/env python3
import json, os, sys
with open(os.environ['CALL_LOG'], 'a') as stream:
stream.write(json.dumps([os.path.basename(sys.argv[0])] + sys.argv[1:]) + '\\n')
if os.path.basename(sys.argv[0]) == 'git':
print(os.environ['FAKE_SHA'])
else:
print('SECRET_FROM_DOCKER', file=sys.stderr)
if os.environ['FAIL'] and os.environ['FAIL'] in sys.argv:
sys.exit(1)
''')
executable.chmod(0o755)
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
CALL_LOG=str(log), FAKE_SHA=sha, FAIL=fail)
result = subprocess.run(['bash', str(SCRIPT), *args], cwd=root,
env=env, capture_output=True, text=True)
calls = [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []
self.assertNotIn('SECRET_FROM_DOCKER', result.stdout + result.stderr)
return result, calls
def test_publication_contract(self): def test_publication_contract(self):
spec = importlib.util.spec_from_file_location('publish', SCRIPT) for args, builds, pushes in [([], 4, 0), (['--push'], 4, 4),
module = importlib.util.module_from_spec(spec) (['--dry-run', '--push'], 0, 0)]:
spec.loader.exec_module(module) with self.subTest(args=args):
sha = 'a' * 40 result, calls = self.invoke(args)
for args, builds, pushes in [([], 4, 0), (['--push'], 4, 4), (['--dry-run', '--push'], 0, 0)]: self.assertEqual(result.returncode, 0, result.stderr)
calls = []
def run(cmd, **kwargs):
calls.append(cmd)
return subprocess.CompletedProcess(cmd, 0, stdout=sha + '\n')
with patch.object(module.subprocess, 'run', side_effect=run):
module.main(args)
docker = [c for c in calls if c[0] == 'docker'] docker = [c for c in calls if c[0] == 'docker']
self.assertEqual(sum(c[1] == 'build' for c in docker), builds) self.assertEqual([c[1] for c in docker], ['build'] * builds + ['push'] * pushes)
self.assertEqual(sum(c[1] == 'push' for c in docker), pushes) for i, name in enumerate(['backend', 'frontend', 'scraper', 'laya']):
for cmd in docker: self.assertIn(PREFIX + name + ':' + SHA, result.stdout)
self.assertTrue(any(sha in arg for arg in cmd))
if builds: if builds:
laya = docker[3] command = docker[i]
self.assertIn('TORCH_INDEX=cpu', laya) revision = PIN if name == 'laya' else SHA
self.assertTrue(laya[-1].endswith(module.LAYA_REVISION)) self.assertIn('org.opencontainers.image.revision=' + revision, command)
for cmd in docker[:4]: self.assertIn('org.opencontainers.image.version=' + SHA, command)
for label in ['source', 'revision', 'version']: self.assertTrue(any(a.startswith('org.opencontainers.image.source=https://') for a in command))
self.assertTrue(any(a.startswith('org.opencontainers.image.' + label + '=') for a in cmd)) if builds:
self.assertIn('TORCH_INDEX=cpu', docker[3])
self.assertEqual(docker[3][-1], 'https://github.com/NandhaKishorM/laya.git#' + PIN)
def test_failed_build_prevents_all_pushes(self): def test_failures_stop_publication(self):
spec = importlib.util.spec_from_file_location('publish', SCRIPT) for failure, count in [('build', 1), ('push', 5)]:
module = importlib.util.module_from_spec(spec) result, calls = self.invoke(['--push', '--tag', 'v2'], fail=failure)
spec.loader.exec_module(module) self.assertNotEqual(result.returncode, 0)
calls = [] docker = [c for c in calls if c[0] == 'docker']
def run(cmd, **kwargs): self.assertEqual(len(docker), count)
calls.append(cmd) self.assertIn(PREFIX + 'backend:v2', docker[0])
if cmd[:2] == ['docker', 'build']:
raise subprocess.CalledProcessError(1, cmd) def test_bad_arguments_rejected_before_commands(self):
return subprocess.CompletedProcess(cmd, 0, stdout='a' * 40) for args in [['--tag', tag] for tag in ['', 'bad/tag', 'secret=value', '-bad', 'x' * 129, '$(touch bad)', 'a\nb']] + [['--tag'], ['--unknown'], ['extra']]:
with patch.object(module.subprocess, 'run', side_effect=run): with self.subTest(args=args):
with self.assertRaises(subprocess.CalledProcessError): result, calls = self.invoke(args)
module.main(['--push', '--tag', 'v2']) self.assertNotEqual(result.returncode, 0)
self.assertFalse(any(c[:2] == ['docker', 'push'] for c in calls)) self.assertEqual(calls, [])
self.assertIn(module.REGISTRY + '/tradarr-backend:v2', calls[-1])
def test_bad_revision_and_help(self):
result, calls = self.invoke([], sha='short')
self.assertNotEqual(result.returncode, 0)
self.assertEqual(len(calls), 1)
result, calls = self.invoke(['--help'])
self.assertEqual(result.returncode, 0)
self.assertEqual(calls, [])
def test_invalid_tags_fail_before_commands(self):
spec = importlib.util.spec_from_file_location('publish', SCRIPT)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
for tag in ['bad/tag', 'secret=value', '-bad', 'x' * 129]:
with patch.object(module.subprocess, 'run') as run:
with self.assertRaises(SystemExit):
module.main(['--tag', tag])
run.assert_not_called()
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()