From b5db3008eea81a363319441e6c12fa042a218aee Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 9 Sep 2026 10:08:30 +0200 Subject: [PATCH] feat(installer): send failure reports to the FWS bug API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When an installation fails the machine does not reboot: it stays on the log window. Until now the user had a complete report in front of them and no way to get it to us -- no browser, no mail client in a live session. The log window now carries two buttons, "Envoyer le rapport aux développeurs" and "Redémarrer". Sending does not close the window, so it can be retried after plugging in a network cable, which is the usual reason an install failed in the first place. fws-report-bug POSTs to https://fws.laxacube.ch/api/bugs.php. It is written in python3 with urllib -- no added dependency, and json.dumps escapes raw logs containing quotes, backslashes and accents, which a shell-built JSON breaks on at the first line. It attaches the logs (last 200000 characters: the error is always at the end) and the detected hardware (CPU/GPU model, RAM, UEFI or BIOS, disks, virtualisation). It never sends the user name or the host name, and the e-mail only when one is given. Nothing is sent without an explicit click. profiledef.sh also gains the 0755 permission entry for the new helper, since repository files are versioned 0644. Signed-off-by: nocode --- configs/baseline/airootfs/root/.xinitrc | 45 +++- configs/baseline/profiledef.sh | 3 +- .../airootfs/usr/local/bin/fws-report-bug | 225 ++++++++++++++++++ 3 files changed, 270 insertions(+), 3 deletions(-) create mode 100644 configs/releng/airootfs/usr/local/bin/fws-report-bug diff --git a/configs/baseline/airootfs/root/.xinitrc b/configs/baseline/airootfs/root/.xinitrc index 7d2fe2f..27c1cc3 100644 --- a/configs/baseline/airootfs/root/.xinitrc +++ b/configs/baseline/airootfs/root/.xinitrc @@ -230,9 +230,50 @@ if command -v liveinst >/dev/null 2>&1; then systemctl poweroff else # Échec (ou install non terminée) : on montre les logs pour diagnostiquer. + # + # La machine NE REDÉMARRE PAS ici (contrairement au cas « réussite ») : + # l'utilisateur reste devant le rapport. Il lui faut donc, DANS cette + # fenêtre, de quoi (a) nous envoyer le rapport et (b) repartir. + # zenity --extra-button ajoute de vrais boutons à la fenêtre de logs : + # au clic, zenity SORT en imprimant le libellé du bouton sur stdout. + # On boucle donc : envoyer un rapport ne ferme pas définitivement les + # logs, et l'utilisateur peut réessayer (typiquement après avoir + # branché un câble réseau) autant de fois qu'il veut. + # + # L'envoi reste MANUEL et jamais automatique : le rapport contient les + # logs de la machine, ça ne part pas sans un clic. if command -v zenity >/dev/null 2>&1; then - zenity --text-info --title="FWS — logs Anaconda (sortie $rc)" \ - --filename="$DBG" --width=1100 --height=720 2>/dev/null & + ( + while :; do + _btn="$(zenity --text-info \ + --title="FWS — l'installation ne s'est pas terminée (sortie $rc)" \ + --filename="$DBG" --width=1100 --height=720 \ + --ok-label="Fermer" \ + --extra-button="Envoyer le rapport aux développeurs" \ + --extra-button="Redémarrer" 2>/dev/null)" || true + case "$_btn" in + "Envoyer le rapport aux développeurs") + if command -v fws-report-bug >/dev/null 2>&1; then + fws-report-bug --gui --type installation \ + --app "installateur FWS" \ + --logs "$DBG" \ + --logs /tmp/fws-post-chroot.log \ + 2>/dev/null || true + else + zenity --error --width=440 \ + --text="fws-report-bug est absent de cette image :\nle rapport ne peut pas être envoyé d'ici." 2>/dev/null || true + fi + ;; + "Redémarrer") + systemctl reboot + break + ;; + # « Fermer », croix de la fenêtre, ou zenity indisponible + # (X cassé) : on sort — surtout pas de boucle infinie. + *) break ;; + esac + done + ) & fi wait "$_OB_PID" fi diff --git a/configs/baseline/profiledef.sh b/configs/baseline/profiledef.sh index 33eac92..a5538c5 100644 --- a/configs/baseline/profiledef.sh +++ b/configs/baseline/profiledef.sh @@ -3,7 +3,7 @@ iso_name="FWS" iso_label="FWS_$(date --date="@${SOURCE_DATE_EPOCH:-$(date +%s)}" +%Y%m)" -iso_publisher="FWS " +iso_publisher="FWS " iso_application="Replace Windows from Microsoft" iso_version="$(date --date="@${SOURCE_DATE_EPOCH:-$(date +%s)}" +%Y.%m.%d)" install_dir="fws" @@ -41,5 +41,6 @@ file_permissions=( ["/usr/local/bin/fws-recovery-gui"]="0:0:755" ["/usr/local/bin/fws-powermenu"]="0:0:755" ["/usr/local/bin/fws-about"]="0:0:755" + ["/usr/local/bin/fws-report-bug"]="0:0:755" ["/etc/grub.d/42_fws-recovery"]="0:0:755" ) diff --git a/configs/releng/airootfs/usr/local/bin/fws-report-bug b/configs/releng/airootfs/usr/local/bin/fws-report-bug new file mode 100644 index 0000000..88ffb54 --- /dev/null +++ b/configs/releng/airootfs/usr/local/bin/fws-report-bug @@ -0,0 +1,225 @@ +#!/usr/bin/env python3 +"""FWS — envoi d'un signalement à l'API de suivi de bugs. + +POURQUOI EN PYTHON : le contenu envoyé est du JSON contenant des LOGS bruts +(guillemets, antislashs, accents, sauts de ligne). Le construire à la main en +shell casse à la première ligne de log contenant un guillemet ; json.dumps +échappe correctement. python3 est de toute façon garanti sur le live (Anaconda +en dépend) et sur le système installé (copie du live) — pas de dépendance en +plus, et urllib évite même d'avoir besoin de curl. + +CONTRAT DE L'API (POST JSON sur $FWS_BUG_API) : + app, version, type, title, description, email, system_info, logs +« type » ∈ bug | crash | installation | suggestion | autre. +Réponse : 201 {"ok":true,"id":N,"message":…} ou {"ok":false,"error":…}. + +Utilisation : + fws-report-bug --type installation --logs /tmp/fws-debug.txt \\ + --title "Installation interrompue" + fws-report-bug --gui --logs /tmp/fws-debug.txt # demande la description + +RIEN N'EST ENVOYÉ SANS ACTION EXPLICITE : ce script n'est jamais appelé +automatiquement, seulement derrière une confirmation de l'utilisateur (cf. le +harnais de diagnostic du .xinitrc) ou à la main. L'e-mail est facultatif et +n'est joint que s'il est passé en argument. +""" + +import argparse +import json +import os +import platform +import shutil +import subprocess +import sys +import urllib.error +import urllib.request + +API = os.environ.get("FWS_BUG_API", "https://fws.laxacube.ch/api/bugs.php") +TIMEOUT = 25 + +# Les logs d'installation peuvent peser plusieurs Mo (journal complet). On +# n'envoie que la FIN : c'est là que se trouve l'erreur, et ça garde la requête +# sous les limites d'upload d'un PHP par défaut. +MAX_LOG_CHARS = 200_000 + + +def _run(cmd): + """Sortie d'une commande, ou chaîne vide — un rapport ne doit jamais planter.""" + try: + out = subprocess.run(cmd, capture_output=True, text=True, timeout=10) + return (out.stdout or "").strip() + except Exception: # pylint: disable=broad-except + return "" + + +def _os_release(): + data = {} + for path in ("/etc/os-release", "/usr/lib/os-release"): + try: + with open(path, encoding="utf-8") as fh: + for line in fh: + if "=" in line and not line.startswith("#"): + key, _, val = line.partition("=") + data[key.strip()] = val.strip().strip('"') + break + except OSError: + continue + return data + + +def collect_system_info(): + """Matériel et environnement — rien de nominatif (ni user, ni hostname).""" + osr = _os_release() + bits = [ + f"{osr.get('NAME', 'FWS')} {osr.get('VERSION_ID', '?')}", + f"noyau {platform.release()}", + "UEFI" if os.path.isdir("/sys/firmware/efi") else "BIOS", + ] + + virt = _run(["systemd-detect-virt"]) + bits.append(f"virtualisation {virt}" if virt and virt != "none" else "matériel réel") + + cpu = "" + try: + with open("/proc/cpuinfo", encoding="utf-8") as fh: + for line in fh: + if line.startswith("model name"): + cpu = line.split(":", 1)[1].strip() + break + except OSError: + pass + if cpu: + bits.append(f"CPU {cpu}") + + try: + with open("/proc/meminfo", encoding="utf-8") as fh: + for line in fh: + if line.startswith("MemTotal:"): + bits.append(f"RAM {int(line.split()[1]) // 1024} Mio") + break + except OSError: + pass + + if shutil.which("lspci"): + gpus = [ln.split(": ", 1)[-1] for ln in _run(["lspci"]).splitlines() + if "VGA compatible controller" in ln or "3D controller" in ln] + if gpus: + bits.append("GPU " + " | ".join(gpus)) + + disks = _run(["lsblk", "-dno", "NAME,SIZE,MODEL"]) + if disks: + bits.append("disques " + " ; ".join(disks.split("\n"))) + + return "\n".join(bits) + + +def read_logs(paths): + """Concatène les fichiers de log lisibles, en gardant la FIN de l'ensemble.""" + chunks = [] + for path in paths: + try: + with open(path, encoding="utf-8", errors="replace") as fh: + chunks.append(f"########## {path} ##########\n{fh.read()}") + except OSError as err: + chunks.append(f"########## {path} : illisible ({err}) ##########") + text = "\n".join(chunks) + if len(text) > MAX_LOG_CHARS: + text = ("[… début tronqué, seuls les derniers " + f"{MAX_LOG_CHARS} caractères sont envoyés …]\n" + + text[-MAX_LOG_CHARS:]) + return text + + +def send(payload): + """POST du signalement. Renvoie (ok, message).""" + body = json.dumps(payload, ensure_ascii=False).encode("utf-8") + request = urllib.request.Request( + API, data=body, method="POST", + headers={"Content-Type": "application/json", + "User-Agent": "fws-report-bug/1.0"}) + try: + with urllib.request.urlopen(request, timeout=TIMEOUT) as resp: + answer = json.loads(resp.read().decode("utf-8", "replace")) + except urllib.error.HTTPError as err: + detail = err.read().decode("utf-8", "replace")[:400] + return False, f"Le serveur a refusé le signalement (HTTP {err.code}) : {detail}" + except urllib.error.URLError as err: + return False, f"Serveur injoignable ({err.reason}). Vérifiez la connexion Internet." + except Exception as err: # pylint: disable=broad-except + return False, f"Envoi impossible : {err}" + + if answer.get("ok"): + return True, f"Signalement envoyé ✔ (numéro {answer.get('id', '?')})" + return False, f"Refusé : {answer.get('error', 'raison inconnue')}" + + +def ask_description_gui(): + """Demande la description via zenity. None = l'utilisateur a annulé.""" + if not shutil.which("zenity"): + return "" + try: + out = subprocess.run( + ["zenity", "--entry", "--width=520", "--title=FWS — signaler un problème", + "--text=Décrivez en une phrase ce qui s'est passé " + "(les logs et le matériel sont joints automatiquement) :"], + capture_output=True, text=True, timeout=600) + except Exception: # pylint: disable=broad-except + return "" + if out.returncode != 0: + return None + return (out.stdout or "").strip() + + +def notify_gui(ok, message): + if not shutil.which("zenity"): + return + subprocess.run(["zenity", "--info" if ok else "--error", + "--width=460", "--title=FWS", f"--text={message}"], + capture_output=True, timeout=300, check=False) + + +def main(): + parser = argparse.ArgumentParser(description="Envoie un signalement à l'équipe FWS.") + parser.add_argument("--type", default="bug", + choices=["bug", "crash", "installation", "suggestion", "autre"]) + parser.add_argument("--app", default="FWS") + parser.add_argument("--title", default="") + parser.add_argument("--description", default="") + parser.add_argument("--email", default="", help="facultatif, pour être recontacté") + parser.add_argument("--logs", action="append", default=[], + metavar="FICHIER", help="peut être répété") + parser.add_argument("--gui", action="store_true", + help="demander la description et afficher le résultat via zenity") + args = parser.parse_args() + + description = args.description + if args.gui and not description: + description = ask_description_gui() + if description is None: + print("Envoi annulé.") + return 1 + + title = args.title or (description.splitlines()[0][:120] if description + else f"Signalement {args.type} sans titre") + + payload = { + "app": args.app, + "version": _os_release().get("VERSION_ID", ""), + "type": args.type, + "title": title, + "description": description, + "system_info": collect_system_info(), + "logs": read_logs(args.logs) if args.logs else "", + } + if args.email: + payload["email"] = args.email + + ok, message = send(payload) + print(message, file=sys.stdout if ok else sys.stderr) + if args.gui: + notify_gui(ok, message) + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main())