From 0d9ee9fa1d4a466d49309379c95c3bf3656c3404 Mon Sep 17 00:00:00 2001 From: William Mikal Ruud Schmidt Date: Tue, 24 Nov 2026 14:37:23 +0100 Subject: [PATCH 1/2] Updated README and vm.md for the new deploy script --- README.md | 8 +- docs/vm.md | 481 ++++++++----------------------- frontend/package.json | 1 - scripts/deploy.sh | 201 +++++++++++++ scripts/project2-backend.service | 23 ++ 5 files changed, 345 insertions(+), 369 deletions(-) create mode 100755 scripts/deploy.sh create mode 100644 scripts/project2-backend.service diff --git a/README.md b/README.md index 2877dc6..2b63b93 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ yet, depending on when the review is made. | GraphQL API: search, filter, sort, pagination | Done | Queries `wines`, `wine` and `filterOptions` | | Database schema and X-Wines import | Done | Tables and indexes come from the migrations in `backend/migrations/` | | Frontend deployed on the VM | Done | Deep links such as `/project2/sok` work on reload | -| Backend running on the VM | Done | Started with `nohup`, see [VM guide](docs/vm.md) | +| Backend running on the VM | Done | Runs as a systemd service, see [VM guide](docs/vm.md) | | Apollo Client in the frontend | Done | | | Search page with results | Done | Search with debounce, number of hits and "Last inn flere" at `/sok` | | Filtering and sorting in the user interface | Done | Filter panel, active filters and sorting on `/sok` | @@ -97,7 +97,7 @@ cd frontend && npm run dev # http://localhost:5173/project2/ The landing page needs the backend for wines and categories. Without it, the page shows an error message with a "Prøv igjen" button. -To deploy on the VM, see the [VM guide](docs/vm.md). +To deploy on the VM, run `./scripts/deploy.sh` there. See the [VM guide](docs/vm.md). ### Demo user @@ -174,7 +174,7 @@ Each row explains what we chose, why, and what else we considered. Added as the | Filter panel on small screens | Native `` with `showModal()` | The browser handles focus trapping, Escape and returning focus, with no extra JavaScript | A dialog library | | Filter counts | One count query per group that leaves out the group's own filter | The user can see what each choice gives before choosing, and values can be combined | Fixed counts for the whole catalogue | | Testing | Vitest, React Testing Library, Playwright, axe | Vitest shares configuration with Vite. Playwright tests real browsers, also on mobile | Jest, Cypress | -| Deployment | Apache serves static files, the backend runs with `nohup` | Matches the course VM | systemd service (possible improvement) | +| Deployment | Apache serves static files, the backend runs as a systemd service, and one script (`scripts/deploy.sh`) updates both | Matches the course VM. The backend starts again after a crash or a restart of the VM, and a deploy is the same steps every time | Starting the backend by hand with `nohup`, which we did first | See [API](docs/api.md) for the schema and example queries. @@ -472,7 +472,7 @@ Remove known issues as they are fixed. - [Setup](docs/setup.md): Git, dependencies, `.env` and local start - [Database](docs/database.md): PostgreSQL on macOS, Windows and Ubuntu -- [VM](docs/vm.md): deployment, Apache and running the backend with `nohup` +- [VM](docs/vm.md): the deploy script, first-time setup, Apache, backups and loading the dataset - [API](docs/api.md): GraphQL queries, user accounts, reviews, wine lists, the demo user, database tests and the X-Wines citation - [Manual testing](docs/manual-testing.md): how to test login, reviews, wine lists and the demo user by hand - [Screen reader testing](docs/screen-reader.md): what we found, what we fixed and the VoiceOver script diff --git a/docs/vm.md b/docs/vm.md index ef857f9..02f6eed 100644 --- a/docs/vm.md +++ b/docs/vm.md @@ -1,245 +1,134 @@ # VM -Use the NTNU network or VPN. Connect with your own VM account: +The site runs on `it2810-18.idi.ntnu.no`, at [/project2/](http://it2810-18.idi.ntnu.no/project2/). +Use the NTNU network or VPN, and connect with your own VM account: ```bash ssh @it2810-18.idi.ntnu.no ``` -On Windows, run this command in PowerShell. Replace `` with your VM username. -If `ssh` is missing, install OpenSSH Client through Windows Optional Features. -See [Microsoft's instructions](https://learn.microsoft.com/en-us/windows-server/administration/OpenSSH/openssh-overview). -After connecting, run the Linux commands below on the VM. +| Part | Where on the VM | Run by | +| -------- | -------------------------- | -------------------------------------- | +| Frontend | `/var/www/html/project2` | Apache | +| Backend | `/opt/project2/backend` | The systemd service `project2-backend` | +| Database | PostgreSQL, `vinmonopolet` | The systemd service `postgresql` | +| Backups | `/opt/project2/backups` | Written by the deploy script | -## Install +## Deploy -Run these commands on the VM: - -```bash -sudo apt update -sudo apt install apache2 postgresql git curl ca-certificates -sudo systemctl enable --now apache2 postgresql -``` - -Install nvm as your normal user: - -```bash -curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.8/install.sh | bash -``` - -For Bash, add this block to `~/.bash_profile` once: - -```bash -export NVM_DIR="$HOME/.nvm" -[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" -``` - -Load nvm and install Node.js: - -```bash -source ~/.bash_profile -nvm install 24 -nvm alias default 24 -``` - -Each user needs their own nvm installation. Check the selected Node.js version: - -```bash -node --version -npm --version -``` - -Keep the repository in your home directory, outside Apache's document root. -If you already cloned it into `~/ntnuhome/T18-Project-2`, use that checkout. -Otherwise, clone it once: - -```bash -mkdir -p ~/ntnuhome -cd ~/ntnuhome -git clone https://git.ntnu.no/IT2810-H26/T18-Project-2.git -``` - -Git access uses your repository credentials, separately from your VM account. -For an SSH clone URL, configure your VM account's SSH key for git.ntnu.no. - -Follow [setup](setup.md) to configure `backend/.env`. -Use the Ubuntu steps in [database](database.md) to create the database and user once. - -## `backend/.env` on the VM - -The backend reads `DATABASE_URL` from `backend/.env` in the checkout it runs from. Git does not -copy `.env`, so every checkout that starts the backend needs its own. The password is the one for -the database user `vinmonopolet_app` on the VM, not your VM password. - -Find the checkout the running backend uses, and so the `.env` that works. The file can be read with -`sudo`, also for the course staff: - -```bash -sudo readlink "/proc/$(pgrep -f 'src/server.ts' | head -1)/cwd" # e.g. /home//ntnuhome/T18-Project-2/backend -sudo ls -l /home/*/ntnuhome/T18-Project-2/backend/.env -``` - -To create your own, ask the group for the password, then: - -```bash -cd ~/ntnuhome/T18-Project-2/backend -cp .env.example .env -chmod 600 .env -nano .env -``` - -- Write `@`, `:`, `/`, `#` and `%` in the password as `%40`, `%3A`, `%2F`, `%23` and `%25`. -- Leave `COOKIE_SECURE` commented out. The VM serves plain HTTP, and secure cookies are only sent - over HTTPS, so login would stop working. - -Check the connection. The first line about GSSAPI or Kerberos is harmless; only -`password authentication failed` means the password is wrong: - -```bash -psql "$(grep ^DATABASE_URL .env | cut -d= -f2-)" -c "SELECT current_user;" -``` - -If nobody knows the password, a group member with `sudo` can set a new one. Every other `.env` on -the VM then stops working until it is updated, so tell the group first: - -```bash -sudo -u postgres psql -c "ALTER ROLE vinmonopolet_app WITH PASSWORD 'new_password';" -``` - -## Publish the frontend - -Run on the VM from the checkout's `frontend/` directory: +Run this on the VM, as your own user, from your own checkout of the repository: ```bash cd ~/ntnuhome/T18-Project-2 -git pull --ff-only -cd frontend -npm ci -npm run buildvm -curl -I http://localhost/project2/ +git switch main +./scripts/deploy.sh ``` -`npm run buildvm` builds with the `/project2/` base path, creates -`/var/www/html/project2` if needed, and copies the contents of `frontend/dist` there. -The copy runs only after a successful build. -Run this command as your normal VM user. -`sudo` may prompt for your password when publishing the files. - -The `dist/.` source copies the files directly into `project2`, including hidden files. -It avoids an extra `project2/dist` directory on repeated deployments. -Old files absent from the new build remain in the destination. - -Open [the application](http://it2810-18.idi.ntnu.no/project2/). -A successful HTTP check returns `200 OK`. -Apache serves the frontend after logout. You do not need `nohup` for the frontend. +The script asks for your `sudo` password once. It stops at the first error, and it builds and checks +everything before it touches the running site, so a failed build leaves the site as it was. It does this: -## Backend with nohup +1. Checks that the checkout is clean and on `main`, and gets the newest `main`. +2. Builds the frontend, installs the backend's packages and type-checks the backend. +3. Backs up the database to `/opt/project2/backups` and keeps the newest five backups. +4. Copies the backend to `/opt/project2/backend`, runs the database migrations, and restarts the + backend. If the new backend does not answer within 30 seconds, the script puts the previous code + back and starts that. Migrations that ran are not undone. +5. Copies the frontend to `/var/www/html/project2`. +6. Checks that the site answers, that the API answers through Apache, and that the cache headers are right. -The backend listens on port `3001`. -Configure PostgreSQL and `backend/.env` using the setup guides above before starting the backend. -Keep PostgreSQL on localhost, port `5432`. Keep credentials out of Git. +Tell the group before you deploy. The site is unavailable for a few seconds while the backend restarts. -### Start - -Use your normal VM account. Check whether port `3001` already has a listener: +Afterwards, look at the site in a private browser window, so no old code is cached. Delete test +users you made: ```bash -ss -ltnp 'sport = :3001' +sudo -u postgres psql -d vinmonopolet -c "DELETE FROM app_user WHERE username LIKE 'test\_%';" ``` -If a backend already uses the port, stop it before starting another instance. -See who started it and from which checkout, and coordinate with the group if it is another user. -Never stop another user's process without asking: - -```bash -pgrep -af 'src/server.ts' -ps -o pid,user,args -p "$(pgrep -f 'src/server.ts' | head -1)" -``` +Files from earlier builds stay in `/var/www/html/project2/assets` for 14 days, and are then deleted +by the next deploy. A visitor who has the old page open can then still load the parts of it they +have not opened yet. -Start the backend from its directory: +## Check the services and read the logs ```bash -cd ~/ntnuhome/T18-Project-2/backend -npm ci -mkdir -p logs -nohup node --import tsx src/server.ts >> logs/backend.log 2>&1 < /dev/null & -echo $! > logs/backend.pid +systemctl status project2-backend apache2 postgresql --no-pager +sudo journalctl -u project2-backend -n 50 --no-pager # the backend's log; add -f to follow it +sudo cat /opt/project2/REVISION # the commit that is deployed +curl -s http://127.0.0.1:3001/graphql -H 'content-type: application/json' -d '{"query":"{ wines(first: 1) { totalCount } }"}' ``` -`nohup` lets the process continue after SSH logout. The `&` starts it in the background. -The command appends output and errors to `logs/backend.log`. -It saves the Node process ID in `logs/backend.pid`. -The repository ignores `logs` directories. - -Check that the backend started: - -```bash -ps -p "$(cat logs/backend.pid)" -o pid,user,args -tail -n 50 logs/backend.log -curl -i http://127.0.0.1:3001/ -curl -s http://127.0.0.1:3001/graphql -H 'content-type: application/json' -d '{"query":"{ me { id } wines(first: 1) { totalCount } }"}' -``` +systemd starts the backend when the VM starts, and starts it again if it crashes. Restart it by hand +with `sudo systemctl restart project2-backend`. -The log should say `Backend listening`. The first `curl` shows HTTP `200` and database information; -`503` means the database query failed, so check the log and `backend/.env`. The second should answer -`{"data":{"me":null,"wines":{"totalCount":…}}}`. An error about a missing table or column means a -migration has not been run (see [Update and restart](#update-and-restart)). +## Restore a backup -Follow the log with: +The backups hold everything except the 21 million X-Wines ratings: accounts, reviews, lists and +wines. Use one if a deploy has damaged the data. Reviews and accounts made after the backup are lost. ```bash -tail -f logs/backend.log +sudo ls -lh /opt/project2/backups +sudo systemctl stop project2-backend +sudo cat /opt/project2/backups/.dump | sudo -u postgres pg_restore --clean --if-exists -d vinmonopolet ``` -Press **Ctrl+C** to stop following the log. The backend continues to run. +Then [load the dataset](#load-the-dataset) again to get the ratings back, and run the deploy script. +It runs the migrations that the backup lacks and starts the backend. -### Stop +## First-time setup -After reconnecting, use the same VM account and checkout that started the backend: +This is done once per VM. Steps 1 to 3 are done once for each person who deploys. -```bash -cd ~/ntnuhome/T18-Project-2/backend -backend_pid=$(cat logs/backend.pid) -ps -p "$backend_pid" -o pid,user,args -``` +1. **Install the programs:** + + ```bash + sudo apt update + sudo apt install apache2 postgresql git curl rsync ca-certificates + sudo systemctl enable --now apache2 postgresql + ``` -Check that the output identifies your Node process and this checkout's `src/server.ts`. -Then stop that process: +2. **Install Node.js 24** with [nvm](https://github.com/nvm-sh/nvm), as your own user: -```bash -kill -TERM "$backend_pid" -``` + ```bash + curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.8/install.sh | bash + exit # then connect again, so the shell loads nvm + nvm install 24 + nvm alias default 24 + ``` -Confirm that the process exited and port `3001` is free: +3. **Clone the repository** into your home directory: -```bash -ps -p "$backend_pid" -o pid,user,args -ss -ltnp 'sport = :3001' -``` + ```bash + mkdir -p ~/ntnuhome && cd ~/ntnuhome + git clone https://git.ntnu.no/IT2810-H26/T18-Project-2.git + ``` -An absent process produces no process row. An unused port produces no listener row. -A saved PID can become stale after a crash or reboot. -If it identifies another process, do not use it. Find the backend with `ss` first. +4. **Create the database** and its user with the Ubuntu steps in [database](database.md). -For a foreground backend started with `npm start`, press **Ctrl+C** in its terminal to stop it. -`nohup` does not restart the backend after a crash or VM reboot. -Start it again with the commands above. Use systemd if automatic restarts are needed. +5. **Create the user that runs the backend**, and give it the database password. The backend reads + `DATABASE_URL` from `/opt/project2/backend/.env`. This is the only `.env` on the VM: -## Apache configuration + ```bash + sudo useradd --system --home-dir /opt/project2 --shell /usr/sbin/nologin project2 + sudo mkdir -p /opt/project2/backend + sudo install -m 600 -o project2 -g project2 ~/ntnuhome/T18-Project-2/backend/.env.example /opt/project2/backend/.env + sudo nano /opt/project2/backend/.env + ``` -Apache serves the built frontend and forwards GraphQL requests to the backend. -The frontend asks for `/project2/graphql`, and Apache passes that on to the backend on port 3001. + Write `@`, `:`, `/`, `#` and `%` in the password as `%40`, `%3A`, `%2F`, `%23` and `%25`. + Leave `COOKIE_SECURE` commented out: the VM serves plain HTTP, and login would stop working. + If nobody knows the password, set a new one with + `sudo -u postgres psql -c "ALTER ROLE vinmonopolet_app WITH PASSWORD 'new_password';"`. -`FallbackResource` makes deep links such as `/project2/sok` work on reload: the files do not -exist on disk, so Apache serves `index.html` and React Router takes over. +6. **Configure Apache** as described under [Apache](#apache). -Configure this once, after starting the backend: +7. **Run the deploy script.** It installs the systemd service, creates the tables, and publishes the + site. A new database has no wines, so [load the dataset](#load-the-dataset) afterwards. -```bash -sudo nano /etc/apache2/conf-available/project2.conf -``` +## Apache -The file should contain: +Apache serves the built frontend and forwards `/project2/graphql` to the backend on port 3001. +The configuration is in `/etc/apache2/conf-available/project2.conf`: ```apache ProxyPass "/project2/graphql" "http://127.0.0.1:3001/graphql" @@ -256,17 +145,18 @@ ProxyPassReverse "/project2/graphql" "http://127.0.0.1:3001/graphql" ``` -Enable the configuration and check its syntax: +After a change, enable it, check the syntax and reload: ```bash sudo a2enmod proxy proxy_http headers sudo a2enconf project2 -sudo apache2ctl configtest +sudo apache2ctl configtest && sudo systemctl reload apache2 ``` -### Cache headers +`FallbackResource` makes deep links such as `/project2/sok` work on reload: the files do not exist +on disk, so Apache serves `index.html` and React Router takes over. -The two `Header` lines tell the browser what it can keep between visits: +### Cache headers - **Files in `assets/`** have a hash of their content in the name, such as `index-BL5R2qxO.js`. A changed file gets a new name, so the browser can keep each one for a year (`max-age=31536000`) @@ -274,195 +164,58 @@ The two `Header` lines tell the browser what it can keep between visits: - **`index.html`** always has the same name, and it names the hashed files. `no-cache` lets the browser store it, but makes it ask Apache on every visit if it has changed. Without this, a visitor could keep an old `index.html` after an update and ask for files that are gone. +- **`FallbackResource disabled`** makes a missing file in `assets/` give `404`. Without it, Apache + would answer with `index.html`, and the browser would keep that for a year under the missing + file's name. -`FallbackResource disabled` makes a missing file in `assets/` give `404`. Without it, Apache would -answer with `index.html` and let the browser keep that answer for a year under the missing file's name. - -The headers do not apply to `/project2/graphql`, because Apache forwards those requests and reads -no file from the directories. - -After a reload, check the headers. Take a file name from the first command's output for the second: - -```bash -curl -s http://localhost/project2/ | grep -o 'assets/index-[^"]*\.js' -curl -sI http://localhost/project2/assets/.js | grep -i cache-control -curl -sI http://localhost/project2/ | grep -i cache-control -curl -sI http://localhost/project2/sok | grep -i cache-control -curl -sI http://localhost/project2/assets/missing.js | head -1 -``` - -The first `Cache-Control` should be `public, max-age=31536000, immutable`, the next two `no-cache`, -and the last line `HTTP/1.1 404 Not Found`. See Apache's -[mod_headers documentation](https://httpd.apache.org/docs/2.4/mod/mod_headers.html#header) and MDN on +The headers do not apply to `/project2/graphql`, because Apache forwards those requests. The deploy +script checks both headers. See Apache's +[mod_headers](https://httpd.apache.org/docs/2.4/mod/mod_headers.html#header) and MDN on [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control). -If the check reports `Syntax OK`, reload Apache and try a query: - -```bash -sudo systemctl reload apache2 -curl -s -X POST http://localhost/project2/graphql -H 'Content-Type: application/json' -d '{"query":"{ wines(first: 1) { totalCount } }"}' -``` - -Expect a number of wines back. A `503` means Apache is running but cannot reach the backend, -so check that the backend process is still up. - -The file on the VM also has an older `ProxyPass "/api/hello"` from the first submission. -It does nothing now and can be removed the next time the configuration is touched. -See Apache's [reverse proxy documentation](https://httpd.apache.org/docs/2.4/mod/mod_proxy.html#examples). - -## Update and restart - -Do the backend first: new frontend code expects the new API, so publishing the frontend before the -backend runs the new code gives errors on the site until the backend is back. Tell the group before -you start, and check who runs the backend (see [Start](#start)). - -1. **Back up the database.** Migrations change tables, and the backup is the way back. - `sudo -u postgres` works without the database password. With the Full dataset the dump is - large, so check that the disk has room for it first: - - ```bash - df -h ~ # free space - sudo -u postgres psql -Atc "SELECT pg_size_pretty(pg_database_size('vinmonopolet'));" - mkdir -p ~/backups - sudo -u postgres pg_dump -Fc vinmonopolet > ~/backups/vinmonopolet-$(date +%F-%H%M).dump - ls -lh ~/backups - ``` - - The compressed dump (`-Fc`) is smaller than the database, but plan for it to be a sizeable - part of it. Delete old dumps in `~/backups` when the update has gone well. - -2. **Stop the backend** using [Stop](#stop) above. -3. **Update the checkout** to `main`: - - ```bash - cd ~/ntnuhome/T18-Project-2 - git status # clean, on main - git pull --ff-only - ``` - -4. **Install, migrate and start the backend.** The migration is safe to run every time: it only - runs the migrations that are missing. Without it, the new code asks for tables and columns - the database does not have yet: - - ```bash - cd backend - node --version # 24 or newer; otherwise `source ~/.bash_profile` - npm ci - npm run db:migrate - npm run db:seed:demo # the demo user in the README: creates it, or puts it back as it was - ``` - - Then start it with the `nohup` commands in [Start](#start), and run the checks there. Check - that the API knows the newest fields before you publish the frontend, for example: - - ```bash - curl -s http://127.0.0.1:3001/graphql -H 'content-type: application/json' -d '{"query":"{ wines(first: 1) { edges { node { myLists } } } }"}' - ``` - - `Cannot query field` means the old backend is still running, or the migration did not run. - -5. **Publish the frontend:** - - ```bash - cd ../frontend - npm ci - npm run buildvm - curl -I http://localhost/project2/ - ``` - -6. **Check the site** in a private browser window, so no old code is cached: the landing page and - search show wines, a wine shows its reviews, and you can log in, write a review, reload and - still be logged in. Delete test users afterwards: - - ```bash - sudo -u postgres psql -d vinmonopolet -c "DELETE FROM app_user WHERE username LIKE 'test\_%';" - ``` - -### Restore a backup - -If an update went wrong and the data must go back: stop the backend, restore, check out the -version that matches the backup, and start again. Reviews and accounts created after the backup -are lost. - -```bash -sudo -u postgres pg_restore --clean --if-exists -d vinmonopolet ~/backups/.dump -``` - ## Load the dataset -The VM uses the Full version of X-Wines (100 646 wines, 21 013 536 ratings). It replaced Slim on -17 November 2026. The database is now about 2.4 GB, and the VM had 2.7 GB of disk left afterwards. +The VM uses the Full version of X-Wines (100 646 wines, 21 013 536 ratings), which makes the database +about 2.4 GB. The files are not in the repository. The X-Wines authors share them in a +[Google Drive folder](https://drive.google.com/drive/folders/1LqguJNV-aKh1PuWMVx5ELA61LPfGfuu_), +linked from the [X-Wines repository](https://github.com/rogerioxavier/X-Wines). -The files are not in the repository, and they are not kept on the VM. The X-Wines authors share them -in a [Google Drive folder](https://drive.google.com/drive/folders/1LqguJNV-aKh1PuWMVx5ELA61LPfGfuu_), -linked from the [X-Wines repository](https://github.com/rogerioxavier/X-Wines). The two files are in -its `last` folder: `XWines_Full_100K_wines.csv` (36 MB) and `XWines_Full_21M_ratings.csv` (1.1 GB). - -1. **Back up the database** as in step 1 of [Update and restart](#update-and-restart). The import does - not touch student reviews or user accounts, but the backup is the way back if it goes wrong. - The backup taken before the switch is `~/vinmonopolet-slim-2026-11-17.dump` in `williasc`'s home. -2. **Check that the disk has room.** The database grows to about 2.4 GB, and PostgreSQL needs up to - 1 GB more while it writes. Start only if `df -h /` shows at least 4 GB free: +1. **Check that the disk has room.** PostgreSQL needs up to 1 GB more than the database while it + writes. Start only if this shows at least 4 GB free: ```bash df -h / ``` -3. **Download the files on the VM** into `/tmp`. `/tmp` is kept in memory, so the files do not use - disk space, and it is emptied when the VM restarts: +2. **Download the files** into `/tmp`, which is kept in memory and uses no disk space: ```bash mkdir -p /tmp/xwines-full && cd /tmp/xwines-full - curl -fL -o XWines_Full_100K_wines.csv 'https://drive.usercontent.google.com/download?id=1uEEipmKNxdiKUAhjH-K14JOSQ2BLRFss&export=download&confirm=t' - curl -fL -o XWines_Full_21M_ratings.csv 'https://drive.usercontent.google.com/download?id=15mwSBmGv-FY3-gJzL0wd1grav6CpYw8j&export=download&confirm=t' - wc -l XWines_Full_21M_ratings.csv # 21013537, including the header + curl -fL -o wines.csv 'https://drive.usercontent.google.com/download?id=1uEEipmKNxdiKUAhjH-K14JOSQ2BLRFss&export=download&confirm=t' + curl -fL -o ratings.csv 'https://drive.usercontent.google.com/download?id=15mwSBmGv-FY3-gJzL0wd1grav6CpYw8j&export=download&confirm=t' + wc -l ratings.csv # 21013537, including the header ``` -4. **Import them** with `nohup`, so the import is not stopped if the SSH connection drops: +3. **Import them** as a background service, so the import continues if the SSH connection drops: ```bash - cd ~/ntnuhome/T18-Project-2/backend - mkdir -p logs - nohup npx tsx src/scripts/seed-xwines.ts /tmp/xwines-full/XWines_Full_100K_wines.csv /tmp/xwines-full/XWines_Full_21M_ratings.csv >> logs/seed-full.log 2>&1 < /dev/null & - tail -f logs/seed-full.log + sudo systemd-run --unit=project2-import --uid=project2 --working-directory=/opt/project2/backend /opt/project2/bin/node --import tsx src/scripts/seed-xwines.ts /tmp/xwines-full/wines.csv /tmp/xwines-full/ratings.csv + sudo journalctl -u project2-import -f ``` - The import takes about 8 minutes on the VM: 14 s for the wines, 7.5 minutes for the ratings and - 13 s for the averages. The log reports every 500 000 ratings and ends with `Updated average ratings`. - Until then, the site shows old or missing averages. + It takes about 8 minutes on the VM. The log reports every 500 000 ratings and ends with + `Updated average ratings`. Until then, the site shows old or missing averages. -5. **Update the query statistics and delete the files:** +4. **Update the query statistics and delete the files:** ```bash - psql -h localhost -U vinmonopolet_app -d vinmonopolet -c 'VACUUM (ANALYZE) wine' -c 'VACUUM (ANALYZE) community_rating' + sudo -u postgres psql -d vinmonopolet -c 'VACUUM (ANALYZE) wine' -c 'VACUUM (ANALYZE) community_rating' rm -rf /tmp/xwines-full ``` -The import is safe to run more than once: wines that are already there are updated, not duplicated, -and ratings that are already there are skipped. Student reviews and user accounts are not touched. -The backend does not need a restart. - -The same script loads the Slim version (1 007 wines, 150 000 ratings) from -[Kaggle](https://www.kaggle.com/datasets/rogerioxavier/x-wines-slim-version), and the Test version -in `backend/data/xwines-test` (`npm run db:seed:test`), for a smaller local database. Loading Slim -does not remove Full wines that are already there. To go back to Slim on the VM, restore the backup -from before the switch (see [Restore a backup](#restore-a-backup)). - -## Command reference - -- [GNU nohup manual](https://www.gnu.org/software/coreutils/manual/html_node/nohup-invocation.html) -- [Bash background commands](https://www.gnu.org/software/bash/manual/html_node/Lists.html) - -## Check services and logs - -```bash -systemctl status apache2 postgresql --no-pager -ss -ltnp -pgrep -af 'node|npm' -sudo journalctl -u apache2 -n 30 --no-pager -pg_isready -h localhost -p 5432 -sudo -u postgres psql -``` +The import is safe to run more than once: wines that are already there are updated, and ratings that +are already there are skipped. Reviews and accounts are not touched, and the backend needs no restart. -Use `sudo systemctl start`, `stop`, or `restart`, followed by the service name. -In `psql`, use `\l` to list databases and `\q` to exit. +The same script loads the Slim version (1 007 wines, 150 000 ratings) from the same folder, and the +Test version in `backend/data/xwines-test`. Loading a smaller version does not remove wines that are +already there. diff --git a/frontend/package.json b/frontend/package.json index 6658415..720db89 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -6,7 +6,6 @@ "scripts": { "dev": "vite", "build": "tsc -b && vite build", - "buildvm": "npm run build -- --base=/project2/ && sudo mkdir -p /var/www/html/project2 && sudo cp -a dist/. /var/www/html/project2/", "lint": "eslint .", "preview": "vite preview", "format": "prettier --write .", diff --git a/scripts/deploy.sh b/scripts/deploy.sh new file mode 100755 index 0000000..edf51e8 --- /dev/null +++ b/scripts/deploy.sh @@ -0,0 +1,201 @@ +#!/usr/bin/env bash +# Updates the site on the VM to the newest `main`. Run it on the VM, as your own user, +# from your own checkout: +# +# ./scripts/deploy.sh +# +# It builds in your checkout and then copies the result to fixed places with sudo, so the +# running site does not depend on any one person's home directory: +# +# /var/www/html/project2 the built frontend, served by Apache +# /opt/project2/backend the backend code, run by the systemd service project2-backend +# /opt/project2/bin/node the Node.js binary the service runs with +# /opt/project2/backend.previous the backend from before this deploy, used if the new one fails +# /opt/project2/backups database backups without the X-Wines ratings, the newest five +# +# The script stops at the first error. Everything is built and checked before the running +# site is touched, so an error in the build leaves the site as it was. +# First-time setup of the VM is in docs/vm.md. + +set -euo pipefail + +# The values can be changed from the shell, which the test in a container uses. +APP_DIR="${APP_DIR:-/opt/project2}" +WEB_DIR="${WEB_DIR:-/var/www/html/project2}" +SERVICE="${SERVICE:-project2-backend}" +SERVICE_USER="${SERVICE_USER:-project2}" +DATABASE="${DATABASE:-vinmonopolet}" +API_URL="${API_URL:-http://127.0.0.1:3001/graphql}" +SITE_URL="${SITE_URL:-http://localhost/project2}" +BRANCH="${BRANCH:-main}" +KEEP_BACKUPS=5 +KEEP_OLD_ASSETS_DAYS=14 + +WINE_COUNT_QUERY='{"query":"{ wines(first: 1) { totalCount } }"}' + +step() { printf '\n\033[1m== %s\033[0m\n' "$1"; } +fail() { + printf '\n\033[31mDeploy stopped: %s\033[0m\n' "$1" >&2 + exit 1 +} + +# Runs a command in the published backend, as the user the service runs as. +as_service() { + (cd "$APP_DIR/backend" && sudo -u "$SERVICE_USER" env PATH="$APP_DIR/bin:/usr/bin:/bin" "$@") +} + +header() { curl -sI "$1" | tr -d '\r' | awk -F': ' -v name="$2" 'tolower($1) == tolower(name) { print $2 }'; } + +check_before_start() { + step "Check before start" + [ "$(id -u)" -ne 0 ] || fail "run the script as your own user, not as root. It asks for sudo itself." + for tool in git node npm curl rsync; do + command -v "$tool" >/dev/null || fail "$tool is not installed. See docs/vm.md." + done + local node_major + node_major="$(node --version | sed 's/^v\([0-9]*\).*/\1/')" + [ "$node_major" -ge 24 ] || fail "Node.js 24 or newer is needed, this is $(node --version). Run: nvm use 24" + + [ "$(git branch --show-current)" = "$BRANCH" ] || fail "the checkout is not on $BRANCH." + [ -z "$(git status --porcelain)" ] || fail "the checkout has changes that are not committed. See: git status" + + sudo -v || fail "sudo is needed to publish the files and restart the backend." + id "$SERVICE_USER" >/dev/null 2>&1 || fail "the user $SERVICE_USER does not exist. See \"First-time setup\" in docs/vm.md." + sudo test -f "$APP_DIR/backend/.env" || fail "$APP_DIR/backend/.env is missing. See \"First-time setup\" in docs/vm.md." +} + +update_checkout() { + step "Get the newest $BRANCH" + local script_before + script_before="$(git rev-parse HEAD:scripts/deploy.sh)" + git pull --ff-only + if [ "$(git rev-parse HEAD:scripts/deploy.sh)" != "$script_before" ]; then + echo "This script was updated. Starting again with the new version." + exec ./scripts/deploy.sh + fi + git log -1 --format='Deploying %h: %s' +} + +build() { + step "Build the frontend" + (cd frontend && npm ci && npm run build) + + step "Install and check the backend" + (cd backend && npm ci && npm run typecheck) +} + +back_up_database() { + step "Back up the users' data" + # Everything except the rows of community_rating: the 21 million X-Wines ratings are 2 GB + # and can be loaded again (see "Load the dataset" in docs/vm.md). The wines stay in the + # backup, because the reviews and lists point to them. + local file + file="$APP_DIR/backups/$DATABASE-$(date +%F-%H%M%S).dump" + sudo mkdir -p "$APP_DIR/backups" + sudo -u postgres pg_dump -Fc --exclude-table-data=community_rating "$DATABASE" | + sudo tee "$file" >/dev/null + sudo chmod 600 "$file" + echo "Saved $file ($(sudo du -h "$file" | cut -f1))" + # Keep the newest ones. The names sort by date. + sudo find "$APP_DIR/backups" -name "$DATABASE-*.dump" | sort -r | tail -n "+$((KEEP_BACKUPS + 1))" | + while read -r old; do sudo rm -f "$old"; done +} + +publish_backend() { + step "Publish the backend" + sudo mkdir -p "$APP_DIR/backend" "$APP_DIR/bin" + # A copy of the code that runs now, to go back to if the new code does not start. + sudo rsync -a --delete --exclude .env "$APP_DIR/backend/" "$APP_DIR/backend.previous/" + # --delete removes files that are gone from the repository. .env exists only on the VM. + sudo rsync -a --delete --no-owner --no-group --exclude .env --exclude logs backend/ "$APP_DIR/backend/" + sudo install -m 755 "$(command -v node)" "$APP_DIR/bin/node" + + if ! sudo cmp -s scripts/project2-backend.service "/etc/systemd/system/$SERVICE.service"; then + sudo install -m 644 scripts/project2-backend.service "/etc/systemd/system/$SERVICE.service" + sudo systemctl daemon-reload + sudo systemctl enable "$SERVICE" + echo "Installed the systemd service $SERVICE" + fi + + step "Update the database" + # Safe to run every time: only the migrations that are missing are run. + as_service node node_modules/node-pg-migrate/bin/node-pg-migrate.js up + # The demo user in the README: creates it, or puts it back as it was. It reviews wines, so a + # new database gets it on the first deploy after the dataset is loaded. + if [ "$(sudo -u postgres psql -At -d "$DATABASE" -c 'SELECT count(*) FROM wine')" -gt 0 ]; then + as_service node --import tsx src/scripts/seed-demo-user.ts + else + echo "The database has no wines yet, so the demo user is not made. See \"Load the dataset\" in docs/vm.md." + fi + + step "Restart the backend" + sudo systemctl restart "$SERVICE" + if ! wait_for_backend; then + sudo journalctl -u "$SERVICE" -n 30 --no-pager >&2 || true + echo "The new backend did not answer within 30 seconds. Going back to the previous code." >&2 + sudo rsync -a --delete --exclude .env "$APP_DIR/backend.previous/" "$APP_DIR/backend/" + sudo systemctl restart "$SERVICE" + if wait_for_backend; then + fail "the new backend did not start, and its log is above. The previous backend runs again. Migrations that ran are not undone." + fi + fail "the new backend did not start, and the previous one did not either. The log is above." + fi + echo "The backend answers on $API_URL" +} + +# Waits up to 30 seconds for the API to answer. +wait_for_backend() { + local tries=0 + until curl -sf "$API_URL" -H 'content-type: application/json' -d "$WINE_COUNT_QUERY" >/dev/null; do + tries=$((tries + 1)) + [ "$tries" -lt 30 ] || return 1 + sleep 1 + done +} + +publish_frontend() { + step "Publish the frontend" + sudo mkdir -p "$WEB_DIR" + sudo rsync -a --no-owner --no-group frontend/dist/ "$WEB_DIR/" + # Files from earlier builds stay for a while, so a visitor with the old page open can still + # load the parts of it they have not opened yet. After that they are only using disk space. + sudo find "$WEB_DIR/assets" -type f -mtime "+$KEEP_OLD_ASSETS_DAYS" -delete + git rev-parse HEAD | sudo tee "$APP_DIR/REVISION" >/dev/null +} + +check_site() { + step "Check the site" + local status answer asset cache + status="$(curl -s -o /dev/null -w '%{http_code}' "$SITE_URL/")" + [ "$status" = 200 ] || fail "$SITE_URL/ answered $status, not 200." + echo "ok $SITE_URL/ answers 200" + + answer="$(curl -s "$SITE_URL/graphql" -H 'content-type: application/json' -d "$WINE_COUNT_QUERY")" + [[ "$answer" =~ \"totalCount\":[0-9]+ ]] || fail "the API through Apache answered: $answer" + echo "ok the API through Apache answers: $answer" + + cache="$(header "$SITE_URL/" Cache-Control)" + [ "$cache" = "no-cache" ] || fail "index.html has Cache-Control \"$cache\", not \"no-cache\". See \"Apache\" in docs/vm.md." + echo "ok index.html is sent with no-cache" + + asset="$(curl -s "$SITE_URL/" | grep -o 'assets/index-[^"]*\.js' | head -1)" + cache="$(header "$SITE_URL/$asset" Cache-Control)" + [[ "$cache" == *immutable* ]] || fail "$asset has Cache-Control \"$cache\", without \"immutable\". See \"Apache\" in docs/vm.md." + echo "ok $asset is sent with $cache" +} + +# Everything is in functions and started from the last line, so Bash has read the whole file +# before `git pull` can change it. +main() { + cd "$(dirname "${BASH_SOURCE[0]}")/.." + check_before_start + update_checkout + build + back_up_database + publish_backend + publish_frontend + check_site + printf '\n\033[32mDeployed %s to %s\033[0m\n' "$(git rev-parse --short HEAD)" "$SITE_URL/" +} + +main "$@" diff --git a/scripts/project2-backend.service b/scripts/project2-backend.service new file mode 100644 index 0000000..8e95c26 --- /dev/null +++ b/scripts/project2-backend.service @@ -0,0 +1,23 @@ +# The backend on the VM. scripts/deploy.sh installs this file and restarts the service. +# Follow the log with: sudo journalctl -u project2-backend -f +[Unit] +Description=Kork & Krone backend (GraphQL API on port 3001) +After=network.target postgresql.service +Wants=postgresql.service + +[Service] +User=project2 +Group=project2 +WorkingDirectory=/opt/project2/backend +# The Node.js binary is a copy of the one the deploy ran with, so the service does not +# depend on anyone's home directory. DATABASE_URL comes from /opt/project2/backend/.env. +ExecStart=/opt/project2/bin/node --import tsx src/server.ts +Restart=on-failure +RestartSec=3 +NoNewPrivileges=true +ProtectSystem=full +ProtectHome=true +PrivateTmp=true + +[Install] +WantedBy=multi-user.target From 8ddb762035c1007bc8a9eb3896195b1e254efe05 Mon Sep 17 00:00:00 2001 From: William Mikal Ruud Schmidt Date: Tue, 24 Nov 2026 14:53:26 +0100 Subject: [PATCH 2/2] Fixes for comments from @siverne --- docs/vm.md | 19 +++++++++++++++++++ frontend/README.md | 7 +++---- scripts/deploy.sh | 34 +++++++++++++++++++++++++--------- 3 files changed, 47 insertions(+), 13 deletions(-) diff --git a/docs/vm.md b/docs/vm.md index 02f6eed..0427aad 100644 --- a/docs/vm.md +++ b/docs/vm.md @@ -49,6 +49,25 @@ Files from earlier builds stay in `/var/www/html/project2/assets` for 14 days, a by the next deploy. A visitor who has the old page open can then still load the parts of it they have not opened yet. +### If the script stops + +The last line, in red, says what failed. Every step can be repeated, so fix the cause and run the +script again. Where it stopped tells you what state the site is in: + +| It stopped at | The site now | Do this | +| ----------------------------------------------------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------- | +| Check before start, Get the newest `main`, the builds, the backup | As before the deploy | Fix what the message says and run again | +| Update the database | The old backend runs, and its code is back in place. Migrations that finished stay | Fix the migration or the demo user in a new commit, merge, run again | +| Restart the backend | The previous backend runs again. The message says so if it does not | Read the log above the message, fix the code, merge, run again | +| Publish the frontend, Check the site | The new backend runs. The frontend can be the old or the new one | Often the Apache configuration, see [Apache](#apache). Then run again | + +If the backend is down and the fix takes time, put the previous backend back by hand: + +```bash +sudo rsync -a --delete --exclude .env /opt/project2/backend.previous/ /opt/project2/backend/ +sudo systemctl restart project2-backend +``` + ## Check the services and read the logs ```bash diff --git a/frontend/README.md b/frontend/README.md index fba9939..5c49441 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -17,7 +17,6 @@ error message if the request fails. For production hosting, configure the web server to forward `/api/hello` to the backend's `/` endpoint as well. -To build and publish on the VM, run `npm run buildvm` from `frontend/`. -This builds for `/project2/` and uses `sudo` to copy the output into -`/var/www/html/project2`. See the [VM guide](../docs/vm.md) for deployment -and backend start/stop instructions. +To build and publish on the VM, run `./scripts/deploy.sh` from the repository root on the VM. +It builds for `/project2/` and uses `sudo` to copy the output into `/var/www/html/project2`. +See the [VM guide](../docs/vm.md). diff --git a/scripts/deploy.sh b/scripts/deploy.sh index edf51e8..0cf0546 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -118,14 +118,11 @@ publish_backend() { fi step "Update the database" - # Safe to run every time: only the migrations that are missing are run. - as_service node node_modules/node-pg-migrate/bin/node-pg-migrate.js up - # The demo user in the README: creates it, or puts it back as it was. It reviews wines, so a - # new database gets it on the first deploy after the dataset is loaded. - if [ "$(sudo -u postgres psql -At -d "$DATABASE" -c 'SELECT count(*) FROM wine')" -gt 0 ]; then - as_service node --import tsx src/scripts/seed-demo-user.ts - else - echo "The database has no wines yet, so the demo user is not made. See \"Load the dataset\" in docs/vm.md." + if ! update_database; then + # The old process still runs, but a restart would start the new code. Put the code back, + # so a restart or a crash gives the same backend as before the deploy. + restore_previous_backend + fail "the database update failed, and its error is above. The previous backend code is back in place and still runs. Migrations that finished are not undone." fi step "Restart the backend" @@ -133,7 +130,7 @@ publish_backend() { if ! wait_for_backend; then sudo journalctl -u "$SERVICE" -n 30 --no-pager >&2 || true echo "The new backend did not answer within 30 seconds. Going back to the previous code." >&2 - sudo rsync -a --delete --exclude .env "$APP_DIR/backend.previous/" "$APP_DIR/backend/" + restore_previous_backend sudo systemctl restart "$SERVICE" if wait_for_backend; then fail "the new backend did not start, and its log is above. The previous backend runs again. Migrations that ran are not undone." @@ -143,6 +140,25 @@ publish_backend() { echo "The backend answers on $API_URL" } +# Runs the migrations and makes the demo user. Returns an error at the first step that fails. +update_database() { + # Safe to run every time: only the migrations that are missing are run. + as_service node node_modules/node-pg-migrate/bin/node-pg-migrate.js up || return 1 + # The demo user in the README: creates it, or puts it back as it was. It reviews wines, so a + # new database gets it on the first deploy after the dataset is loaded. + local wines + wines="$(sudo -u postgres psql -At -d "$DATABASE" -c 'SELECT count(*) FROM wine')" || return 1 + if [ "$wines" -gt 0 ]; then + as_service node --import tsx src/scripts/seed-demo-user.ts || return 1 + else + echo "The database has no wines yet, so the demo user is not made. See \"Load the dataset\" in docs/vm.md." + fi +} + +restore_previous_backend() { + sudo rsync -a --delete --exclude .env "$APP_DIR/backend.previous/" "$APP_DIR/backend/" +} + # Waits up to 30 seconds for the API to answer. wait_for_backend() { local tries=0