feature/backup #96

Merged
admin merged 4 commits from feature/backup into master 2026-10-07 13:13:37 +03:30
7 changed files with 347 additions and 0 deletions

View File

@@ -12,6 +12,8 @@ Local development: see **`backend/README.md`** and **`frontend/README.md`**.
**Full guide:** [`infrastructure/DEPLOY.md`](infrastructure/DEPLOY.md)
**Database backup and restore:** [`infrastructure/BACKUP.md`](infrastructure/BACKUP.md)
Git tag **`v1.0.1`** → Gitea workflow [`.gitea/workflows/prod-tag-deploy.yml`](.gitea/workflows/prod-tag-deploy.yml) builds images (URLs baked for nudentic.ir), pushes to Gitea registry, SSH-deploys the Linux stack.
First-time SSL / Hub fallback: same `DEPLOY.md`.

227
infrastructure/BACKUP.md Normal file
View File

@@ -0,0 +1,227 @@
# Manual database backup (nudentic.ir)
Copy-paste runbook for the production Postgres database. Use it when you need a dump in a hurry, a copy of production data on your Mac, or a restore after something has gone wrong.
A **dump** is one file that contains the `dyolink_db` tables: users, patients, appointments, treatments, lab cases, billing, and so on. Taking a dump does **not** stop the site. Postgres reads a consistent snapshot while the app keeps running.
The dump does **not** contain photo or case-file bytes. Those files live on disk under `uploads/`. The database only stores the file name and the path. After a restore, the case row is back; opening the file still needs the file on disk.
## Names
| What | Value |
|------|--------|
| SSH | `dyolink@185.243.48.140` |
| Server directory | `/opt/dyolink/infrastructure` |
| Production Postgres container | `dyolink_db_prod` |
| Database | `dyolink_db` |
| Dump folder on the server | `/opt/dyolink/infrastructure/database/backups` |
| Same folder inside the container | `/backups` |
| Copy on the Mac | `~/Documents/dental/nudentic-backups/` |
| Local Postgres container | `dyolink-postgres-dev` |
The container already has `POSTGRES_USER` and `POSTGRES_DB`. Do not type the password, and do not print `database.env`.
Keep dump files private. They contain patient and account data. Do not commit them, and do not put them inside the git repo. `~/Documents/dental/nudentic-backups/` is outside the repo.
## Do not
- Do not run `infrastructure/scripts/manage.sh backup`. It uses `-U postgres`. Production has no `postgres` role; the user is `dyolink_user`.
- Do not run `docker volume rm dyolink_postgres_data_prod` or `docker volume prune`. That deletes the live database.
- Do not run the `scp` copy while your prompt is `dyolink@srv…`. That copies the file onto the server again. `scp` runs on the Mac, where the prompt is `rameen@…`.
---
## Automatic backups (three times a day)
The server keeps a new dump at three Iran times (`Asia/Tehran`, UTC+3:30). Each run adds a file. It does not replace the previous one. Files named `nudentic_YYYYMMDD_HHMMSS.dump` that are older than 3 days are deleted. That is about 9 files. `nudentic_before_restore_*.dump` is never deleted by this job.
| Iran time | What it captures |
|-----------|------------------|
| 02:00 | The previous day, after the clinic is closed |
| 11:00 | Morning work |
| 16:00 | Most of the afternoon |
The longest gap is overnight, from 16:00 to 02:00. Rows saved in that gap are only in the live database until the next file. These files sit on the same disk as the database. Copy them to the Mac with section 2 when you want copies that survive a dead server. Filenames use UTC, the same clock as the first manual dump.
The script is [`scripts/backup-prod-db.sh`](scripts/backup-prod-db.sh). A git tag deploy does not copy it, so put it on the server once from the Mac:
```bash
scp infrastructure/scripts/backup-prod-db.sh dyolink@185.243.48.140:/opt/dyolink/infrastructure/scripts/
ssh dyolink@185.243.48.140 'chmod +x /opt/dyolink/infrastructure/scripts/backup-prod-db.sh && /opt/dyolink/infrastructure/scripts/backup-prod-db.sh'
```
The last command writes one dump immediately so you can see it in `database/backups` before cron is installed.
Cron is also one time, on the server, as the `dyolink` user. Check the server clock first:
```bash
date
```
If that time is already Iran time (offset `+0330`), install these three lines:
```bash
(crontab -l 2>/dev/null | grep -v backup-prod-db.sh; cat <<'EOF'
0 2 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
0 11 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
0 16 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
EOF
) | crontab -
```
If `date` shows UTC, the same Iran times are 22:30, 07:30, and 12:30 UTC:
```bash
(crontab -l 2>/dev/null | grep -v backup-prod-db.sh; cat <<'EOF'
30 22 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
30 7 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
30 12 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
EOF
) | crontab -
```
Confirm with `crontab -l`. Putting this in git does not turn cron on. On nudentic the UTC lines above are already installed, so `date` on that server prints UTC and the jobs run at 22:30, 07:30, and 12:30 UTC.
---
## 1. Take a backup
The site stays up. SSH in:
```bash
ssh dyolink@185.243.48.140
```
On the server (`dyolink@srv…`):
```bash
cd /opt/dyolink/infrastructure
mkdir -p database/backups
docker exec dyolink_db_prod sh -c \
'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc -f /backups/nudentic_$(date +%Y%m%d_%H%M%S).dump'
ls -lh database/backups
docker exec dyolink_db_prod sh -c 'pg_restore -l /backups/nudentic_*.dump | head -40'
```
`ls -lh` must be run from `/opt/dyolink/infrastructure`, or use `ls -lh` with no extra path if you are already inside `database/backups`.
A good dump is larger than a few kilobytes. The `pg_restore -l` list should name `dbname: dyolink_db` and tables such as `patients` and `lab_cases`. A file of a few bytes means the dump failed.
Leave this SSH session open if you still need it. The next step is a **new** terminal on the Mac.
---
## 2. Copy the dump to the Mac
Open a terminal on the Mac. The prompt must be `rameen@…`, not `dyolink@srv…`. From the repo:
```bash
cd /Users/rameen/Documents/dental/dyolink
./infrastructure/scripts/copy-prod-backup.sh
```
It asks for the server password once and does not save it. It copies every `.dump` file from the server backup folder into `~/Documents/dental/nudentic-backups/` and prints the list. A good file is larger than a few kilobytes (the first successful dump was 574K).
### Every day at 17:00
Run that script once a day at **17:00 Iran time**, after the 16:00 server dump. One run copies every dump still on the server, including the 02:00 and 11:00 files, so it does not need to run three times. The Mac clock must be Iran time. If the Mac is asleep at 17:00, that run is skipped; the files stay on the server for 3 days, so the next afternoon the Mac is awake still copies them.
At 17:00 a password box appears on the Mac. Type the server password and click Copy. It is not saved. You must be logged in so the box can appear. Cancel skips that day’s copy.
Install the 17:00 job (this does not happen from git by itself):
```bash
mkdir -p ~/Documents/dental/nudentic-backups ~/Library/LaunchAgents
cp infrastructure/launchd/ir.nudentic.copy-prod-backup.plist ~/Library/LaunchAgents/
launchctl bootout gui/$(id -u) ~/Library/LaunchAgents/ir.nudentic.copy-prod-backup.plist 2>/dev/null || true
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/ir.nudentic.copy-prod-backup.plist
```
Output goes to `~/Documents/dental/nudentic-backups/copy.log`.
---
## 3. Load the dump into the local database
This **deletes** the current local `dyolink_db` and replaces it with the dump. Production is not touched.
Stop the local API first (`npm run start:dev` in `backend/`). Postgres itself stays up.
From `backend/`, start local Postgres if it is not already running:
```bash
cd /Users/rameen/Documents/dental/dyolink/backend
docker compose -f docker-compose.postgres.yml up -d
```
The container name is `dyolink-postgres-dev`. `DATABASE_URL` in `backend/.env` should already point at `localhost` and database `dyolink_db`.
On the Mac, copy the dump into that container and replace the local database. Change the filename if yours is different.
```bash
docker cp ~/Documents/dental/nudentic-backups/nudentic_YYYYMMDD_HHMMSS.dump dyolink-postgres-dev:/tmp/nudentic.dump
docker exec dyolink-postgres-dev sh -c 'psql -U "$POSTGRES_USER" -d postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '\''dyolink_db'\'' AND pid <> pg_backend_pid();"'
docker exec dyolink-postgres-dev sh -c 'dropdb -U "$POSTGRES_USER" --if-exists dyolink_db && createdb -U "$POSTGRES_USER" dyolink_db'
docker exec dyolink-postgres-dev sh -c 'pg_restore -U "$POSTGRES_USER" -d dyolink_db --no-owner --no-acl /tmp/nudentic.dump'
docker exec dyolink-postgres-dev sh -c 'psql -U "$POSTGRES_USER" -d dyolink_db -c "\dt"'
```
`pg_restore` may print warnings. If `\dt` lists tables such as `patients`, `lab_cases`, and `users`, the restore worked.
Start the API and the frontend the way you usually do. Sign in with a production account: the password hashes came with the dump. Local `.env` secrets stay as they are.
Attachment links will not open files on the Mac, because those files were not in the dump.
---
## 4. Emergency: put a dump back on production
**This replaces the live nudentic.ir database.** Everything saved after that dump’s timestamp is gone. Run this only when you have decided the current production data should be discarded.
SSH in and go to the infrastructure directory:
```bash
ssh dyolink@185.243.48.140
cd /opt/dyolink/infrastructure
```
**4a. Save the database you are about to replace.** If the restore is wrong, this file is the way back.
```bash
docker exec dyolink_db_prod sh -c \
'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc -f /backups/nudentic_before_restore_$(date +%Y%m%d_%H%M%S).dump'
ls -lh database/backups
```
**4b. If the dump you want is only on the Mac,** send it to the server first. Run this on the Mac, not inside SSH:
```bash
scp ~/Documents/dental/nudentic-backups/nudentic_YYYYMMDD_HHMMSS.dump \
dyolink@185.243.48.140:/opt/dyolink/infrastructure/database/backups/
```
**4c. Stop the API** so it cannot write during the restore. Postgres stays running.
```bash
docker compose -f docker-compose.prod.yml --env-file .env stop backend
```
**4d. Load the chosen dump.** Replace the filename with the dump you intend to keep (not the `before_restore` file, unless that is the one you want).
```bash
docker exec dyolink_db_prod sh -c 'psql -U "$POSTGRES_USER" -d postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '\''dyolink_db'\'' AND pid <> pg_backend_pid();"'
docker exec dyolink_db_prod sh -c 'dropdb -U "$POSTGRES_USER" --if-exists dyolink_db && createdb -U "$POSTGRES_USER" dyolink_db'
docker exec dyolink_db_prod sh -c 'pg_restore -U "$POSTGRES_USER" -d dyolink_db --no-owner --no-acl /backups/nudentic_YYYYMMDD_HHMMSS.dump'
```
**4e. Start the API again.**
```bash
docker compose -f docker-compose.prod.yml --env-file .env start backend
```
On startup the API runs `prisma migrate deploy` and the reference-data seed. That brings the schema in line with the running app if the app is newer than the dump. It does not delete the restored patients and cases.
**4f. Check the site.** Open `https://nudentic.ir/api/health`, then sign in and open a case you know was in that dump.
Case rows come back with the dump. Photo and case files on the server disk are left as they are. A database restore does not roll those files backward or forward.

View File

@@ -505,6 +505,8 @@ docker compose -f docker-compose.prod.yml --env-file .env exec frontend \
---
Database dump and restore (take a backup, copy it off the server, load it locally, or restore production): [`BACKUP.md`](BACKUP.md).
## File reference
| Path on server | Purpose |

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>ir.nudentic.copy-prod-backup</string>
<key>WorkingDirectory</key>
<string>/Users/rameen/Documents/dental/dyolink</string>
<key>ProgramArguments</key>
<array>
<string>/Users/rameen/Documents/dental/dyolink/infrastructure/scripts/copy-prod-backup.sh</string>
</array>
<key>StartCalendarInterval</key>
<dict>
<key>Hour</key>
<integer>17</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
<key>StandardOutPath</key>
<string>/Users/rameen/Documents/dental/nudentic-backups/copy.log</string>
<key>StandardErrorPath</key>
<string>/Users/rameen/Documents/dental/nudentic-backups/copy.log</string>
</dict>
</plist>

View File

@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Scheduled production dump. Run on the Linux host as the dyolink user (cron).
# Does not stop the site. Keeps nudentic_YYYYMMDD_HHMMSS.dump for 3 days.
# Does not delete nudentic_before_restore_*.dump.
set -euo pipefail
INFRA="${PROD_INFRA_DIR:-/opt/dyolink/infrastructure}"
BACKUP_DIR="$INFRA/database/backups"
CONTAINER="${POSTGRES_CONTAINER:-dyolink_db_prod}"
STAMP="$(date -u +%Y%m%d_%H%M%S)"
FILE="$BACKUP_DIR/nudentic_${STAMP}.dump"
mkdir -p "$BACKUP_DIR"
echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] Starting dump nudentic_${STAMP}.dump"
docker exec -e BACKUP_STAMP="$STAMP" "$CONTAINER" \
sh -c 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc -f "/backups/nudentic_${BACKUP_STAMP}.dump"'
if [ ! -s "$FILE" ]; then
echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] Backup failed: $FILE is missing or empty" >&2
exit 1
fi
BYTES=$(wc -c < "$FILE" | tr -d ' ')
echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] Wrote $FILE ($BYTES bytes)"
# 8 digits after nudentic_ so nudentic_before_restore_*.dump is left alone.
find "$BACKUP_DIR" -maxdepth 1 -type f \
-name 'nudentic_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_*.dump' \
-mtime +3 -delete
echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] Removed scheduled dumps older than 3 days"

View File

@@ -0,0 +1,4 @@
#!/bin/bash
# Shown by SSH when the copy runs with no terminal (the 17:00 Mac job).
# Prints the password to SSH only. Does not save it.
osascript -e 'text returned of (display dialog "Enter the nudentic server password." default answer "" with hidden answer buttons {"Cancel", "Copy"} default button "Copy" cancel button "Cancel" with title "Nudentic backup")'

View File

@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# Run on the Mac. Asks for the server password once and copies every dump
# in the production backup folder to ~/Documents/dental/nudentic-backups/.
# Does not save the password.
set -euo pipefail
REMOTE="dyolink@185.243.48.140"
REMOTE_DIR="/opt/dyolink/infrastructure/database/backups"
DEST="${HOME}/Documents/dental/nudentic-backups"
CONTROL="$(mktemp -u "${TMPDIR:-/tmp}/dyolink-backup-ssh.XXXXXX")"
ASKPASS="$(cd "$(dirname "$0")" && pwd)/copy-prod-backup-askpass.sh"
SSH_BASE=(
-o ControlPath="$CONTROL"
-o PreferredAuthentications=password
-o PubkeyAuthentication=no
)
cleanup() {
ssh -o ControlPath="$CONTROL" -O exit "$REMOTE" >/dev/null 2>&1 || true
rm -f "$CONTROL"
}
trap cleanup EXIT
mkdir -p "$DEST"
# A terminal asks in the terminal. The 17:00 job has no terminal, so a password box is shown.
if [ ! -t 0 ]; then
export SSH_ASKPASS="$ASKPASS"
export SSH_ASKPASS_REQUIRE=force
echo "Waiting for the password box."
else
echo "Connecting to ${REMOTE}. Enter the server password once."
fi
ssh -o ControlMaster=yes -o ControlPersist=60 "${SSH_BASE[@]}" "$REMOTE" true
FILES="$(
ssh "${SSH_BASE[@]}" "$REMOTE" \
"ls -1 ${REMOTE_DIR}/*.dump 2>/dev/null" \
|| true
)"
if [ -z "$FILES" ]; then
echo "No dump found in ${REMOTE_DIR}." >&2
exit 1
fi
while IFS= read -r FILE; do
[ -z "$FILE" ] && continue
scp "${SSH_BASE[@]}" "${REMOTE}:${FILE}" "${DEST}/"
done <<< "$FILES"
echo "Copied to ${DEST}:"
ls -lh "${DEST}"/*.dump