diff --git a/ansible/.ssh/omnex b/ansible/.ssh/omnex new file mode 100644 index 0000000..6f54daf --- /dev/null +++ b/ansible/.ssh/omnex @@ -0,0 +1,7 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACCWjBZrCPtCi8oAl32aed/Nm6iqVNOHOdaySen6B5jwogAAAIhX0UinV9FI +pwAAAAtzc2gtZWQyNTUxOQAAACCWjBZrCPtCi8oAl32aed/Nm6iqVNOHOdaySen6B5jwog +AAAEDBdRokUMkqZcgLXREfafmo/ZEMPhjPPZq5I/447cPZW5aMFmsI+0KLygCXfZp5382b +qKpU04c51rJJ6foHmPCiAAAAAAECAwQF +-----END OPENSSH PRIVATE KEY----- diff --git a/ansible/ansible.cfg b/ansible/ansible.cfg new file mode 100644 index 0000000..ca8c8e7 --- /dev/null +++ b/ansible/ansible.cfg @@ -0,0 +1,3 @@ +[defaults] +inventory = inventory/host.ini +host_key_checking = False diff --git a/ansible/inventory/group_vars/all/vars.yml b/ansible/inventory/group_vars/all/vars.yml new file mode 100644 index 0000000..b51728b --- /dev/null +++ b/ansible/inventory/group_vars/all/vars.yml @@ -0,0 +1,2 @@ +ansible_user: xor +ansible_password: xor diff --git a/ansible/inventory/group_vars/dev/vars.yml b/ansible/inventory/group_vars/dev/vars.yml new file mode 100644 index 0000000..5c3ade4 --- /dev/null +++ b/ansible/inventory/group_vars/dev/vars.yml @@ -0,0 +1,4 @@ +docker_user: "{{ ansible_user }}" +docker_group: docker +ansible_user: ubuntu +docker_dir: /home/ubuntu/docker diff --git a/ansible/inventory/group_vars/k3s-prod/vars.yml b/ansible/inventory/group_vars/k3s-prod/vars.yml new file mode 100644 index 0000000..8411a89 --- /dev/null +++ b/ansible/inventory/group_vars/k3s-prod/vars.yml @@ -0,0 +1,5 @@ +# Version K3s installée sur master-prod et slaves-prod (voir +# playbook-cluster.yml). Groupe "k3s-prod" défini dans inventory/host.ini +# (children: master-prod + slaves-prod) — group_vars/ n'est chargé que +# pour les hôtes membres d'un groupe qui existe réellement. +k3s_version: "v1.30.1+k3s1" diff --git a/ansible/inventory/group_vars/omnex-prod/vars.yml b/ansible/inventory/group_vars/omnex-prod/vars.yml new file mode 100644 index 0000000..e038239 --- /dev/null +++ b/ansible/inventory/group_vars/omnex-prod/vars.yml @@ -0,0 +1,15 @@ +docker_user: "{{ ansible_user }}" +docker_group: docker +ansible_user: omnex +docker_dir: /home/omnex/docker +helm_link: https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 +deploy_dir: /home/omnex/deploy +# Utilisées par playbook-certbot.yml : certificat du site omnex lui-même +# (nginx sur ce serveur, HTTP-01 via le plugin certbot --nginx). Les +# sous-domaines de démo (*.omnex.sbs) ne passent PAS par ce playbook : ils +# sont couverts par le certificat wildcard émis dans le cluster k8s via +# cert-manager + DNS-01 (voir deploy/cert-manager/wildcard-certificate.yml) +# — un wildcard ne peut pas être validé en HTTP-01, donc pas la peine de le +# lister ici. +domain_name: omnex.sbs +subdomains: [] diff --git a/ansible/inventory/host.ini b/ansible/inventory/host.ini new file mode 100644 index 0000000..b7eaa9d --- /dev/null +++ b/ansible/inventory/host.ini @@ -0,0 +1,35 @@ +[master-dev] +xor-master ansible_host=192.168.1.31 + +[slaves-dev] +xor-slaves-2 ansible_host=192.168.1.44 +xor-slaves-3 ansible_host=192.168.1.45 +xor-slave-4 ansible_host=192.168.1.43 + +[dev:children] +slaves-dev + +[all:vars] +ansible_user=xor +ansible_password=xor + + +[master-prod] +master-k3s ansible_host=176.116.0.189 ansible_user=omnex ansible_ssh_private_key_file=.ssh/omnex ansible_become_pass=aiQgIAcCVIy1E33ReRssfm414dm + +[slaves-prod] +slave-1-k3s ansible_host=93.185.167.134 ansible_user=omnex ansible_ssh_private_key_file=.ssh/omnex ansible_become_pass=aiQgIAcCVIy1E33ReRssfm414dm +slave-2-k3s ansible_host=185.139.215.125 ansible_user=omnex ansible_ssh_private_key_file=.ssh/omnex ansible_become_pass=aiQgIAcCVIy1E33ReRssfm414dm +slave-3-k3s ansible_host=5.252.20.74 ansible_user=omnex ansible_ssh_private_key_file=.ssh/omnex ansible_become_pass=aiQgIAcCVIy1E33ReRssfm414dm + + +[omnex-prod] +prod-server ansible_host=132.243.166.157 ansible_user=omnex ansible_ssh_private_key_file=.ssh/omnex ansible_become_pass=aiQgIAcCVIy1E33ReRssfm414dm + +# Regroupe master-prod + slaves-prod : nécessaire pour que group_vars/k3s-prod +# (k3s_version, voir playbook-cluster.yml) s'applique aux deux. Ansible ne +# charge group_vars/ QUE pour les hôtes membres d'un groupe qui +# existe réellement dans l'inventaire. +[k3s-prod:children] +master-prod +slaves-prod diff --git a/ansible/playbook-certbot.yml b/ansible/playbook-certbot.yml new file mode 100644 index 0000000..86f44c7 --- /dev/null +++ b/ansible/playbook-certbot.yml @@ -0,0 +1,127 @@ +--- +- name: Génération du certificat SSL Let's Encrypt + hosts: omnex-prod + become: true + gather_facts: false + + tasks: + - name: Installer certbot et le plugin nginx + ansible.builtin.apt: + name: + - certbot + - python3-certbot-nginx + - nginx + state: present + update_cache: yes + + - name: Déployer la config Nginx HTTP simple (ACME challenge) + ansible.builtin.copy: + dest: /etc/nginx/sites-available/certbot + content: | + server { + listen 80; + listen [::]:80; + server_name {{ domain_name }} {{ subdomains | join(' ') }}; + + location /.well-known/acme-challenge/ { + root /var/www/html; + } + + location / { + return 200 'ok'; + add_header Content-Type text/plain; + } + } + + - name: Activer le site certbot + ansible.builtin.file: + src: /etc/nginx/sites-available/certbot + dest: /etc/nginx/sites-enabled/certbot + state: link + force: yes + + - name: Désactiver le site par défaut + ansible.builtin.file: + path: /etc/nginx/sites-enabled/default + state: absent + + - name: Tester la configuration Nginx + ansible.builtin.command: nginx -t + changed_when: false + + - name: Redémarrer Nginx + ansible.builtin.systemd: + name: nginx + state: restarted + enabled: yes + + - name: Ouvrir les ports dans UFW + ansible.builtin.ufw: + rule: allow + port: "{{ item }}" + proto: tcp + loop: + - "22" + - "80" + - "443" + + - name: Vérifier si le certificat existe déjà + ansible.builtin.stat: + path: "/etc/letsencrypt/live/{{ domain_name }}/fullchain.pem" + register: cert_file + tags: [gen] + + - name: Générer le certificat avec Certbot (domaine + sous-domaines) + ansible.builtin.command: > + certbot certonly --nginx + -d {{ domain_name }} + {{ subdomains | map('regex_replace', '^(.*)$', '-d \1') | join(' ') }} + --non-interactive + --agree-tos + --email admin@{{ domain_name }} + when: not cert_file.stat.exists + tags: [gen] + + - name: Vérifier que le certificat a bien été généré + ansible.builtin.stat: + path: "/etc/letsencrypt/live/{{ domain_name }}/fullchain.pem" + register: cert_check + + - name: Afficher le résultat + ansible.builtin.debug: + msg: "{{ 'Certificat généré : /etc/letsencrypt/live/' + domain_name + '/fullchain.pem' if cert_check.stat.exists else 'ERREUR : certificat non trouvé' }}" + + - name: Vérifier le renouvellement automatique + ansible.builtin.command: certbot renew --dry-run + changed_when: false + failed_when: false + when: cert_check.stat.exists + + - name: Créer le dossier docker/certs + ansible.builtin.file: + path: "{{ docker_dir }}/nginx/certs" + state: directory + owner: "{{ docker_user }}" + group: "{{ docker_group }}" + mode: "0750" + tags: [create] + + - name: Copier fullchain.pem dans docker/certs + ansible.builtin.copy: + src: "/etc/letsencrypt/live/{{ domain_name }}/fullchain.pem" + dest: "{{ docker_dir }}/nginx/certs/fullchain.pem" + owner: "{{ docker_user }}" + group: "{{ docker_group }}" + mode: "0644" + remote_src: yes + tags: [create] + + - name: Copier privkey.pem dans docker/certs + ansible.builtin.copy: + src: "/etc/letsencrypt/live/{{ domain_name }}/privkey.pem" + dest: "{{ docker_dir }}/nginx/certs/privkey.pem" + owner: "{{ docker_user }}" + group: "{{ docker_group }}" + mode: "0640" + remote_src: yes + tags: [create] diff --git a/ansible/playbook-cluster.yml b/ansible/playbook-cluster.yml new file mode 100644 index 0000000..66d5e0a --- /dev/null +++ b/ansible/playbook-cluster.yml @@ -0,0 +1,217 @@ +--- +- name: Installation du cluster K3s - Master + hosts: master-prod + become: true + vars: + k3s_token_file: /var/lib/rancher/k3s/server/node-token + tasks: + - name: Mettre à jour les paquets + ansible.builtin.apt: + update_cache: yes + upgrade: yes + + - name: Installer les dépendances + ansible.builtin.apt: + name: + - curl + - apt-transport-https + state: present + + # Nécessaire pour changer le backend CNI (flannel -> aucun, Calico prend + # le relais) sur un serveur déjà installé : le script officiel ne relit + # pas les flags d'exécution une fois k3s présent (voir "creates" ci- + # dessous). Idempotent : le script d'uninstall se supprime lui-même, + # donc "removes" ne matche plus au run suivant et cette tâche est skip. + - name: Désinstaller K3s existant (pour changer les flags CNI) + ansible.builtin.shell: /usr/local/bin/k3s-uninstall.sh + args: + removes: /usr/local/bin/k3s-uninstall.sh + + # --flannel-backend=none + --disable-network-policy : CNI géré + # entièrement par Calico (deploy/cni/calico-install.yml), pas de conflit + # avec le contrôleur de NetworkPolicy intégré à k3s (kube-router). + # --cluster-cidr doit correspondre à l'ipPool Calico (192.168.0.0/16, + # voir deploy/cni/calico-install.yml) — cette même plage est déjà + # anticipée comme bloquée par deploy/chart-gestion/network-policy + # (blockedEgressCIDRs), donc aucun autre fichier à changer. + # --tls-san=ansible_host : IP publique du master, pour que le + # kubeconfig généré pour le control-plane (omnex-prod) valide le + # certificat du serveur API sans passer par 127.0.0.1. + - name: Installer le serveur K3s + ansible.builtin.shell: | + curl -sfL https://get.k3s.io | INSTALL_K3S_VERSION={{ k3s_version }} sh -s - server \ + --flannel-backend=none --disable-network-policy \ + --cluster-cidr=192.168.0.0/16 --tls-san={{ ansible_host }} + args: + creates: /usr/local/bin/k3s + + - name: Définir l'URL du serveur K3s + ansible.builtin.set_fact: + k3s_server_url: "https://{{ ansible_host }}:6443" + + - name: Récupérer le token du cluster + ansible.builtin.slurp: + src: "{{ k3s_token_file }}" + register: k3s_token_raw + + - name: Définir le token en variable + ansible.builtin.set_fact: + k3s_token: "{{ k3s_token_raw.content | b64decode | trim }}" + +- name: Installation du cluster K3s - Workers + hosts: slaves-prod + become: true + vars: + # On récupère dynamiquement le premier hôte du groupe master-prod + # (nom du groupe défini dans inventory/host.ini — "master" n'existe pas). + k3s_token: "{{ hostvars[groups['master-prod'][0]]['k3s_token'] }}" + k3s_server_url: "{{ hostvars[groups['master-prod'][0]]['k3s_server_url'] }}" + tasks: + - name: Mettre à jour les paquets + ansible.builtin.apt: + update_cache: yes + upgrade: yes + + - name: Installer les dépendances + ansible.builtin.apt: + name: + - curl + - apt-transport-https + state: present + + # Idempotent, même logique que côté master : permet de rejoindre le + # master reconstruit (nouveau token après désinstallation ci-dessus). + - name: Désinstaller l'agent K3s existant (pour rejoindre avec le nouveau token) + ansible.builtin.shell: /usr/local/bin/k3s-agent-uninstall.sh + args: + removes: /usr/local/bin/k3s-agent-uninstall.sh + + - name: Joindre le nœud au cluster K3s + ansible.builtin.shell: | + curl -sfL https://get.k3s.io | K3S_URL={{ k3s_server_url }} K3S_TOKEN={{ k3s_token }} INSTALL_K3S_VERSION={{ k3s_version }} sh - + args: + creates: /usr/local/bin/k3s-agent + +- name: Installation et configuration de Docker + hosts: master-prod,slaves-prod + become: true + gather_facts: true + + vars: + docker_group: docker + + tasks: + + - name: Update apt cache + ansible.builtin.apt: + update_cache: true + cache_valid_time: 3600 + + - name: Install required packages + ansible.builtin.apt: + name: + - ca-certificates + - curl + - gnupg + - lsb-release + - acl + state: present + tags: docker + + - name: Create directory for Docker GPG key + ansible.builtin.file: + path: /etc/apt/keyrings + state: directory + mode: "0755" + tags: docker + + - name: Download Docker GPG key + ansible.builtin.get_url: + url: https://download.docker.com/linux/debian/gpg + dest: /tmp/docker.asc + mode: "0644" + tags: docker + + - name: Convert Docker GPG key + ansible.builtin.command: + cmd: gpg --dearmor -o /etc/apt/keyrings/docker.gpg /tmp/docker.asc + args: + creates: /etc/apt/keyrings/docker.gpg + tags: docker + + - name: Set Docker GPG key permissions + ansible.builtin.file: + path: /etc/apt/keyrings/docker.gpg + mode: "0644" + tags: docker + + - name: Add Docker Debian repository + ansible.builtin.apt_repository: + repo: >- + deb [arch={{ 'arm64' if ansible_architecture == 'aarch64' + else 'armhf' if ansible_architecture == 'armv7l' + else 'amd64' }} + signed-by=/etc/apt/keyrings/docker.gpg] + https://download.docker.com/linux/{{ ansible_distribution | lower }} + {{ ansible_distribution_release }} + stable + state: present + filename: docker + tags: docker + + - name: Update apt cache after adding Docker repository + ansible.builtin.apt: + update_cache: true + tags: docker + + - name: Install Docker packages + ansible.builtin.apt: + name: + - docker-ce + - docker-ce-cli + - containerd.io + - docker-buildx-plugin + - docker-compose-plugin + state: present + tags: docker + + - name: Ensure Docker service is started + ansible.builtin.systemd: + name: docker + state: started + enabled: true + tags: docker + + - name: Create docker group + ansible.builtin.group: + name: docker + state: present + tags: docker + + - name: Add Ansible user to docker group + ansible.builtin.user: + name: "{{ ansible_user }}" + groups: docker + append: true + tags: docker + + - name: Verify Docker installation + ansible.builtin.command: + cmd: docker --version + register: docker_version + changed_when: false + tags: docker + + - name: Verify Docker Compose installation + ansible.builtin.command: + cmd: docker compose version + register: compose_version + changed_when: false + tags: docker + + - name: Display Docker versions + ansible.builtin.debug: + msg: + - "{{ docker_version.stdout }}" + - "{{ compose_version.stdout }}" + tags: docker diff --git a/ansible/playbook-deploy-site.yml b/ansible/playbook-deploy-site.yml new file mode 100644 index 0000000..d74ca8d --- /dev/null +++ b/ansible/playbook-deploy-site.yml @@ -0,0 +1,266 @@ +- name: Installation et configuration de Docker + hosts: omnex-prod + become: true + gather_facts: true + + vars: + docker_group: docker + + tasks: + + - name: Update apt cache + ansible.builtin.apt: + update_cache: true + cache_valid_time: 3600 + + - name: Install required packages + ansible.builtin.apt: + name: + - ca-certificates + - curl + - gnupg + - lsb-release + - acl + state: present + tags: docker + + - name: Create directory for Docker GPG key + ansible.builtin.file: + path: /etc/apt/keyrings + state: directory + mode: "0755" + tags: docker + + - name: Download Docker GPG key + ansible.builtin.get_url: + url: https://download.docker.com/linux/debian/gpg + dest: /tmp/docker.asc + mode: "0644" + tags: docker + + - name: Convert Docker GPG key + ansible.builtin.command: + cmd: gpg --dearmor -o /etc/apt/keyrings/docker.gpg /tmp/docker.asc + args: + creates: /etc/apt/keyrings/docker.gpg + tags: docker + + - name: Set Docker GPG key permissions + ansible.builtin.file: + path: /etc/apt/keyrings/docker.gpg + mode: "0644" + tags: docker + + - name: Add Docker Debian repository + ansible.builtin.apt_repository: + repo: >- + deb [arch={{ 'arm64' if ansible_architecture == 'aarch64' + else 'armhf' if ansible_architecture == 'armv7l' + else 'amd64' }} + signed-by=/etc/apt/keyrings/docker.gpg] + https://download.docker.com/linux/{{ ansible_distribution | lower }} + {{ ansible_distribution_release }} + stable + state: present + filename: docker + tags: docker + + - name: Update apt cache after adding Docker repository + ansible.builtin.apt: + update_cache: true + tags: docker + + - name: Install Docker packages + ansible.builtin.apt: + name: + - docker-ce + - docker-ce-cli + - containerd.io + - docker-buildx-plugin + - docker-compose-plugin + state: present + tags: docker + + - name: Ensure Docker service is started + ansible.builtin.systemd: + name: docker + state: started + enabled: true + tags: docker + + - name: Create docker group + ansible.builtin.group: + name: docker + state: present + tags: docker + + - name: Add Ansible user to docker group + ansible.builtin.user: + name: "{{ ansible_user }}" + groups: docker + append: true + tags: docker + + - name: Verify Docker installation + ansible.builtin.command: + cmd: docker --version + register: docker_version + changed_when: false + tags: docker + + - name: Verify Docker Compose installation + ansible.builtin.command: + cmd: docker compose version + register: compose_version + changed_when: false + tags: docker + + - name: Display Docker versions + ansible.builtin.debug: + msg: + - "{{ docker_version.stdout }}" + - "{{ compose_version.stdout }}" + tags: docker + + - name: Ensure parent directory has correct permissions + ansible.builtin.file: + path: "{{ docker_dir }}" + state: directory + owner: "{{ docker_user }}" + group: "{{ docker_group }}" + mode: "0755" + tags: project + + - name: Copier le fichier docker-compose.yml + ansible.builtin.copy: + src: ../docker/docker-compose.yml + dest: "{{ docker_dir }}/docker-compose.yml" + owner: root + group: root + mode: "0644" + notify: Redémarrer la stack + + - name: Copier le contexte de build du WAF (Dockerfile + config nginx/ModSecurity) + ansible.builtin.copy: + src: ../docker/waf/ + dest: "{{ docker_dir }}/waf/" + owner: root + group: root + mode: "0644" + notify: Redémarrer la stack + + - name: Set correct permissions for Docker files + ansible.builtin.file: + path: "{{ docker_dir }}" + owner: "{{ docker_user }}" + group: "{{ docker_group }}" + recurse: yes + tags: project + + - name: Set permissions for .env file + ansible.builtin.file: + path: "{{ docker_dir }}/.env" + owner: "{{ docker_user }}" + group: "{{ docker_group }}" + mode: "0640" + tags: project + ignore_errors: yes + + - name: Create certs folder + ansible.builtin.file: + path: "{{ docker_dir }}/certs" + state: directory + owner: "{{ docker_user }}" + group: "{{ docker_group }}" + mode: "0750" + tags: project + + - name: Copy certs in docker/certs + ansible.builtin.copy: + src: "/etc/letsencrypt/live/omnex.sbs/{{ item }}" + dest: /home/omnex/docker/certs + owner: "{{ docker_user }}" + group: "{{ docker_group }}" + remote_src: true + mode: "0640" + loop: + - fullchain.pem + - privkey.pem + tags: project + + # Monté en fichier sur /kubeconfig/config (KUBECONFIG_HOST_PATH dans .env + # = {{ docker_dir }}/kubeconfig/config). L'API tourne en uid 10001 dans son + # conteneur (voir control-plane/api/Dockerfile) : le fichier doit lui + # appartenir, sinon "permission denied" au démarrage. Le token qu'il + # contient reste illisible pour tout autre utilisateur (0400). + - name: Create kubeconfig folder + ansible.builtin.file: + path: "{{ docker_dir }}/kubeconfig" + state: directory + owner: root + group: root + mode: "0755" + tags: project + + - name: Copy kubeconfig + ansible.builtin.template: + src: templates/kubeconfig.j2 + dest: "{{ docker_dir }}/kubeconfig/config" + owner: "10001" + group: "10001" + mode: "0400" + tags: project + + # Slash final : copie le CONTENU de deploy/ dans deploy_dir. Sans lui, Ansible + # crée deploy_dir/deploy/, alors que le compose monte ../deploy/chart-gestion + # et ../deploy/chart-vitrine (donc l'ancienne copie non mise à jour). + - name: Add deploy folder + ansible.builtin.copy: + src: ../deploy/ + dest: "{{ deploy_dir }}" + owner: "{{ docker_user }}" + group: "{{ docker_user }}" + mode: "0750" + tags: project + + - name: Lancer la stack Docker Compose + community.docker.docker_compose_v2: + project_src: "{{ docker_dir }}" + state: present + pull: always + build: always # le service "waf" se build localement (pas d'image sur un registre) + tags: start + + - name: Vérifier si Helm est déjà installé + ansible.builtin.command: helm version --short + register: helm_check + changed_when: false + failed_when: false + tags: helm + + - name: Télécharger le script d'installation officiel de Helm + ansible.builtin.get_url: + url: "{{ helm_link }}" + dest: /tmp/get_helm.sh + mode: "0700" + when: helm_check.rc != 0 + tags: helm + + - name: Installer Helm via le script officiel + ansible.builtin.command: /tmp/get_helm.sh + when: helm_check.rc != 0 + tags: helm + + - name: Nettoyer le script d'installation + ansible.builtin.file: + path: /tmp/get_helm.sh + state: absent + when: helm_check.rc != 0 + tags: helm + + handlers: + - name: Redémarrer la stack + community.docker.docker_compose_v2: + project_src: "{{ docker_dir }}" + state: restarted + tags: helm diff --git a/ansible/playbook-docker.yml b/ansible/playbook-docker.yml new file mode 100644 index 0000000..923b7eb --- /dev/null +++ b/ansible/playbook-docker.yml @@ -0,0 +1,123 @@ +- name: Installation et configuration de Docker + hosts: dev + become: true + gather_facts: true + + vars: + docker_group: docker + + tasks: + + - name: Update apt cache + ansible.builtin.apt: + update_cache: true + cache_valid_time: 3600 + + - name: Install required packages + ansible.builtin.apt: + name: + - ca-certificates + - curl + - gnupg + - lsb-release + - acl + state: present + tags: docker + + - name: Create directory for Docker GPG key + ansible.builtin.file: + path: /etc/apt/keyrings + state: directory + mode: "0755" + tags: docker + + - name: Download Docker GPG key + ansible.builtin.get_url: + url: https://download.docker.com/linux/debian/gpg + dest: /tmp/docker.asc + mode: "0644" + tags: docker + + - name: Convert Docker GPG key + ansible.builtin.command: + cmd: gpg --dearmor -o /etc/apt/keyrings/docker.gpg /tmp/docker.asc + args: + creates: /etc/apt/keyrings/docker.gpg + tags: docker + + - name: Set Docker GPG key permissions + ansible.builtin.file: + path: /etc/apt/keyrings/docker.gpg + mode: "0644" + tags: docker + + - name: Add Docker Debian repository + ansible.builtin.apt_repository: + repo: >- + deb [arch={{ 'arm64' if ansible_architecture == 'aarch64' + else 'armhf' if ansible_architecture == 'armv7l' + else 'amd64' }} + signed-by=/etc/apt/keyrings/docker.gpg] + https://download.docker.com/linux/{{ ansible_distribution | lower }} + {{ ansible_distribution_release }} + stable + state: present + filename: docker + tags: docker + + - name: Update apt cache after adding Docker repository + ansible.builtin.apt: + update_cache: true + tags: docker + + - name: Install Docker packages + ansible.builtin.apt: + name: + - docker-ce + - docker-ce-cli + - containerd.io + - docker-buildx-plugin + - docker-compose-plugin + state: present + tags: docker + + - name: Ensure Docker service is started + ansible.builtin.systemd: + name: docker + state: started + enabled: true + tags: docker + + - name: Create docker group + ansible.builtin.group: + name: docker + state: present + tags: docker + + - name: Add Ansible user to docker group + ansible.builtin.user: + name: "{{ ansible_user }}" + groups: docker + append: true + tags: docker + + - name: Verify Docker installation + ansible.builtin.command: + cmd: docker --version + register: docker_version + changed_when: false + tags: docker + + - name: Verify Docker Compose installation + ansible.builtin.command: + cmd: docker compose version + register: compose_version + changed_when: false + tags: docker + + - name: Display Docker versions + ansible.builtin.debug: + msg: + - "{{ docker_version.stdout }}" + - "{{ compose_version.stdout }}" + tags: docker diff --git a/ansible/templates/kubeconfig.j2 b/ansible/templates/kubeconfig.j2 new file mode 100644 index 0000000..f3c8db6 --- /dev/null +++ b/ansible/templates/kubeconfig.j2 @@ -0,0 +1,18 @@ +apiVersion: v1 +kind: Config +clusters: + - name: omnex-k3s + cluster: + server: https://176.116.0.189:6443 + certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJkekNDQVIyZ0F3SUJBZ0lCQURBS0JnZ3Foa2pPUFFRREFqQWpNU0V3SHdZRFZRUUREQmhyTTNNdGMyVnkKZG1WeUxXTmhRREUzT0RZNU9ESXhNVEF3SGhjTk1qWXdPREUzTVRVMU5URXdXaGNOTXpZd09ERTBNVFUxTlRFdwpXakFqTVNFd0h3WURWUVFEREJock0zTXRjMlZ5ZG1WeUxXTmhRREUzT0RZNU9ESXhNVEF3V1RBVEJnY3Foa2pPClBRSUJCZ2dxaGtqT1BRTUJCd05DQUFTQ3N2WGwrQVYrL3ByM0ZwTTBIVTdubnZ0SWN5dnlFZC90VklJSllSdloKMytBVVpJZEpmb2ZuR3ZJZDZKRTRpZWtuZS95M05ScVh5bXFhbGdKa0tXUWdvMEl3UURBT0JnTlZIUThCQWY4RQpCQU1DQXFRd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZEJnTlZIUTRFRmdRVTRySWZTS00zTmdvbkd6M1pwR2tYCkluMkVRV2N3Q2dZSUtvWkl6ajBFQXdJRFNBQXdSUUloQU9nT2hBdW51dVJiejU1ZFhoZlIrM2FKRGNkeDZzam4KbUtKVDFJZHQwWG1uQWlCWkdQVm9xTWp5T0lHVXdKVFZYeUxkU2xPWDUvYm5IdExISHBCcitWMVVwZz09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K +contexts: + - name: omnex-control-plane + context: + cluster: omnex-k3s + user: omnex-control-plane + namespace: omnex-system +current-context: omnex-control-plane +users: + - name: omnex-control-plane + user: + token: eyJhbGciOiJSUzI1NiIsImtpZCI6InFJYUNVM0MxNlhia0F2clpETXVjMUFjWk9yNFhyWWtSUWt4S3NQSi1hUjgifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJvbW5leC1zeXN0ZW0iLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoib21uZXgtY29udHJvbC1wbGFuZS10b2tlbiIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJvbW5leC1jb250cm9sLXBsYW5lIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiYTA5NDBiYjItNzM3OC00MDRlLWI2MGQtMGM0NTk1YzMxMTRkIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Om9tbmV4LXN5c3RlbTpvbW5leC1jb250cm9sLXBsYW5lIn0.ui6EFCyLp8Su_JE7ctAfgvMjKwsVsysBtYyE1ktxLuPchW7jM8omJYionYITXw4176ZifbFOk-f7HeiJldubzhtklz1BrOBx-BjrR6hIzfCyUeVxvGKXoTOiWsf2W2qxy8DO4joNnAw73ESMWXW2LXQ3D3r_c9LJGnp65BYzBiHKAnX33OINqmIKx8YMT6i9086U69VHU4RkXr-kW93f3doX0v7CH3OP4mOJ2xsE-PjGy_LhLjcXBiRP-jpnM6Pe5GYphS6yWWUmGe5K0uUvrcXkxJrdk552Yi_-_8DiNSDUItSROmrpeHo916K26te4fWM17BUNClTwG9wV-gD2TQ diff --git a/control-plane/api/cmd/api/main.go b/control-plane/api/cmd/api/main.go index 185568b..bdb3141 100644 --- a/control-plane/api/cmd/api/main.go +++ b/control-plane/api/cmd/api/main.go @@ -178,6 +178,9 @@ func main() { Domain: cfg.VitrineDomain, // Un client ne peut pas revendiquer un domaine d'Omnex (démos). ReservedDomains: []string{cfg.DemoDomain}, + // Incidents projets vers le Discord / Telegram de chaque admin (sans + // base, pas de réglages : l'alerte reste dans les logs). + Alert: projectAlert(alertRecipients), }) go projectSvc.RunExpirationLoop(context.Background(), 5*time.Minute) @@ -253,3 +256,12 @@ func main() { log.Printf("extinction forcée après délai: %v", err) } } + +// projectAlert adapte les destinataires d'alertes au hook Alert des projets. +// nil si aucun destinataire n'est résolvable (mode mémoire). +func projectAlert(recipients func(ctx context.Context) ([]alerts.Notifier, error)) func(string) { + if recipients == nil { + return nil + } + return func(message string) { alerts.Broadcast(recipients, message) } +} diff --git a/control-plane/api/internal/alerts/broadcast.go b/control-plane/api/internal/alerts/broadcast.go new file mode 100644 index 0000000..a90e5fe --- /dev/null +++ b/control-plane/api/internal/alerts/broadcast.go @@ -0,0 +1,35 @@ +package alerts + +import ( + "context" + "log" + "time" +) + +// broadcastTimeout borne l'envoi d'une alerte ponctuelle (résolution des +// destinataires en base + appels HTTP Discord/Telegram). +const broadcastTimeout = 20 * time.Second + +// Broadcast envoie message à tous les destinataires actuels (admins ayant +// renseigné un webhook Discord et/ou un bot Telegram). Les destinataires sont +// résolus à l'appel : un changement de réglages est pris en compte sans +// redémarrage. Les erreurs sont journalisées, jamais renvoyées — une alerte +// qui échoue ne doit pas faire échouer l'opération qui l'a déclenchée. +// Bloquant : à appeler dans une goroutine depuis un chemin sensible. +func Broadcast(recipients func(ctx context.Context) ([]Notifier, error), message string) { + ctx, cancel := context.WithTimeout(context.Background(), broadcastTimeout) + defer cancel() + + list, err := recipients(ctx) + if err != nil { + log.Printf("alerts: chargement des destinataires échoué: %v", err) + return + } + if len(list) == 0 { + log.Printf("alerts: aucun destinataire configuré, alerte non envoyée: %s", message) + return + } + if err := MultiNotifier(list).Notify(ctx, message); err != nil { + log.Printf("alerts: envoi de l'alerte échoué: %v", err) + } +} diff --git a/control-plane/api/internal/alerts/broadcast_test.go b/control-plane/api/internal/alerts/broadcast_test.go new file mode 100644 index 0000000..7b09b17 --- /dev/null +++ b/control-plane/api/internal/alerts/broadcast_test.go @@ -0,0 +1,37 @@ +package alerts + +import ( + "context" + "errors" + "sync" + "testing" +) + +type recordingNotifier struct { + mu sync.Mutex + msgs []string + err error +} + +func (r *recordingNotifier) Notify(_ context.Context, message string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.msgs = append(r.msgs, message) + return r.err +} + +func TestBroadcast_DeliversToEveryRecipientEvenIfOneFails(t *testing.T) { + failing := &recordingNotifier{err: errors.New("webhook mort")} + ok := &recordingNotifier{} + Broadcast(func(context.Context) ([]Notifier, error) { return []Notifier{failing, ok}, nil }, "incident") + + if len(failing.msgs) != 1 || len(ok.msgs) != 1 || ok.msgs[0] != "incident" { + t.Errorf("failing=%v ok=%v : l'échec d'un canal a empêché l'autre", failing.msgs, ok.msgs) + } +} + +func TestBroadcast_SwallowsRecipientErrorsAndEmptyLists(t *testing.T) { + // Ne doit ni paniquer ni bloquer. + Broadcast(func(context.Context) ([]Notifier, error) { return nil, errors.New("db indisponible") }, "x") + Broadcast(func(context.Context) ([]Notifier, error) { return nil, nil }, "x") +} diff --git a/control-plane/api/internal/demos/helm_provisioner.go b/control-plane/api/internal/demos/helm_provisioner.go index 0c2a8d9..cce45df 100644 --- a/control-plane/api/internal/demos/helm_provisioner.go +++ b/control-plane/api/internal/demos/helm_provisioner.go @@ -800,12 +800,18 @@ func (h *HelmProvisioner) ensureWorkloadRoleBinding(namespace string) error { return nil } -// deleteNamespace supprime un namespace (avec cascading). +// deleteNamespace supprime un namespace (avec cascading). Idempotent : un +// namespace déjà supprimé (à la main avec kubectl, ou par un appel précédent) +// n'est pas une erreur — sinon la ligne en base reste bloquée en "deleting". func (h *HelmProvisioner) deleteNamespace(name string) error { propagationPolicy := metav1.DeletePropagationForeground - return h.k8sClient.CoreV1().Namespaces().Delete(context.Background(), name, metav1.DeleteOptions{ + err := h.k8sClient.CoreV1().Namespaces().Delete(context.Background(), name, metav1.DeleteOptions{ PropagationPolicy: &propagationPolicy, }) + if k8sErrors.IsNotFound(err) { + return nil + } + return err } // veleroNamespace : namespace fixe où tourne Velero (installé une fois par diff --git a/control-plane/api/internal/demos/project_provisioner.go b/control-plane/api/internal/demos/project_provisioner.go index 108e07c..96b13d6 100644 --- a/control-plane/api/internal/demos/project_provisioner.go +++ b/control-plane/api/internal/demos/project_provisioner.go @@ -7,6 +7,7 @@ import ( "strconv" corev1 "k8s.io/api/core/v1" + k8sErrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -150,6 +151,20 @@ func (h *HelmProvisioner) ProjectState(ctx context.Context, namespace string) (R return buildProjectState(pods.Items, h.podUsage(ctx, namespace)), nil } +// NamespaceExists : le namespace existe-t-il dans le cluster ? Seule une erreur +// « not found » explicite signifie « absent » ; toute autre erreur (API +// injoignable, droits) est renvoyée pour que l'appelant ne conclue rien. +func (h *HelmProvisioner) NamespaceExists(ctx context.Context, namespace string) (bool, error) { + _, err := h.k8sClient.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{}) + if k8sErrors.IsNotFound(err) { + return false, nil + } + if err != nil { + return false, err + } + return true, nil +} + // buildProjectState range les pods d'un projet par composant (voir // ProjectState). usage : nom de pod -> [cpuMilli, memMi]. func buildProjectState(pods []corev1.Pod, usage map[string][2]int64) ResourceState { diff --git a/control-plane/api/internal/projects/models.go b/control-plane/api/internal/projects/models.go index 1031a5a..4f0a6bc 100644 --- a/control-plane/api/internal/projects/models.go +++ b/control-plane/api/internal/projects/models.go @@ -41,30 +41,20 @@ func (s Status) Extendable() bool { } type Project struct { - ID string `gorm:"type:uuid;primaryKey" json:"id"` - ClientName string `gorm:"size:64;not null;index" json:"client_name"` - Status Status `gorm:"size:20;not null;index" json:"status"` - Namespace string `gorm:"size:63;uniqueIndex" json:"namespace"` - Host string `gorm:"size:255" json:"host"` - URL string `gorm:"size:255" json:"url"` - // CustomDomain : domaine du client, servi en plus de Host ("" = aucun). - // URL pointe dessus quand il est défini. - CustomDomain string `gorm:"size:255" json:"custom_domain,omitempty"` - // OwnerUsername : compte client qui a demandé le site ("" = déployé - // directement par l'admin). Donne au client la lecture de son site. - OwnerUsername string `gorm:"size:64;index" json:"owner_username,omitempty"` - - // AdminUsername : compte admin créé dans le backend déployé (le mot de - // passe n'est jamais persisté). AdminNumber : ADMIN_NUMBER du backend. - AdminUsername string `gorm:"size:64" json:"admin_username"` - AdminNumber int `json:"admin_number"` - - // MonthsPurchased : total des mois souscrits (création + renouvellements). - MonthsPurchased int `json:"months_purchased"` - - CreatedAt time.Time `json:"created_at"` - // ExpiresAt : fin de l'abonnement (le projet est alors supprimé). - ExpiresAt time.Time `json:"expires_at"` + ID string `gorm:"type:uuid;primaryKey" json:"id"` + ClientName string `gorm:"size:64;not null;index" json:"client_name"` + Status Status `gorm:"size:20;not null;index" json:"status"` + Namespace string `gorm:"size:63;uniqueIndex" json:"namespace"` + Host string `gorm:"size:255" json:"host"` + URL string `gorm:"size:255" json:"url"` + CustomDomain string `gorm:"size:255" json:"custom_domain,omitempty"` + OwnerUsername string `gorm:"size:64;index" json:"owner_username,omitempty"` + AdminUsername string `gorm:"size:64" json:"admin_username"` + AdminNumber int `json:"admin_number"` + MonthsPurchased int `json:"months_purchased"` + CreatedAt time.Time `json:"created_at"` + ExpiresAt time.Time `json:"expires_at"` + UpdateAt time.Time `json:"update_at"` } func (Project) TableName() string { return "projects" } diff --git a/control-plane/api/internal/projects/service.go b/control-plane/api/internal/projects/service.go index 37736de..503332d 100644 --- a/control-plane/api/internal/projects/service.go +++ b/control-plane/api/internal/projects/service.go @@ -3,6 +3,7 @@ package projects import ( "context" "errors" + "fmt" "log" "net" "regexp" @@ -38,6 +39,7 @@ type Provisioner interface { TeardownProject(namespace string) error UpdateProjectDomain(spec demos.ProjectDomainSpec) error ProjectState(ctx context.Context, namespace string) (demos.ResourceState, error) + NamespaceExists(ctx context.Context, namespace string) (bool, error) } // NoopProvisioner : aucun déploiement réel (dev en mémoire, tests). @@ -49,6 +51,7 @@ func (NoopProvisioner) UpdateProjectDomain(demos.ProjectDomainSpec) error { retu func (NoopProvisioner) ProjectState(context.Context, string) (demos.ResourceState, error) { return demos.ResourceState{}, nil } +func (NoopProvisioner) NamespaceExists(context.Context, string) (bool, error) { return true, nil } // Config du service (injectable pour les tests). type Config struct { @@ -57,6 +60,10 @@ type Config struct { // pas revendiquer comme domaine personnalisé — ceux d'Omnex (démos…). Le // domaine des projets (Domain) est toujours réservé. ReservedDomains []string + // Alert reçoit un message à destination des admins pour les incidents qui + // demandent une intervention (ex. site en ligne dont le namespace a + // disparu). Facultatif ; appelé dans une goroutine, il peut être lent. + Alert func(message string) } // CreateInput : saisie de l'admin Omnex au déploiement (dashboard). @@ -364,6 +371,7 @@ func (s *Service) RunExpirationLoop(ctx context.Context, interval time.Duration) return case <-ticker.C: s.expireOverdue() + s.reconcile() } } } @@ -395,6 +403,95 @@ func (s *Service) applyLifecycle(id string) { log.Printf("projets: %s supprimé (abonnement échu)", p.Namespace) } +// reconcile aligne la base sur le cluster : une ligne dont le namespace n'existe +// plus est purgée, mais seulement quand c'est sans risque (voir reconcileOne). +func (s *Service) reconcile() { + all, err := s.store.List() + if err != nil { + log.Printf("projets: réconciliation, liste échouée: %v", err) + return + } + for _, p := range all { + s.mu.Lock() + s.reconcileOne(p.ID) + s.mu.Unlock() + } +} + +// reconcileOne relit le projet (il a pu changer depuis List) puis compare son +// statut à l'existence réelle de son namespace. À appeler avec s.mu tenu. +func (s *Service) reconcileOne(id string) { + p, ok := s.store.Get(id) + if !ok { + return + } + // Seuls ces statuts ont une raison d'avoir (ou non) un namespace. + // provisioning/pending : le namespace est créé après la ligne, donc son + // absence est normale. failed : on garde la ligne pour que l'admin voie + // l'échec (il la supprime lui-même depuis l'interface). + if p.Status != StatusDeleting && p.Status != StatusDeleted && p.Status != StatusReady { + return + } + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + exists, err := s.prov.NamespaceExists(ctx, p.Namespace) + if err != nil { + // Erreur ≠ « absent » : on ne conclut rien ce tour-ci. + log.Printf("projets: namespace %s non vérifiable: %v", p.Namespace, err) + return + } + if exists { + return // y compris Terminating : Kubernetes n'a pas fini + } + + if p.Status == StatusReady { + // Un projet en ligne sans namespace est un incident : on ne supprime + // jamais la ligne (client payant), on la passe en échec et on le signale. + p.Status = StatusFailed + if _, err := s.store.Update(p); err != nil { + log.Printf("projets: mise en échec de %s échouée: %v", p.Namespace, err) + return + } + log.Printf("projets: ATTENTION %s était en ligne mais son namespace a disparu", p.Namespace) + s.alert(fmt.Sprintf( + "⚠️ Omnex — le site vitrine « %s » (%s) était en ligne mais son namespace %s n'existe plus dans le cluster. "+ + "Il est passé en échec. Vérifiez la suppression manuelle éventuelle et les sauvegardes Velero.", + alertText(p.ClientName), p.Host, p.Namespace)) + return + } + + if err := s.store.Delete(p.ID); err != nil { + log.Printf("projets: purge de %s échouée: %v", p.Namespace, err) + return + } + log.Printf("projets: %s purgé (namespace absent du cluster)", p.Namespace) +} + +// alert transmet un incident aux admins sans jamais bloquer ni faire échouer +// l'appelant (qui tient s.mu) : l'envoi part dans une goroutine. +func (s *Service) alert(message string) { + if s.cfg.Alert == nil { + return + } + go s.cfg.Alert(message) +} + +// alertText neutralise le texte saisi par un client avant de l'insérer dans une +// alerte : sans « @ » une mention (@everyone) ne peut pas être déclenchée sur +// le Discord d'un admin, et sans retour à la ligne le message reste lisible. +func alertText(s string) string { + return strings.Map(func(r rune) rune { + switch r { + case '@': + return '@' + case '\n', '\r', '\t': + return ' ' + } + return r + }, s) +} + // shortID : 8 premiers caractères hex d'un uuid pour un nom de namespace court. func shortID(id string) string { clean := strings.ReplaceAll(id, "-", "") diff --git a/control-plane/api/internal/projects/service_test.go b/control-plane/api/internal/projects/service_test.go index a6a4590..4e67b22 100644 --- a/control-plane/api/internal/projects/service_test.go +++ b/control-plane/api/internal/projects/service_test.go @@ -3,6 +3,7 @@ package projects import ( "context" "errors" + "strings" "sync" "testing" "time" @@ -22,6 +23,8 @@ type fakeProv struct { stateCalls []string domainSpecs []demos.ProjectDomainSpec domainErr error + missing map[string]bool // namespaces absents du cluster simulé + existsErr error provisioned chan struct{} } @@ -48,6 +51,15 @@ func (f *fakeProv) ProjectState(_ context.Context, ns string) (demos.ResourceSta return f.state, f.stateErr } +func (f *fakeProv) NamespaceExists(_ context.Context, ns string) (bool, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.existsErr != nil { + return false, f.existsErr + } + return !f.missing[ns], nil +} + func (f *fakeProv) UpdateProjectDomain(s demos.ProjectDomainSpec) error { f.mu.Lock() defer f.mu.Unlock() @@ -446,3 +458,240 @@ func TestSetDomain_StateAndClusterErrors(t *testing.T) { t.Errorf("projet supprimé : erreur %v, attendu ErrNotReady", err) } } + +// --- Réconciliation base / cluster --- + +// setStatus force le statut d'un projet en base (simule un état hérité). +func setStatus(t *testing.T, svc *Service, id string, st Status) Project { + t.Helper() + p, ok := svc.store.Get(id) + if !ok { + t.Fatalf("projet %s introuvable", id) + } + p.Status = st + if _, err := svc.store.Update(p); err != nil { + t.Fatal(err) + } + return p +} + +func TestReconcile_PurgesDeletingAndDeletedWhenNamespaceIsGone(t *testing.T) { + for _, st := range []Status{StatusDeleting, StatusDeleted} { + svc, prov, _ := newTestService(t) + p := createReady(t, svc, prov, validInput()) + setStatus(t, svc, p.ID, st) + prov.missing = map[string]bool{p.Namespace: true} + + svc.reconcile() + + if _, ok := svc.store.Get(p.ID); ok { + t.Errorf("statut %s : ligne conservée alors que le namespace n'existe plus", st) + } + } +} + +func TestReconcile_KeepsRowWhileNamespaceExists(t *testing.T) { + svc, prov, _ := newTestService(t) + p := createReady(t, svc, prov, validInput()) + setStatus(t, svc, p.ID, StatusDeleting) // namespace encore là (Terminating compris) + + svc.reconcile() + + if got, ok := svc.store.Get(p.ID); !ok || got.Status != StatusDeleting { + t.Errorf("ligne purgée alors que le namespace existe : ok=%v %+v", ok, got) + } +} + +func TestReconcile_ReadyWithoutNamespaceBecomesFailedNeverDeleted(t *testing.T) { + svc, prov, _ := newTestService(t) + p := createReady(t, svc, prov, validInput()) + prov.missing = map[string]bool{p.Namespace: true} + + svc.reconcile() + + got, ok := svc.store.Get(p.ID) + if !ok { + t.Fatal("un projet en ligne ne doit jamais être purgé") + } + if got.Status != StatusFailed { + t.Errorf("statut %s, attendu failed", got.Status) + } +} + +func TestReconcile_LeavesFailedProvisioningAndPendingAlone(t *testing.T) { + for _, st := range []Status{StatusFailed, StatusProvisioning, StatusPending} { + svc, prov, _ := newTestService(t) + p := createReady(t, svc, prov, validInput()) + setStatus(t, svc, p.ID, st) + prov.missing = map[string]bool{p.Namespace: true} + + svc.reconcile() + + if got, ok := svc.store.Get(p.ID); !ok || got.Status != st { + t.Errorf("statut %s : ligne modifiée ou purgée (%v %+v)", st, ok, got) + } + } +} + +func TestReconcile_APIErrorWritesNothing(t *testing.T) { + svc, prov, _ := newTestService(t) + gone := createReady(t, svc, prov, validInput()) + live := createReady(t, svc, prov, validInput()) + setStatus(t, svc, gone.ID, StatusDeleted) + prov.missing = map[string]bool{gone.Namespace: true} + prov.existsErr = errors.New("api k8s injoignable") + + svc.reconcile() + + if _, ok := svc.store.Get(gone.ID); !ok { + t.Error("ligne purgée alors que le cluster était injoignable") + } + if got, _ := svc.store.Get(live.ID); got.Status != StatusReady { + t.Errorf("projet en ligne modifié sur une simple erreur d'API : %s", got.Status) + } +} + +func TestReconcile_OnlyTargetsMissingNamespaces(t *testing.T) { + svc, prov, _ := newTestService(t) + a := createReady(t, svc, prov, validInput()) + b := createReady(t, svc, prov, validInput()) + setStatus(t, svc, a.ID, StatusDeleted) + setStatus(t, svc, b.ID, StatusDeleted) + prov.missing = map[string]bool{a.Namespace: true} + + svc.reconcile() + + if _, ok := svc.store.Get(a.ID); ok { + t.Error("la ligne au namespace absent aurait dû être purgée") + } + if _, ok := svc.store.Get(b.ID); !ok { + t.Error("la ligne au namespace existant ne doit pas être purgée") + } +} + +func TestStoreDelete_IsIdempotent(t *testing.T) { + st := NewMemStore() + if _, err := st.Create(Project{ID: "p1"}); err != nil { + t.Fatal(err) + } + if err := st.Delete("p1"); err != nil { + t.Fatal(err) + } + if _, ok := st.Get("p1"); ok { + t.Error("ligne toujours présente après Delete") + } + if err := st.Delete("p1"); err != nil { + t.Errorf("second Delete : %v, attendu nil", err) + } +} + +func TestRunExpirationLoop_ReconcilesOnEachTick(t *testing.T) { + svc, prov, _ := newTestService(t) + p := createReady(t, svc, prov, validInput()) + setStatus(t, svc, p.ID, StatusDeleting) + prov.missing = map[string]bool{p.Namespace: true} + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + svc.RunExpirationLoop(ctx, 5*time.Millisecond) + close(done) + }() + + deadline := time.After(2 * time.Second) + for { + if _, ok := svc.store.Get(p.ID); !ok { + break + } + select { + case <-deadline: + t.Fatal("la boucle n'a pas purgé la ligne : reconcile() n'est pas appelé") + case <-time.After(5 * time.Millisecond): + } + } + cancel() + <-done +} + +// --- Alerte d'incident --- + +// captureAlerts branche un Alert de test ; chaque message arrive sur le canal. +func captureAlerts(svc *Service) chan string { + ch := make(chan string, 8) + svc.cfg.Alert = func(m string) { ch <- m } + return ch +} + +func waitAlert(t *testing.T, ch chan string) string { + t.Helper() + select { + case m := <-ch: + return m + case <-time.After(2 * time.Second): + t.Fatal("aucune alerte reçue") + return "" + } +} + +func TestReconcile_ReadyWithoutNamespaceAlertsAdminsOnce(t *testing.T) { + svc, prov, _ := newTestService(t) + alerts := captureAlerts(svc) + p := createReady(t, svc, prov, validInput()) + prov.missing = map[string]bool{p.Namespace: true} + + svc.reconcile() + msg := waitAlert(t, alerts) + for _, want := range []string{p.Namespace, p.Host, "Boutique Dupont"} { + if !strings.Contains(msg, want) { + t.Errorf("l'alerte ne mentionne pas %q : %s", want, msg) + } + } + + // Le projet est passé en échec : les tours suivants ne renvoient rien. + svc.reconcile() + svc.reconcile() + select { + case m := <-alerts: + t.Errorf("alerte répétée : %s", m) + case <-time.After(100 * time.Millisecond): + } +} + +func TestReconcile_NoAlertForRoutinePurgesOrAPIErrors(t *testing.T) { + svc, prov, _ := newTestService(t) + alerts := captureAlerts(svc) + gone := createReady(t, svc, prov, validInput()) + setStatus(t, svc, gone.ID, StatusDeleting) + prov.missing = map[string]bool{gone.Namespace: true} + svc.reconcile() // purge normale + + live := createReady(t, svc, prov, validInput()) + prov.missing = map[string]bool{live.Namespace: true} + prov.existsErr = errors.New("api k8s injoignable") + svc.reconcile() // cluster injoignable : aucun incident à déclarer + + select { + case m := <-alerts: + t.Errorf("alerte inutile : %s", m) + case <-time.After(100 * time.Millisecond): + } +} + +func TestReconcile_WithoutAlertHookStillMarksFailed(t *testing.T) { + svc, prov, _ := newTestService(t) // Config.Alert == nil + p := createReady(t, svc, prov, validInput()) + prov.missing = map[string]bool{p.Namespace: true} + + svc.reconcile() // ne doit pas paniquer + + if got, _ := svc.store.Get(p.ID); got.Status != StatusFailed { + t.Errorf("statut %s, attendu failed", got.Status) + } +} + +func TestAlertText_NeutralisesMentionsAndLineBreaks(t *testing.T) { + got := alertText("a@everyone\nb\tc") + if strings.Contains(got, "@") || strings.ContainsAny(got, "\n\t") { + t.Errorf("texte non neutralisé : %q", got) + } +} diff --git a/control-plane/api/internal/projects/store.go b/control-plane/api/internal/projects/store.go index a8fb260..e6487a1 100644 --- a/control-plane/api/internal/projects/store.go +++ b/control-plane/api/internal/projects/store.go @@ -14,6 +14,9 @@ type Store interface { Get(id string) (Project, bool) List() ([]Project, error) Update(p Project) (Project, error) + // Delete supprime définitivement la ligne. Idempotent : un identifiant + // inconnu n'est pas une erreur. + Delete(id string) error } // GormStore : Store adossé à PostgreSQL via GORM. @@ -52,6 +55,10 @@ func (s *GormStore) Update(p Project) (Project, error) { return p, nil } +func (s *GormStore) Delete(id string) error { + return s.db.Where("id = ?", id).Delete(&Project{}).Error +} + // MemStore : Store en mémoire (dev/tests). type MemStore struct { mu sync.RWMutex @@ -91,3 +98,10 @@ func (m *MemStore) Update(p Project) (Project, error) { m.items[p.ID] = p return p, nil } + +func (m *MemStore) Delete(id string) error { + m.mu.Lock() + defer m.mu.Unlock() + delete(m.items, id) + return nil +}