VPS flow for a root clone of PyQuest: server_setup, server_update, server_manage; drop ssh/sudo push scripts

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-17 11:25:48 +02:00
parent a4df92a7c6
commit 170db9efee
21 changed files with 463 additions and 607 deletions
+30 -87
View File
@@ -32,68 +32,21 @@ CDN) and the fonts.
A complete nginx configuration example (MIME types, headers, cache, API) is provided in
`nginx/pyquest.conf.example`.
## Deploying to a VPS, step by step
## Installing on a VPS
Assumptions: a Linux VPS with **nginx**, a **domain name** pointing to it, and **SSH key** access.
**1. On the VPS (once)**
The server is set up **from a clone of the repository, directly on the VPS, as root**: the site is built in place,
then published as successive versions with an atomic switch of the `current` link. The repository is cloned under the
name `PyQuest` (for example `/opt/PyQuest`, outside `/root` and `/home`).
```bash
sudo mkdir -p /var/www/pyquest /var/www/letsencrypt
sudo chown "$USER" /var/www/pyquest # the SSH user must be able to write here
sudo apt install nginx certbot rsync
git clone git@github.com:deunix-educ/PyQuest.git /opt/PyQuest
cd /opt/PyQuest
./deploy/server_setup.sh --domain pyquest.example.org --dry-run # simulation
./deploy/server_setup.sh --domain pyquest.example.org --certbot you@mail
```
Then install the vhost: copy `nginx/pyquest-static.conf.example` (no backend; with the Django backend, `nginx/pyquest.conf.example`, see below) to `/etc/nginx/sites-available/pyquest` and
replace `pyquest.example.org` with your domain. The certificate does not exist yet: **first comment out the second
`server` block** (the port 443 one), then:
```bash
sudo ln -s /etc/nginx/sites-available/pyquest /etc/nginx/sites-enabled/pyquest
sudo nginx -t && sudo systemctl reload nginx
sudo certbot certonly --webroot -w /var/www/letsencrypt -d your-domain.example # Let's Encrypt
```
Then uncomment the 443 block and reload nginx (`sudo nginx -t && sudo systemctl reload nginx`). Certificate renewal is
automatic (the `certbot` package timer); nginx must be reloaded after each renewal:
`sudo sh -c 'printf "#!/bin/sh\nsystemctl reload nginx\n" > /etc/letsencrypt/renewal-hooks/deploy/nginx && chmod +x /etc/letsencrypt/renewal-hooks/deploy/nginx'`.
**2. On your machine: deploy**
```bash
make install
DEPLOY_HOST=user@your-domain.example make deploy
```
`make deploy` builds `dist/`, uploads the files to `releases/<date>-<commit>/` on the VPS (only changed files
travel), then switches the `current` link **in one atomic step**: the site is never half-updated. The last 3
versions are kept. Variables: `DEPLOY_PATH` (default `/var/www/pyquest`), `DEPLOY_KEEP`.
`./scripts/deploy.sh --dry-run` shows what would be sent without changing anything.
**3. Check**
```bash
make check-deploy URL=https://your-domain.example
```
The check verifies the isolation headers, MIME types, the Python engine, the service worker and the HTTPS
redirect. Then open the site: a level with `input()` (level 03) confirms isolation works.
**4. Update or roll back**
```bash
DEPLOY_HOST=user@your-domain.example make deploy # new version
DEPLOY_HOST=user@your-domain.example ./scripts/deploy.sh --rollback # previous version
```
Browsers pick up the new version on reload (pages and scripts go network first).
!!! warning "If something goes wrong"
- **`input()` unavailable, or stopping a loop restarts the engine**: the COOP/COEP/CORP headers are missing.
`make check-deploy` reports it.
- **Blank page, scripts refused**: wrong MIME type (a `types` block forgotten or incomplete).
- **Old version shown**: check that `service-worker.js` is served with `Cache-Control: no-cache`.
- The script never uses `sudo` or a password: only your SSH key is used, and nothing secret is in the repository.
The whole procedure (MariaDB database, starting the service, first administrator, publishing, backups, rollback,
troubleshooting) is in [Going live and operations](operations.md).
## Testing locally before deploying
@@ -142,33 +95,24 @@ reload), the Python engine is **cache first** (versioned, immutable files).
The Django backend does **two things**, both optional: sync progress between devices, and **protect access to the
level editor** (`author.html`) with a login. The learning application works entirely without it.
1. **Database: MariaDB** (or MySQL). Create a dedicated database and user (`utf8mb4` character set):
`./deploy/server_setup.sh` (see above) does most of the work; here is what it sets up, and what is left to do by hand.
```sql
CREATE DATABASE pyquest CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'pyquest'@'localhost' IDENTIFIED BY '…a long password…';
GRANT ALL PRIVILEGES ON pyquest.* TO 'pyquest'@'localhost';
```
1. **Database: MariaDB** (or MySQL; Django 5.2 requires MariaDB 10.5 or later), to create **by hand** with a dedicated
database and user (`utf8mb4`): adapt then run `deploy/mariadb-setup.sql.example` (`mariadb < …`).
2. **Python environment** inside the repository (`/opt/PyQuest/.venv-prod`), with `backend/requirements-prod.txt`
(Django, gunicorn, `mysqlclient` which is compiled: packages `pkg-config libmariadb-dev build-essential python3-dev`).
3. **Environment variables** in `/etc/pyquest/env` (mode 640, `root:pyquest`, never committed; template:
`deploy/pyquest.env.example`): `PYQUEST_SECRET_KEY` (**generated** at installation), `PYQUEST_ALLOWED_HOSTS`,
`PYQUEST_ORIGIN` (`https://your-domain.example`), `PYQUEST_DB_NAME`, `PYQUEST_DB_USER`, `PYQUEST_DB_PASSWORD` (**to
fill in**), `PYQUEST_DB_HOST` (default `127.0.0.1`), `PYQUEST_DB_PORT` (default `3306`), `PYQUEST_STATIC_ROOT`
(default `/var/www/pyquest/static`) and `DJANGO_SETTINGS_MODULE=pyquest_api.settings.production`.
4. **systemd service `pyquest`** (`deploy/pyquest.service.example`): gunicorn on `127.0.0.1:8001`, `pyquest` system
user; at startup it applies the migrations and collects the administration's static files.
5. **nginx**: `nginx/pyquest.conf.example` (vhost) and the `pyquest-locations.conf` and `pyquest-author-headers.conf`
snippets in `/etc/nginx/snippets/`; `/api/` is proxied to the service, **on the same domain**.
2. **Install** in a dedicated virtual environment (Django 5.2 requires MariaDB 10.5 or later):
```bash
sudo apt install pkg-config libmariadb-dev build-essential python3-dev # to build mysqlclient
python3 -m venv /opt/pyquest/venv
/opt/pyquest/venv/bin/pip install -r backend/requirements-prod.txt
```
3. **Environment variables** (never committed; for example in a file read by the systemd unit, mode `600`):
`PYQUEST_SECRET_KEY` (long random string), `PYQUEST_ALLOWED_HOSTS` (your domain), `PYQUEST_ORIGIN`
(`https://your-domain.example`), `PYQUEST_DB_NAME`, `PYQUEST_DB_USER`, `PYQUEST_DB_PASSWORD`, and if needed
`PYQUEST_DB_HOST` (default `127.0.0.1`), `PYQUEST_DB_PORT` (default `3306`) and `PYQUEST_STATIC_ROOT` (default
`/var/www/pyquest/static`, the administration's static files). Settings:
`DJANGO_SETTINGS_MODULE=pyquest_api.settings.production`.
4. **Create the tables**: `python manage.py migrate` (in `backend/`).
5. **Run** with `gunicorn` on `127.0.0.1:8001` (`gunicorn pyquest_api.wsgi --bind 127.0.0.1:8001`), managed by
systemd. nginx proxies `/api/` to it, **on the same domain**: use `nginx/pyquest.conf.example`, and copy
`nginx/pyquest-locations.conf.example` and `nginx/pyquest-author-headers.conf.example` into `/etc/nginx/snippets/` as
`pyquest-locations.conf` and `pyquest-author-headers.conf`.
Production Django commands go through `./scripts/server_manage.sh` (reads `/etc/pyquest/env` without sourcing it and
uses the right Python environment), for example `./scripts/server_manage.sh migrate`.
### Administration and author accounts
@@ -182,12 +126,11 @@ Two distinct notions:
**First administrator** (on the server, once):
```bash
cd backend && python manage.py createsuperuser # password of at least 12 characters
python manage.py collectstatic --noinput # administration files, served by nginx
./scripts/server_manage.sh createsuperuser # password of at least 12 characters
```
`collectstatic` writes into `PYQUEST_STATIC_ROOT` (default `/var/www/pyquest/static`), which nginx serves under
`/api/static/` (the `alias` in `pyquest-locations.conf`). Redo it after a Django upgrade.
The administration's static files are collected by the service at startup into `PYQUEST_STATIC_ROOT` (default
`/var/www/pyquest/static`), which nginx serves under `/api/static/` (the `alias` in `pyquest-locations.conf`).
**Managing authors**: open `https://your-domain.example/api/admin/`, sign in, then **Users**:
@@ -196,7 +139,7 @@ python manage.py collectstatic --noinput # administration files, serve
- **Add user** creates an account (username, password); then add it to the **Auteurs** group, or use the action above;
- deactivating an account (the "Active" box) removes all access at the next check.
On the command line, `python manage.py create_author ada` creates an author account directly, bypassing the
On the command line, `./scripts/server_manage.sh create_author ada` creates an author account directly, bypassing the
administration; `--reset` changes its password, `--admin` makes it an administrator (access to `/api/admin/`).
An administrator can also use the editor (a superuser has every permission). The `is_staff` status alone is **not
+52 -47
View File
@@ -1,100 +1,105 @@
# Going live and operations
This page is the **roadmap** for installing PyQuest on a VPS, then running it. It relies on scripts tested without a
server; what touches the VPS itself could not be tried for real before the first installation: always start with
`--dry-run` and `vps-doctor`.
Procedure to install PyQuest on a VPS, then run it. Everything is done **on the VPS, as root, from a clone of the
repository** (folder name: `PyQuest`). The scripts are tested without a server; what touches the VPS itself could not be
tried for real before the first installation: start with `--dry-run` and `vps_doctor.sh`.
## Have at hand
- the VPS SSH address and your key (`user@host`), the user having `sudo`;
- the **domain name**, already pointing to the VPS (A/AAAA record);
- **root** access to the VPS (SSH) and the **domain name**, already pointing to it (A/AAAA record);
- an email address (Let's Encrypt expiry notices);
- the **MariaDB** version in place (10.5 or later) and administrator access to create a database there;
- the **MariaDB** version in place (10.5 or later) and its administrator access to create a database there;
- a way to **clone the repository**: over HTTPS if the repository is public, otherwise a (read-only) deploy key:
`ssh-keygen -t ed25519 -f ~/.ssh/pyquest_deploy`, to add in GitHub (*Settings → Deploy keys*);
- nginx 1.25.1 or later preferably (otherwise see the `http2` comment in the examples).
## First installation (in order)
## First installation (in order, as root on the VPS)
| # | Where | Command | Result |
|---|---|---|---|
| 1 | your machine | `make ci` | everything green before sending |
| 2 | your machine | `DEPLOY_HOST=u@h make vps-bootstrap DOMAIN=pyquest.example.org ARGS=--dry-run` | **simulation**: nothing is written to the VPS |
| 3 | your machine | `DEPLOY_HOST=u@h make vps-bootstrap DOMAIN=pyquest.example.org ARGS="--certbot you@mail"` | packages, `pyquest` user, folders, Python environment, environment file (secret key generated), systemd service, nginx, certificate |
| 4 | VPS | adapt then `sudo mariadb < deploy/mariadb-setup.sql.example` | `pyquest` database and its user |
| 5 | VPS | put the database password in `/etc/pyquest/env` (`PYQUEST_DB_PASSWORD`) | the service can connect |
| 6 | VPS | `sudo systemctl enable --now pyquest` | migrations and static files applied at startup |
| 7 | VPS | `createsuperuser` (command printed at the end of the installation) | first administrator |
| 8 | your machine | `DEPLOY_HOST=u@h make deploy` | the site is online |
| 9 | your machine | `make check-deploy URL=https://pyquest.example.org` | headers, MIME types, Python engine, HTTPS redirect |
| 10 | your machine | `DEPLOY_HOST=u@h make vps-doctor` | everything is "ok" |
| # | Command | Result |
|---|---|---|
| 1 | `git clone git@github.com:deunix-educ/PyQuest.git /opt/PyQuest && cd /opt/PyQuest` | the code, in a folder named `PyQuest` outside `/root` and `/home` |
| 2 | `./deploy/server_setup.sh --domain pyquest.example.org --dry-run` | **simulation**: nothing is written |
| 3 | `./deploy/server_setup.sh --domain pyquest.example.org --certbot you@mail` | packages, `pyquest` user, folders, Python environment, `/etc/pyquest/env` (secret key generated), systemd service, nginx, certificate |
| 4 | adapt then `mariadb < deploy/mariadb-setup.sql.example` | `pyquest` database and its user |
| 5 | put the database password in `/etc/pyquest/env` (`PYQUEST_DB_PASSWORD`) | the service can connect |
| 6 | `systemctl enable --now pyquest` | migrations and static files applied at startup |
| 7 | `./scripts/server_manage.sh createsuperuser` | first administrator |
| 8 | `./scripts/server_update.sh` | the site is built, published, checked |
| 9 | `./scripts/vps_doctor.sh` | everything is "ok" |
Then, in a browser: level 03 (`input()`), `/author.html` (redirects to the login), `/api/admin/` (administration), and
**Settings → Sync → Turn on**.
The scripts are **idempotent**: you can rerun them after an error; they never replace a configuration file or a secret
that is already there.
that is already there. `server_setup.sh` refuses a repository under `/root` or `/home` (the service runs as the `pyquest`
system user and must be able to read the code).
## What the installation does, concretely
| Item | Location on the VPS |
|---|---|
| Static site (successive versions) | `/var/www/pyquest/releases/…`, `current` link |
| Cloned repository (backend code, scripts) | `/opt/PyQuest` |
| Backend Python environment | `/opt/PyQuest/.venv-prod` |
| Published site (successive versions) | `/var/www/pyquest/releases/…`, `current` link |
| Administration static files | `/var/www/pyquest/static` |
| Backend code | `/opt/pyquest/backend` |
| Python environment | `/opt/pyquest/venv` |
| Secrets and settings | `/etc/pyquest/env` (mode 640, `root:pyquest`) |
| Service | `pyquest.service` (gunicorn, `127.0.0.1:8001`, `pyquest` system user) |
| nginx | `/etc/nginx/sites-available/pyquest`, snippets in `/etc/nginx/snippets/` |
| Backups | `/var/backups/pyquest` |
The only right given without a password to your user is `systemctl restart|status pyquest`
(`/etc/sudoers.d/pyquest`).
System names (`pyquest` for the service, the user and `/etc/pyquest`) stay lowercase, as Linux convention wants; only the
repository folder is called `PyQuest`.
## Day-to-day operations
## Day-to-day operations (as root, in `/opt/PyQuest`)
| I want to… | Command |
|---|---|
| publish a new site version | `DEPLOY_HOST=u@h make deploy` |
| go back to the previous site version | `DEPLOY_HOST=u@h ./scripts/deploy.sh --rollback` |
| publish a new backend version | `DEPLOY_HOST=u@h make deploy-backend` (restarts the service; automatic migrations) |
| see the server state | `DEPLOY_HOST=u@h make vps-doctor` |
| update the site **and** the backend | `./scripts/server_update.sh` (git pull, build, atomic publish, dependencies, restart, check) |
| go back to the previous site version | `./scripts/server_update.sh --rollback` |
| simulate an update | `./scripts/server_update.sh --dry-run` |
| see the server state | `./scripts/vps_doctor.sh` |
| check the published site | `./scripts/check_deploy.sh https://domain` |
| manage authors | `https://domain/api/admin/` or `./scripts/server_manage.sh create_author ada` |
| read the logs | `journalctl -u pyquest -f`; `/var/log/nginx/error.log` |
| manage authors | `https://domain/api/admin/` |
| check the published site | `make check-deploy URL=https://domain` |
`server_update.sh` uses `git pull --ff-only`: it refuses to continue if the server's repository has local changes
(do not edit the code on the server; edit it on your machine, push, then update). Options: `--no-pull`, `--no-build`,
`--no-restart`, `--no-check`.
### Database backup
It holds the synced progress and the accounts. `scripts/backup_db.sh` makes a compressed, verified export (an empty
backup is refused) in `/var/backups/pyquest`, and keeps the last 14. Credentials are read from `/etc/pyquest/env`,
never passed on the command line.
backup is refused) in `/var/backups/pyquest`, and keeps the last 14. Credentials are read from `/etc/pyquest/env`, never
passed on the command line.
```bash
sudo ./scripts/backup_db.sh # by hand
echo '30 3 * * * root /opt/pyquest/scripts/backup_db.sh' | sudo tee /etc/cron.d/pyquest-backup # every night
gunzip < /var/backups/pyquest/pyquest-YYYYMMDD-HHMMSS.sql.gz | sudo mariadb pyquest # restore
/opt/PyQuest/scripts/backup_db.sh # by hand
echo '30 3 * * * root /opt/PyQuest/scripts/backup_db.sh' > /etc/cron.d/pyquest-backup # every night
gunzip < /var/backups/pyquest/pyquest-YYYYMMDD-HHMMSS.sql.gz | mariadb pyquest # restore
```
(The installation puts the script in `/opt/pyquest/scripts/`.) Remember to move the backups off the VPS (copy to another machine).
Remember to move the backups off the VPS (copy to another machine).
### Security updates
`sudo apt update && sudo apt upgrade` regularly; after a Django upgrade (`pip install -r
backend/requirements-prod.txt`), rerun `make deploy-backend`. The certificate renews itself (`certbot` timer);
`vps-doctor` flags an approaching expiry.
`apt update && apt upgrade` regularly. After a Django upgrade, `./scripts/server_update.sh` reinstalls the dependencies and
restarts the service. The certificate renews itself (`certbot` timer); `vps_doctor.sh` flags an approaching expiry.
## Troubleshooting
| Symptom | Likely cause | What to do |
|---|---|---|
| `vps-doctor`: `pyquest` service inactive | database password missing or wrong | `journalctl -u pyquest -n 50`, fix `/etc/pyquest/env` |
| `vps_doctor.sh`: `pyquest` service inactive | database password missing or wrong | `journalctl -u pyquest -n 50`, fix `/etc/pyquest/env` |
| the API answers 500 | database unreachable | `systemctl status mariadb`, check `PYQUEST_DB_*` |
| login page: "Forbidden (CSRF)" | wrong `PYQUEST_ORIGIN` | must be exactly `https://domain` |
| administration without styles | static files missing | `sudo systemctl restart pyquest` (reruns `collectstatic`) |
| `input()` unavailable | COOP/COEP headers missing | `make check-deploy`; check the nginx snippets |
| 502 on `/api/` | service stopped | `sudo systemctl status pyquest` |
| administration without styles | static files missing | `systemctl restart pyquest` (reruns `collectstatic`) |
| `input()` unavailable | COOP/COEP headers missing | `./scripts/check_deploy.sh`; check the nginx snippets |
| 502 on `/api/` | service stopped | `systemctl status pyquest` |
| 503 on the login | nginx rate limit exceeded | wait a minute |
| login refused "Too many attempts" | 5 failures in 15 minutes | wait 15 minutes |
| `server_setup.sh`: "pyquest cannot read" | repository in an inaccessible folder | clone under `/opt` |
## Resuming work later
The deployment progress and next steps are in `CONTEXT.md` (section "Déploiement sur le VPS"). To resume a session:
read it, run `make ci`, then `make vps-doctor` to see where the server stands.
The deployment progress and next steps are in `CONTEXT.md` (section "Déploiement sur le VPS"). To resume a session: read
it, run `make ci` on your machine, then `./scripts/vps_doctor.sh` on the VPS.
+30 -87
View File
@@ -33,68 +33,21 @@ jamais depuis un CDN) et les polices.
Un exemple complet de configuration nginx (types MIME, en-têtes, cache, API) est fourni dans
`nginx/pyquest.conf.example`.
## Déployer sur un VPS, pas à pas
## Installer sur un VPS
Hypothèses : un VPS Linux avec **nginx**, un **nom de domaine** qui pointe vers lui, et un accès **SSH par clé**.
**1. Sur le VPS (une seule fois)**
Le serveur se met en place **depuis un clone du dépôt, directement sur le VPS, en root** : le site est construit sur
place, puis publié par versions successives avec bascule atomique du lien `current`. Le dépôt se clone sous le nom
`PyQuest` (par exemple `/opt/PyQuest`, hors de `/root` et `/home`).
```bash
sudo mkdir -p /var/www/pyquest /var/www/letsencrypt
sudo chown "$USER" /var/www/pyquest # l'utilisateur SSH doit pouvoir écrire ici
sudo apt install nginx certbot rsync
git clone git@github.com:deunix-educ/PyQuest.git /opt/PyQuest
cd /opt/PyQuest
./deploy/server_setup.sh --domain pyquest.example.org --dry-run # simulation
./deploy/server_setup.sh --domain pyquest.example.org --certbot toi@mail
```
Installe ensuite le vhost : copie `nginx/pyquest-static.conf.example` (sans backend ; avec le backend Django, `nginx/pyquest.conf.example`, voir plus bas) vers `/etc/nginx/sites-available/pyquest` et
remplace `pyquest.example.org` par ton domaine. Le certificat n'existe pas encore : **commente d'abord le second
bloc `server`** (celui du port 443), puis :
```bash
sudo ln -s /etc/nginx/sites-available/pyquest /etc/nginx/sites-enabled/pyquest
sudo nginx -t && sudo systemctl reload nginx
sudo certbot certonly --webroot -w /var/www/letsencrypt -d ton-domaine.example # Let's Encrypt
```
Décommente alors le bloc 443 et recharge nginx (`sudo nginx -t && sudo systemctl reload nginx`). Le renouvellement du
certificat est automatique (minuteur `certbot` du paquet) ; il reste à recharger nginx après renouvellement :
`sudo sh -c 'printf "#!/bin/sh\nsystemctl reload nginx\n" > /etc/letsencrypt/renewal-hooks/deploy/nginx && chmod +x /etc/letsencrypt/renewal-hooks/deploy/nginx'`.
**2. Sur ta machine : déployer**
```bash
make install
DEPLOY_HOST=utilisateur@ton-domaine.example make deploy
```
`make deploy` construit `dist/`, envoie les fichiers dans `releases/<date>-<commit>/` sur le VPS (seuls les fichiers
modifiés voyagent), puis bascule le lien `current` **d'un seul coup** : le site n'est jamais à moitié à jour. Les
3 dernières versions sont conservées. Variables : `DEPLOY_PATH` (défaut `/var/www/pyquest`), `DEPLOY_KEEP`.
`./scripts/deploy.sh --dry-run` montre ce qui serait envoyé sans rien modifier.
**3. Vérifier**
```bash
make check-deploy URL=https://ton-domaine.example
```
Le contrôle vérifie les en-têtes d'isolation, les types MIME, le moteur Python, le service worker et la
redirection HTTPS. Ouvre ensuite le site : un niveau avec `input()` (niveau 03) confirme que l'isolation fonctionne.
**4. Mettre à jour ou revenir en arrière**
```bash
DEPLOY_HOST=utilisateur@ton-domaine.example make deploy # nouvelle version
DEPLOY_HOST=utilisateur@ton-domaine.example ./scripts/deploy.sh --rollback # version précédente
```
Les navigateurs récupèrent la nouvelle version au rechargement (pages et scripts passent par le réseau d'abord).
!!! warning "En cas de problème"
- **`input()` indisponible, ou arrêt d'une boucle qui redémarre le moteur** : les en-têtes COOP/COEP/CORP
manquent. `make check-deploy` le dit.
- **Page blanche, scripts refusés** : type MIME incorrect (un bloc `types` oublié ou incomplet).
- **Ancienne version affichée** : vérifie que `service-worker.js` est bien servi avec `Cache-Control: no-cache`.
- Le script n'utilise jamais `sudo` ni de mot de passe : seule ta clé SSH sert, et rien de secret n'est dans le dépôt.
Toute la marche à suivre (base MariaDB, démarrage du service, premier administrateur, publication, sauvegardes,
retour arrière, dépannage) est dans [Mise en service et exploitation](operations.md).
## Tester en local avant de déployer
@@ -146,33 +99,24 @@ Le backend Django sert à **deux choses**, toutes deux facultatives : synchronis
comptes. L'application d'apprentissage
fonctionne entièrement sans lui.
1. **Base de données : MariaDB** (ou MySQL). Crée une base et un utilisateur dédiés (jeu de caractères `utf8mb4`) :
`./deploy/server_setup.sh` (voir ci-dessus) fait l'essentiel ; voici ce qu'il met en place, et ce qui reste à faire à la main.
```sql
CREATE DATABASE pyquest CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'pyquest'@'localhost' IDENTIFIED BY '…un mot de passe long…';
GRANT ALL PRIVILEGES ON pyquest.* TO 'pyquest'@'localhost';
```
1. **Base de données : MariaDB** (ou MySQL ; Django 5.2 exige MariaDB 10.5 ou plus), à créer **à la main** avec une base et
un utilisateur dédiés (`utf8mb4`) : adapte puis exécute `deploy/mariadb-setup.sql.example` (`mariadb < …`).
2. **Environnement Python** dans le dépôt (`/opt/PyQuest/.venv-prod`), avec `backend/requirements-prod.txt` (Django,
gunicorn, `mysqlclient` qui se compile : paquets `pkg-config libmariadb-dev build-essential python3-dev`).
3. **Variables d'environnement** dans `/etc/pyquest/env` (droits 640, `root:pyquest`, jamais commité ; modèle :
`deploy/pyquest.env.example`) : `PYQUEST_SECRET_KEY` (**générée** à l'installation), `PYQUEST_ALLOWED_HOSTS`,
`PYQUEST_ORIGIN` (`https://ton-domaine.example`), `PYQUEST_DB_NAME`, `PYQUEST_DB_USER`, `PYQUEST_DB_PASSWORD` (**à
remplir**), `PYQUEST_DB_HOST` (défaut `127.0.0.1`), `PYQUEST_DB_PORT` (défaut `3306`), `PYQUEST_STATIC_ROOT` (défaut
`/var/www/pyquest/static`) et `DJANGO_SETTINGS_MODULE=pyquest_api.settings.production`.
4. **Service systemd `pyquest`** (`deploy/pyquest.service.example`) : gunicorn sur `127.0.0.1:8001`, utilisateur système
`pyquest` ; au démarrage il applique les migrations et collecte les fichiers statiques de l'administration.
5. **nginx** : `nginx/pyquest.conf.example` (vhost) et les extraits `pyquest-locations.conf` et
`pyquest-author-headers.conf` dans `/etc/nginx/snippets/` ; `/api/` est relayé vers le service, **sur le même domaine**.
2. **Installer** dans un environnement virtuel dédié (Django 5.2 exige MariaDB 10.5 ou plus) :
```bash
sudo apt install pkg-config libmariadb-dev build-essential python3-dev # pour compiler mysqlclient
python3 -m venv /opt/pyquest/venv
/opt/pyquest/venv/bin/pip install -r backend/requirements-prod.txt
```
3. **Variables d'environnement** (jamais commitées ; par exemple dans un fichier lu par l'unité systemd, droits `600`) :
`PYQUEST_SECRET_KEY` (longue chaîne aléatoire), `PYQUEST_ALLOWED_HOSTS` (ton domaine), `PYQUEST_ORIGIN`
(`https://ton-domaine.example`), `PYQUEST_DB_NAME`, `PYQUEST_DB_USER`, `PYQUEST_DB_PASSWORD`, et si besoin
`PYQUEST_DB_HOST` (défaut `127.0.0.1`), `PYQUEST_DB_PORT` (défaut `3306`) et `PYQUEST_STATIC_ROOT` (défaut
`/var/www/pyquest/static`, fichiers statiques de l'administration). Réglages :
`DJANGO_SETTINGS_MODULE=pyquest_api.settings.production`.
4. **Créer les tables** : `python manage.py migrate` (dossier `backend/`).
5. **Lancer** avec `gunicorn` sur `127.0.0.1:8001` (`gunicorn pyquest_api.wsgi --bind 127.0.0.1:8001`), géré par
systemd. nginx relaie `/api/` vers lui, **sur le même domaine** : utilise `nginx/pyquest.conf.example`, et copie
`nginx/pyquest-locations.conf.example` et `nginx/pyquest-author-headers.conf.example` dans `/etc/nginx/snippets/` sous les
noms `pyquest-locations.conf` et `pyquest-author-headers.conf`.
Les commandes Django de production passent par `./scripts/server_manage.sh` (lit `/etc/pyquest/env` sans le « sourcer » et
utilise le bon environnement Python), par exemple `./scripts/server_manage.sh migrate`.
### Administration et comptes auteurs
@@ -186,12 +130,11 @@ Deux notions distinctes :
**Premier administrateur** (sur le serveur, une seule fois) :
```bash
cd backend && python manage.py createsuperuser # mot de passe de 12 caractères minimum
python manage.py collectstatic --noinput # fichiers de l'administration, servis par nginx
./scripts/server_manage.sh createsuperuser # mot de passe de 12 caractères minimum
```
`collectstatic` écrit dans `PYQUEST_STATIC_ROOT` (défaut `/var/www/pyquest/static`), que nginx sert sous `/api/static/`
(`alias` du fichier `pyquest-locations.conf`). À refaire après une mise à jour de Django.
Les fichiers statiques de l'administration sont collectés par le service au démarrage dans `PYQUEST_STATIC_ROOT`
(défaut `/var/www/pyquest/static`), que nginx sert sous `/api/static/` (`alias` de `pyquest-locations.conf`).
**Gérer les auteurs** : ouvre `https://ton-domaine.example/api/admin/`, connecte-toi, puis **Utilisateurs** :
@@ -201,7 +144,7 @@ python manage.py collectstatic --noinput # fichiers de l'administratio
utilise l'action ci-dessus ;
- désactiver un compte (case « Actif ») lui retire tout accès à la prochaine vérification.
En ligne de commande, `python manage.py create_author ada` crée directement un compte auteur sans passer par
En ligne de commande, `./scripts/server_manage.sh create_author ada` crée directement un compte auteur sans passer par
l'administration ; `--reset` change son mot de passe, `--admin` en fait un administrateur (accès à `/api/admin/`).
Un administrateur peut aussi utiliser l'éditeur (un superutilisateur a toutes les permissions). Le simple statut
+50 -44
View File
@@ -1,65 +1,70 @@
# Mise en service et exploitation
Cette page est la **feuille de route** pour installer PyQuest sur un VPS, puis l'exploiter. Elle s'appuie sur des
scripts testés (sans serveur) ; ce qui touche le VPS lui-même n'a pas pu être essayé en réel avant la première
installation : commence toujours par `--dry-run` et `vps-doctor`.
Marche à suivre pour installer PyQuest sur un VPS, puis l'exploiter. Tout se fait **sur le VPS, en root, depuis un clone
du dépôt** (nom du dossier : `PyQuest`). Les scripts sont testés sans serveur ; ce qui touche le VPS lui-même n'a pas pu
être essayé en réel avant la première installation : commence par `--dry-run` et `vps_doctor.sh`.
## À avoir sous la main
- l'adresse SSH du VPS et ta clé (`utilisateur@hote`), l'utilisateur ayant `sudo` ;
- le **nom de domaine**, qui pointe déjà vers le VPS (enregistrement A/AAAA) ;
- l'accès **root** au VPS (SSH) et le **nom de domaine**, qui pointe déjà vers lui (enregistrement A/AAAA) ;
- une adresse e-mail (avis d'expiration Let's Encrypt) ;
- la version de **MariaDB** en place (10.5 ou plus) et un accès administrateur pour y créer une base ;
- la version de **MariaDB** en place (10.5 ou plus) et son accès administrateur pour y créer une base ;
- de quoi **cloner le dépôt** : en HTTPS si le dépôt est public, sinon une clé de déploiement (lecture seule) :
`ssh-keygen -t ed25519 -f ~/.ssh/pyquest_deploy`, à ajouter dans GitHub (*Settings → Deploy keys*) ;
- nginx 1.25.1 ou plus de préférence (sinon voir le commentaire `http2` dans les exemples).
## Première installation (dans l'ordre)
## Première installation (dans l'ordre, en root sur le VPS)
| # | Où | Commande | Résultat |
|---|---|---|---|
| 1 | ta machine | `make ci` | tout est vert avant d'envoyer |
| 2 | ta machine | `DEPLOY_HOST=u@h make vps-bootstrap DOMAIN=pyquest.example.org ARGS=--dry-run` | **simulation** : rien n'est écrit sur le VPS |
| 3 | ta machine | `DEPLOY_HOST=u@h make vps-bootstrap DOMAIN=pyquest.example.org ARGS="--certbot toi@mail"` | paquets, utilisateur `pyquest`, dossiers, environnement Python, fichier d'environnement (clé secrète générée), service systemd, nginx, certificat |
| 4 | VPS | adapter puis `sudo mariadb < deploy/mariadb-setup.sql.example` | base `pyquest` et son utilisateur |
| 5 | VPS | mettre le mot de passe de la base dans `/etc/pyquest/env` (`PYQUEST_DB_PASSWORD`) | le service pourra se connecter |
| 6 | VPS | `sudo systemctl enable --now pyquest` | migrations et statiques appliqués au démarrage |
| 7 | VPS | `createsuperuser` (commande affichée à la fin de l'installation) | premier administrateur |
| 8 | ta machine | `DEPLOY_HOST=u@h make deploy` | le site est en ligne |
| 9 | ta machine | `make check-deploy URL=https://pyquest.example.org` | en-têtes, types MIME, moteur Python, redirection HTTPS |
| 10 | ta machine | `DEPLOY_HOST=u@h make vps-doctor` | tout est « ok » |
| # | Commande | Résultat |
|---|---|---|
| 1 | `git clone git@github.com:deunix-educ/PyQuest.git /opt/PyQuest && cd /opt/PyQuest` | le code, dans un dossier nommé `PyQuest` hors de `/root` et `/home` |
| 2 | `./deploy/server_setup.sh --domain pyquest.example.org --dry-run` | **simulation** : rien n'est écrit |
| 3 | `./deploy/server_setup.sh --domain pyquest.example.org --certbot toi@mail` | paquets, utilisateur `pyquest`, dossiers, environnement Python, `/etc/pyquest/env` (clé secrète générée), service systemd, nginx, certificat |
| 4 | adapter puis `mariadb < deploy/mariadb-setup.sql.example` | base `pyquest` et son utilisateur |
| 5 | mettre le mot de passe de la base dans `/etc/pyquest/env` (`PYQUEST_DB_PASSWORD`) | le service pourra se connecter |
| 6 | `systemctl enable --now pyquest` | migrations et statiques appliqués au démarrage |
| 7 | `./scripts/server_manage.sh createsuperuser` | premier administrateur |
| 8 | `./scripts/server_update.sh` | le site est construit, publié, contrôlé |
| 9 | `./scripts/vps_doctor.sh` | tout est « ok » |
Puis, dans un navigateur : le niveau 03 (`input()`), `/author.html` (renvoie vers la connexion), `/api/admin/`
(administration), et **Réglages → Synchronisation → Activer**.
Les scripts sont **idempotents** : on peut les relancer après une erreur ; ils ne remplacent jamais un fichier de
configuration ou un secret déjà présent.
configuration ou un secret déjà présent. `server_setup.sh` refuse un dépôt sous `/root` ou `/home` (le service tourne sous
l'utilisateur système `pyquest` et doit pouvoir lire le code).
## Ce que fait l'installation, concrètement
| Élément | Emplacement sur le VPS |
|---|---|
| Site statique (versions successives) | `/var/www/pyquest/releases/…`, lien `current` |
| Dépôt cloné (code du backend, scripts) | `/opt/PyQuest` |
| Environnement Python du backend | `/opt/PyQuest/.venv-prod` |
| Site publié (versions successives) | `/var/www/pyquest/releases/…`, lien `current` |
| Fichiers statiques de l'administration | `/var/www/pyquest/static` |
| Code du backend | `/opt/pyquest/backend` |
| Environnement Python | `/opt/pyquest/venv` |
| Secrets et réglages | `/etc/pyquest/env` (droits 640, `root:pyquest`) |
| Service | `pyquest.service` (gunicorn, `127.0.0.1:8001`, utilisateur système `pyquest`) |
| nginx | `/etc/nginx/sites-available/pyquest`, extraits dans `/etc/nginx/snippets/` |
| Sauvegardes | `/var/backups/pyquest` |
Le seul droit donné sans mot de passe à ton utilisateur est `systemctl restart|status pyquest`
(`/etc/sudoers.d/pyquest`).
Les noms système (`pyquest` pour le service, l'utilisateur et `/etc/pyquest`) restent en minuscules, comme le veut la
convention Linux ; seul le dossier du dépôt s'appelle `PyQuest`.
## Exploitation courante
## Exploitation courante (en root, dans `/opt/PyQuest`)
| Je veux… | Commande |
|---|---|
| publier une nouvelle version du site | `DEPLOY_HOST=u@h make deploy` |
| revenir à la version précédente du site | `DEPLOY_HOST=u@h ./scripts/deploy.sh --rollback` |
| publier une nouvelle version du backend | `DEPLOY_HOST=u@h make deploy-backend` (redémarre le service ; migrations automatiques) |
| voir l'état du serveur | `DEPLOY_HOST=u@h make vps-doctor` |
| mettre à jour le site **et** le backend | `./scripts/server_update.sh` (git pull, construction, publication atomique, dépendances, redémarrage, contrôle) |
| revenir à la version précédente du site | `./scripts/server_update.sh --rollback` |
| simuler une mise à jour | `./scripts/server_update.sh --dry-run` |
| voir l'état du serveur | `./scripts/vps_doctor.sh` |
| contrôler le site publié | `./scripts/check_deploy.sh https://domaine` |
| gérer les auteurs | `https://domaine/api/admin/` ou `./scripts/server_manage.sh create_author ada` |
| lire les journaux | `journalctl -u pyquest -f` ; `/var/log/nginx/error.log` |
| gérer les auteurs | `https://domaine/api/admin/` |
| contrôler le site publié | `make check-deploy URL=https://domaine` |
`server_update.sh` utilise `git pull --ff-only` : il refuse de continuer si le dépôt du serveur contient des
modifications locales (ne modifie pas le code sur le serveur ; modifie-le sur ta machine, pousse, puis mets à jour).
Options : `--no-pull`, `--no-build`, `--no-restart`, `--no-check`.
### Sauvegarde de la base
@@ -68,33 +73,34 @@ Elle contient les progressions synchronisées et les comptes. `scripts/backup_db
dans `/etc/pyquest/env`, jamais passés en ligne de commande.
```bash
sudo ./scripts/backup_db.sh # à la main
echo '30 3 * * * root /opt/pyquest/scripts/backup_db.sh' | sudo tee /etc/cron.d/pyquest-backup # chaque nuit
gunzip < /var/backups/pyquest/pyquest-AAAAMMJJ-HHMMSS.sql.gz | sudo mariadb pyquest # restauration
/opt/PyQuest/scripts/backup_db.sh # à la main
echo '30 3 * * * root /opt/PyQuest/scripts/backup_db.sh' > /etc/cron.d/pyquest-backup # chaque nuit
gunzip < /var/backups/pyquest/pyquest-AAAAMMJJ-HHMMSS.sql.gz | mariadb pyquest # restauration
```
(L'installation place le script dans `/opt/pyquest/scripts/`.) Pense à sortir les sauvegardes du VPS (copie vers une autre machine).
Pense à sortir les sauvegardes du VPS (copie vers une autre machine).
### Mises à jour de sécurité
`sudo apt update && sudo apt upgrade` régulièrement ; après une mise à jour de Django
(`pip install -r backend/requirements-prod.txt`), relance `make deploy-backend`. Le certificat se renouvelle seul
(minuteur `certbot`) ; `vps-doctor` signale une expiration proche.
`apt update && apt upgrade` régulièrement. Après une mise à jour de Django, `./scripts/server_update.sh` réinstalle les
dépendances et redémarre le service. Le certificat se renouvelle seul (minuteur `certbot`) ; `vps_doctor.sh` signale
une expiration proche.
## Dépannage
| Symptôme | Cause probable | Que faire |
|---|---|---|
| `vps-doctor` : service `pyquest` inactif | mot de passe de la base absent ou faux | `journalctl -u pyquest -n 50`, corriger `/etc/pyquest/env` |
| `vps_doctor.sh` : service `pyquest` inactif | mot de passe de la base absent ou faux | `journalctl -u pyquest -n 50`, corriger `/etc/pyquest/env` |
| l'API répond 500 | base injoignable | `systemctl status mariadb`, vérifier `PYQUEST_DB_*` |
| page de connexion : « Forbidden (CSRF) » | `PYQUEST_ORIGIN` incorrect | doit valoir exactement `https://domaine` |
| administration sans style | statiques absents | `sudo systemctl restart pyquest` (relance `collectstatic`) |
| `input()` indisponible | en-têtes COOP/COEP absents | `make check-deploy` ; vérifier les extraits nginx |
| 502 sur `/api/` | service arrêté | `sudo systemctl status pyquest` |
| administration sans style | statiques absents | `systemctl restart pyquest` (relance `collectstatic`) |
| `input()` indisponible | en-têtes COOP/COEP absents | `./scripts/check_deploy.sh` ; vérifier les extraits nginx |
| 502 sur `/api/` | service arrêté | `systemctl status pyquest` |
| 503 sur la connexion | limite de débit nginx dépassée | attendre une minute |
| connexion refusée « Trop d'essais » | 5 échecs en 15 minutes | attendre 15 minutes |
| `server_setup.sh` : « pyquest ne peut pas lire » | dépôt dans un dossier non accessible | cloner sous `/opt` |
## Reprendre le travail plus tard
L'état d'avancement du déploiement et les prochaines étapes sont dans `CONTEXT.md` (section « Déploiement sur le
VPS »). Pour reprendre une session : le lire, lancer `make ci`, puis `make vps-doctor` pour voir où en est le serveur.
VPS »). Pour reprendre une session : le lire, lancer `make ci` sur ta machine, puis `./scripts/vps_doctor.sh` sur le VPS.