diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..cbb1906 --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,14 @@ +# Keep credentials and host artifacts out of the build context. +.env +.env.* +**/.env +**/.env.* +.git +.aws +.claude +**/*.pem +**/*.key +node_modules +dist +coverage +__pycache__ diff --git a/backend/internal/server/compose_laya_test.go b/backend/internal/server/compose_laya_test.go index 33f8d9c..c051a63 100644 --- a/backend/internal/server/compose_laya_test.go +++ b/backend/internal/server/compose_laya_test.go @@ -2,6 +2,7 @@ package server import ( "os" + "reflect" "testing" "gopkg.in/yaml.v3" @@ -46,31 +47,55 @@ func TestStandardComposeRunsLayaOnCPUAndKeepsOllamaOptional(t *testing.T) { }) } -func TestProductionComposeBuildsBackendFromCurrentLocalCode(t *testing.T) { - data, err := os.ReadFile("../../../docker-compose.prod.yml") - if err != nil { - t.Fatal(err) +func TestProductionComposeUsesPublishedImagesAndPreservesRuntime(t *testing.T) { + read := func(path string) map[string]any { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var document map[string]any + if err := yaml.Unmarshal(data, &document); err != nil { + t.Fatal(err) + } + return document } - var compose struct { - Services map[string]struct { - Image string `yaml:"image"` - Build *struct { - Context string `yaml:"context"` - Dockerfile string `yaml:"dockerfile"` - } `yaml:"build"` - } `yaml:"services"` + standard := read("../../../docker-compose.yml") + production := read("../../../docker-compose.prod.yml") + services := production["services"].(map[string]any) + names := map[string]string{"backend": "backend", "frontend": "frontend", "scraper": "scraper", "laya": "laya"} + for name, raw := range services { + service := raw.(map[string]any) + if _, exists := service["build"]; exists { + t.Errorf("%s still builds", name) + } + if service["pull_policy"] == "build" { + t.Errorf("%s has build pull policy", name) + } + if suffix, ok := names[name]; ok { + want := "gitea.anthonybouteiller.ovh/blomios/tradarr-" + suffix + ":${TRADARR_IMAGE_TAG:?TRADARR_IMAGE_TAG is required}" + if service["image"] != want { + t.Errorf("%s image=%v", name, service["image"]) + } + } + original := standard["services"].(map[string]any)[name].(map[string]any) + delete(original, "build") + delete(original, "pull_policy") + if _, ok := names[name]; ok { + delete(original, "image") + delete(service, "image") + } + if name == "backend" { + if service["stop_grace_period"] != "5m" { + t.Error("production shutdown grace lost") + } + delete(service, "stop_grace_period") + } + if !reflect.DeepEqual(original, service) { + t.Errorf("%s runtime differs from standard Compose", name) + } } - if err := yaml.Unmarshal(data, &compose); err != nil { - t.Fatalf("parse docker-compose.prod.yml: %v", err) - } - backend, ok := compose.Services["backend"] - if !ok { - t.Fatal("production Compose has no backend service") - } - if backend.Build == nil || backend.Build.Context != "./backend" { - t.Errorf("backend build=%+v; want an image built from local ./backend source", backend.Build) - } - if backend.Image == "gitea.anthonybouteiller.ovh/blomios/tradarr-backend:v1.1.0" { - t.Errorf("backend still pins historical v1.1.0 image instead of current ticket code") + if !reflect.DeepEqual(standard["volumes"], production["volumes"]) { + t.Error("volumes differ") } } diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 5958736..ef88c38 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -21,7 +21,7 @@ services: - "8191" scraper: - image: gitea.anthonybouteiller.ovh/blomios/tradarr-scraper:v1.1.0 + image: gitea.anthonybouteiller.ovh/blomios/tradarr-scraper:${TRADARR_IMAGE_TAG:?TRADARR_IMAGE_TAG is required} restart: unless-stopped depends_on: - byparr @@ -31,11 +31,9 @@ services: - "3001" backend: - build: - context: ./backend - dockerfile: Dockerfile - restart: unless-stopped stop_grace_period: 5m + image: gitea.anthonybouteiller.ovh/blomios/tradarr-backend:${TRADARR_IMAGE_TAG:?TRADARR_IMAGE_TAG is required} + restart: unless-stopped depends_on: postgres: condition: service_healthy @@ -62,13 +60,7 @@ services: - "8080" laya: - image: tradarr-laya:v0.5.2-cpu - pull_policy: build - build: - # Official v0.5.2 annotated tag dereferenced to its immutable commit. - context: https://github.com/NandhaKishorM/laya.git#e150aa92a0d4059ac621875b39b620847cf1b88a - args: - TORCH_INDEX: cpu + image: gitea.anthonybouteiller.ovh/blomios/tradarr-laya:${TRADARR_IMAGE_TAG:?TRADARR_IMAGE_TAG is required} command: ["laya-serve"] restart: unless-stopped environment: @@ -99,7 +91,7 @@ services: - ollama_data:/root/.ollama frontend: - image: gitea.anthonybouteiller.ovh/blomios/tradarr-frontend:v1.1.0 + image: gitea.anthonybouteiller.ovh/blomios/tradarr-frontend:${TRADARR_IMAGE_TAG:?TRADARR_IMAGE_TAG is required} restart: unless-stopped depends_on: - backend diff --git a/docs/operations.md b/docs/operations.md index 90dcbc1..135b5c4 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -23,7 +23,33 @@ Compose consomme aussi `POSTGRES_DB`/`POSTGRES_USER` (défaut `tradarr`), `POSTG Pour le développement hôte, exporter les variables backend dans le terminal. Le serveur ne charge pas de fichier dotenv. Lancer `make dev-backend` depuis la racine garantit le chemin relatif des migrations. Un PostgreSQL hôte doit être fourni séparément : le Compose existant ne publie pas son port 5432. -Le fichier `docker-compose.prod.yml` construit le backend à partir du code local actuel (`context: ./backend`, `Dockerfile`). `docker compose -f docker-compose.prod.yml build backend` construit seulement cette image, sans démarrer les services ni publier d’image. Le frontend et le service de récupération conservent leurs images préconstruites `v1.1.0` ; la récupération reste inchangée. Aucune image n’est publiée par ce workflow. Les deux Compose contiennent un montage absolu `/home/anthony/.claude:/root/.claude`, non portable et lié au fournisseur Claude Code. Examiner sa pertinence pour l’installation, sans partager de credentials. Les services de récupération et leur configuration héritée restent hors périmètre de cette documentation ; ne pas ajouter de contournement ni modifier leur extraction. +Le fichier `docker-compose.prod.yml` consomme quatre images publiées sous `gitea.anthonybouteiller.ovh/blomios/tradarr-{backend,frontend,scraper,laya}`. `TRADARR_IMAGE_TAG` est obligatoire et commun aux quatre images ; aucun build ne s’exécute côté serveur. PostgreSQL, Byparr et Ollama restent tiers. Le montage `/home/anthony/.claude:/root/.claude` et le délai d’arrêt backend de cinq minutes sont conservés. + +### Construction et publication + +Depuis la racine, avec Python 3, Git et Docker/BuildKit disponibles : + +```sh +python3 scripts/publish-images.py --dry-run +python3 scripts/publish-images.py +python3 scripts/publish-images.py --tag v1.2.0 --dry-run --push +# Après authentification séparée : publication explicite +python3 scripts/publish-images.py --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. + +Authentifier séparément l’opérateur avec `docker login gitea.anthonybouteiller.ovh` (saisie interactive du jeton, ou `--password-stdin` via un gestionnaire de secrets). Configurer Docker avec un credential helper et les droits de publication nécessaires. Ne jamais fournir de secret dans le tag, la commande, les labels ou le dépôt. Le script ne lit ni ne journalise les credentials ; la sortie Docker est masquée pour éviter d’exposer des diagnostics sensibles. Les `.dockerignore` excluent dotenv, clés et répertoires de credentials courants ; aucun secret ne doit être placé dans les sources copiées dans une image. + +Sur le serveur, authentifier Docker séparément avec accès en lecture, puis définir `TRADARR_IMAGE_TAG` à la version intégralement publiée, ainsi que les variables applicatives obligatoires décrites plus haut : + +```sh +docker compose -f docker-compose.prod.yml config --quiet +docker compose -f docker-compose.prod.yml pull +docker compose -f docker-compose.prod.yml up -d --no-build +``` + +Ne pas combiner les deux fichiers Compose : la production s’utilise seule. Pour revenir à une version publiée, rétablir son tag et relancer pull/up sans supprimer de volume. Cette opération ne remplace pas une stratégie de restauration des migrations/données. Aucun mécanisme d’extraction du récupérateur n’est modifié. ## Premier compte et administration @@ -37,7 +63,7 @@ Laya utilise le [serveur officiel v0.5.2](https://github.com/NandhaKishorM/laya/ Variables backend : `LAYA_URL` (défaut `http://laya:8000`), `LAYA_TIMEOUT` (défaut `120s`, durée positive ≤10 minutes) et `LAYA_API_KEY` (optionnelle, bearer partagé avec le service). Lors d’un échec, un log applicatif indique la cause assainie (`HTTP status 503`, `timeout`, réponse invalide, etc.). Aucun corps de réponse, prompt, article, URL fournisseur ou secret n’est journalisé par cet adapter. Le timeout couvre tous les lots d’un appel. `title_content` indique explicitement `content_fallback=title_only` si le contenu manque ; aucun contenu n’est récupéré ou fabriqué. -Compose standard et production construisent le Dockerfile officiel CPU à ce commit, préchargent uniquement `multilingual` (`LAYA_MODELS`, `LAYA_PRELOAD=1`) et utilisent les révisions de poids épinglées fournies par la release (`LAYA_REVISION=reviewed`). `laya_model_cache` conserve les poids ; ne pas supprimer ce volume pour une simple relance. `LAYA_THREADS` (Compose, défaut 4) limite les threads CPU. Le healthcheck authentifié contrôle CPU et checkpoint résident. Laya reste sur le réseau interne. Le premier démarrage nécessite un accès au registre de paquets et au fournisseur de poids ; aucun modèle n’a été lancé pendant les tests backend. La construction distante requiert le réseau et Docker/BuildKit. Le Compose production construit désormais le backend local contenant cet adapter ; aucun tag distant n’est créé ou publié. +Le Compose standard et le script de publication construisent le Dockerfile officiel CPU à ce commit. Les deux Compose préchargent uniquement `multilingual` (`LAYA_MODELS`, `LAYA_PRELOAD=1`) et utilisent les révisions de poids épinglées fournies par la release (`LAYA_REVISION=reviewed`). `laya_model_cache` conserve les poids ; ne pas supprimer ce volume pour une simple relance. `LAYA_THREADS` (Compose, défaut 4) limite les threads CPU. Le healthcheck authentifié contrôle CPU et checkpoint résident. Laya reste sur le réseau interne. Le premier démarrage nécessite un accès au registre de paquets et au fournisseur de poids ; aucun modèle n’a été lancé pendant les tests backend. La construction distante requiert le réseau et Docker/BuildKit. Le Compose production utilise les images publiées explicitement avec le script ci-dessus. Configurer les connexions fournisseurs puis les paires provider/modèle dans le catalogue admin `/api/admin/ai-models`. Chaque utilisateur choisit un `summary_model_id` dans ses préférences, via la liste sans secrets `/api/me/summary-models`. Les comptes créés après migration n’ont aucun choix par défaut. Les anciens réglages `ai_role_*`, provider.model et is_active sont conservés, mais ne sélectionnent plus le modèle de génération. Les endpoints legacy summary-role restent compatibles pour stockage uniquement ; filter/report sont refusés. Aucun rôle/provider Q&A n’est appelé. diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000..cbb1906 --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,14 @@ +# Keep credentials and host artifacts out of the build context. +.env +.env.* +**/.env +**/.env.* +.git +.aws +.claude +**/*.pem +**/*.key +node_modules +dist +coverage +__pycache__ diff --git a/scraper-service/.dockerignore b/scraper-service/.dockerignore new file mode 100644 index 0000000..cbb1906 --- /dev/null +++ b/scraper-service/.dockerignore @@ -0,0 +1,14 @@ +# Keep credentials and host artifacts out of the build context. +.env +.env.* +**/.env +**/.env.* +.git +.aws +.claude +**/*.pem +**/*.key +node_modules +dist +coverage +__pycache__ diff --git a/scripts/publish-images.py b/scripts/publish-images.py new file mode 100755 index 0000000..e234c4c --- /dev/null +++ b/scripts/publish-images.py @@ -0,0 +1,64 @@ +#!/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) diff --git a/scripts/test_publish_images.py b/scripts/test_publish_images.py new file mode 100644 index 0000000..2720604 --- /dev/null +++ b/scripts/test_publish_images.py @@ -0,0 +1,62 @@ +import importlib.util +import pathlib +import subprocess +import unittest +from unittest.mock import patch + +SCRIPT = pathlib.Path(__file__).with_name('publish-images.py') + +class PublishTests(unittest.TestCase): + def test_publication_contract(self): + spec = importlib.util.spec_from_file_location('publish', SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + sha = 'a' * 40 + for args, builds, pushes in [([], 4, 0), (['--push'], 4, 4), (['--dry-run', '--push'], 0, 0)]: + 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'] + self.assertEqual(sum(c[1] == 'build' for c in docker), builds) + self.assertEqual(sum(c[1] == 'push' for c in docker), pushes) + for cmd in docker: + self.assertTrue(any(sha in arg for arg in cmd)) + if builds: + laya = docker[3] + self.assertIn('TORCH_INDEX=cpu', laya) + self.assertTrue(laya[-1].endswith(module.LAYA_REVISION)) + for cmd in docker[:4]: + for label in ['source', 'revision', 'version']: + self.assertTrue(any(a.startswith('org.opencontainers.image.' + label + '=') for a in cmd)) + + def test_failed_build_prevents_all_pushes(self): + spec = importlib.util.spec_from_file_location('publish', SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + calls = [] + def run(cmd, **kwargs): + calls.append(cmd) + if cmd[:2] == ['docker', 'build']: + raise subprocess.CalledProcessError(1, cmd) + return subprocess.CompletedProcess(cmd, 0, stdout='a' * 40) + with patch.object(module.subprocess, 'run', side_effect=run): + with self.assertRaises(subprocess.CalledProcessError): + module.main(['--push', '--tag', 'v2']) + self.assertFalse(any(c[:2] == ['docker', 'push'] for c in calls)) + self.assertIn(module.REGISTRY + '/tradarr-backend:v2', calls[-1]) + + 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__': + unittest.main()