Metadata-Version: 2.5
Name: lts-backup-cli
Version: 2.0.0
Summary: LTS backup utility: per-server restic backups of Apache vhosts, MariaDB databases and folders over SSH/SFTP, with discovery and scheduled rotation.
Author-email: LTS <joaomartins@lts.pt>
License: BSD-3-Clause
License-File: LICENSE
Keywords: apache,backup,cli,mariadb,mysql,restic,restore,sftp,systemd
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: BSD License
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: System :: Archiving :: Backup
Requires-Python: >=3.9
Requires-Dist: click<9,>=8.1
Requires-Dist: questionary<3,>=2.0
Requires-Dist: tomli-w>=1.0
Requires-Dist: tomli>=2.0; python_version < '3.11'
Provides-Extra: dev
Requires-Dist: behave>=1.2.6; extra == 'dev'
Requires-Dist: build>=1.0; extra == 'dev'
Requires-Dist: mypy>=1.8; extra == 'dev'
Requires-Dist: pytest-cov>=4; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Requires-Dist: twine>=5; extra == 'dev'
Description-Content-Type: text/markdown

# lts-backup-cli — `ltsbu`

`ltsbu` gives every **server** its own set of [restic](https://restic.net) backups, stored on SFTP
storage and made **incrementally on a schedule, with automatic rotation**:

- **one repo per Apache/httpd vhost**: its DocumentRoot
- **one database repo per server**: any number of MariaDB databases, each in its own snapshot
- **one repo per extra folder**: anything else on the server, such as `/etc/apache2`

`ltsbu discover <host>` logs in to a server over SSH, finds its vhosts and databases, lets you pick
what to back up and installs the systemd timers. Run it again whenever you want to change anything.

```
┌──── admin box (ltsbu) ────┐        ┌──────── web server ────────┐        ┌─── storage ───┐
│ config, restic passwords, │  ssh   │ restic · mariadb-dump      │  SFTP  │ /srv/restic/  │
│ systemd timers            │ ─────▶ │ vhost DocumentRoots        │ ─────▶ │   <server>/   │
│ ltsbu discover/backup/... │        │ MariaDB (localhost)        │        │     <repo>/   │
└───────────────────────────┘        └────────────────────────────┘        └───────────────┘
```

- **Central pull.** ltsbu runs on one admin box. Commands run on each web server over SSH, so the
  web servers only need `restic`, the MariaDB client and an SSH login. If the admin box itself is
  the server, use the host `localhost` to run everything locally.
- **Incremental, every 2 hours, plus a weekly run** at a staggered night slot. After each run ltsbu
  rotates (`restic forget`), and the weekly run also prunes. Two backups never run at the same time.
- **Databases are streamed** (`mariadb-dump | restic backup --stdin`): no dump file is ever written to disk.
- **Verified before use.** The MariaDB admin login is checked during `discover` and saved on the
  server (`0600`). `ltsbu doctor` re-checks it with every database, the paths, the storage route,
  the repos and the timers.
- **Secrets never appear in a process list or a log.**

> **Upgrading from 0.x?** Version 2 is a clean break. The old model, one snapshot per label holding
> files plus a dump, is gone, and so is `ltsbu configure`. ltsbu refuses a v1 `config.toml` with a
> hint: move it aside and run `ltsbu discover <host>`. Old snapshots remain readable with plain restic.

---

## Contents

1. [Requirements](#requirements)
2. [Installation](#installation)
3. [Quick start](#quick-start)
4. [Commands](#commands): `discover` · `doctor` · `list` · `backup` · `snapshot` · `restore` · `forget` · `credentials`
5. [Common options](#common-options)
6. [How backups work](#how-backups-work)
7. [Schedule and rotation](#schedule-and-rotation)
8. [Files and configuration](#files-and-configuration)
9. [Managed SSH config blocks](#managed-ssh-config-blocks)
10. [Restoring](#restoring)
11. [Moving to another admin box / disaster recovery](#moving-to-another-admin-box--disaster-recovery)
12. [Troubleshooting](#troubleshooting)
13. [Development](#development)
14. [License](#license)

---

## Requirements

| Where | Component | Version | Notes |
|---|---|---|---|
| admin box | OS | Rocky Linux 8.10, Ubuntu 22.04 | with systemd (timers) |
| admin box | Python | ≥ 3.9 | Rocky 8: `python39` package; Ubuntu 22.04: system 3.10 |
| admin box | OpenSSH client | any | key-based login to each server |
| web server | restic | ≥ 0.12 | Rocky 8: official release binary (not in EPEL 8); Ubuntu: `apt` (0.12.1) |
| web server | MariaDB client | 10.4+ | **only if it has a database repo**: `mariadb`/`mysql` and `mariadb-dump`/`mysqldump` |
| web server | OpenSSH client + bash | any | restic reaches the storage over SFTP |
| storage | SSH server with SFTP | any | the default on any Linux or NAS |

## Installation

On the **admin box**:

```bash
# Rocky Linux 8.10
sudo dnf install -y python39 python39-pip openssh-clients
python3.9 -m pip install --user lts-backup-cli

# Ubuntu 22.04
sudo apt install -y python3-pip openssh-client
python3 -m pip install --user lts-backup-cli

ltsbu --version          # make sure ~/.local/bin is on PATH (or use pipx)
```

On every **web server**:

```bash
# Rocky Linux 8.10: restic is not packaged in EPEL 8, install the official static binary
curl -fsSL https://github.com/restic/restic/releases/download/v0.16.4/restic_0.16.4_linux_amd64.bz2 \
  | bunzip2 | sudo tee /usr/local/bin/restic >/dev/null && sudo chmod 755 /usr/local/bin/restic
sudo dnf install -y mariadb openssh-clients            # MariaDB client only for database backups

# Ubuntu 22.04
sudo apt install -y restic mariadb-client openssh-client
```

## Quick start

1. **SSH keys.** The admin box must log in to the web server, and the web server must log in to the
   storage:

   ```bash
   # on the admin box
   ssh-keygen -t ed25519 -f ~/.ssh/id_ltsbu -N '' && ssh-copy-id -i ~/.ssh/id_ltsbu.pub root@web1.example.com
   # on the web server
   ssh-keygen -t ed25519 -f ~/.ssh/id_storage -N '' && ssh-copy-id -i ~/.ssh/id_storage.pub restic@nas.example.com
   ```

2. **Discover the server** (interactive):

   ```bash
   ltsbu discover web1.example.com
   ```

   The wizard asks for, or detects:
   - the SSH login. A host already defined in your `~/.ssh/config` is used as is.
   - the storage host, user, base path and the key **on the server**
   - the **MariaDB admin ("sa") login**, if no working one is saved yet. It is verified and stored
     `0600` on the server.
   - **vhosts** to back up, one repo each (multi-select, all checked by default)
   - **databases** for the server's `db` repo (multi-select)
   - extra **folders**, one repo each
   - optionally a custom schedule and retention per repo (default: every 2h + weekly, rotated)
   - a summary, then: initialise the restic repos and install the timers

3. **Check everything:** `ltsbu doctor`

4. **Done.** Backups now run on their own. To run one by hand and look at it:

   ```bash
   ltsbu backup --server web1 --all
   ltsbu snapshot --server web1 --repo db
   ```

> **Keep the restic passwords safe.** Without them the repos can't be decrypted. They live in
> `~/.config/ltsbu/servers/<server>/<repo>.pass` on the admin box, with a copy on the server.
> Keep an offline copy with `ltsbu credentials export` (see [below](#moving-to-another-admin-box--disaster-recovery)).

## Commands

Every command accepts the [common options](#common-options), before or after the command name.

### `ltsbu discover HOST`

Creates or edits the backups of one server. `HOST` is a hostname or IP address, or a `Host` alias
from your `~/.ssh/config` (then ltsbu writes no SSH block for it), or `localhost`.

Running it again for the same server is **edit mode**:
- current choices are the defaults
- the vhosts' DocumentRoots are refreshed
- new repos get a password and a staggered schedule
- the server-side secrets and timers are refreshed

Repos you uncheck are only removed after an explicit confirmation (`--remove` when non-interactive).
Removing a repo stops its timers and drops it from the config, **but never deletes restic data**.

For automation, pass the answers as options with `--non-interactive`:

```bash
export LTSBU_DB_PASSWORD='…'            # used with --db-user; never on the command line
ltsbu discover web1.example.com --non-interactive \
  --ssh-user root --identity ~/.ssh/id_ltsbu \
  --storage-host nas.example.com --storage-user restic --storage-path /srv/restic \
  --storage-identity /root/.ssh/id_storage \
  --db-user root --vhosts all --databases shop_db,blog_db --folders "/etc/apache2"
```

| Option | Default |
|---|---|
| `--server LABEL` | derived from the host (`web1` for `web1.example.com`) |
| `--ssh-user`, `--ssh-port`, `--identity` | *(required for a new server unless HOST is an ssh alias)*, `22`, none |
| `--storage-host`, `--storage-user` | *(required for a new server)* |
| `--storage-port`, `--storage-path`, `--storage-identity` | `22`, `/srv/restic`, the server's default keys |
| `--db-user` / `--no-db-login` | password from `$LTSBU_DB_PASSWORD` / skip databases |
| `--vhosts`, `--databases` | `all`, `none` or a comma-separated list; new server: all; edit: unchanged |
| `--folders "/a /b"` | none |
| `--every-hours N`, `--weekly-day DAY`, `--weekly-time HH:MM` | `2`, staggered night slot |
| `--keep-hourly/-daily/-weekly/-monthly N` | `12 / 7 / 4 / 6` |
| `--remove` | off: unchecked repos are kept |
| `--no-restic-init`, `--no-timers` | off: repos are initialised and timers installed |

### `ltsbu doctor`

Runs health checks and exits with **3** if any check fails. Remote checks are skipped for a server
that ltsbu can't log in to.

| Check | What it verifies |
|---|---|
| local binaries | `ssh` exists (`systemctl` missing is only a warning) |
| config lint / ssh config lint | values are valid, local secrets are `0600`, managed SSH blocks are present and balanced |
| dns / tcp | each server's name resolves and its SSH port answers |
| ssh login | non-interactive key login to the server (`BatchMode=yes`) |
| remote binaries | `restic` on the server; the MariaDB client only if it has a database repo |
| paths | each vhost/folder path exists on the server |
| MariaDB | the saved login file is `0600`, the login works, and **every configured database exists** |
| storage | the server reaches the storage over SSH, and every restic repo opens with its password |
| timers | both timers of every repo are installed and enabled; user timers warn if linger is off |

### `ltsbu list`

```
SERVER  REPO              KIND   WHAT              SCHEDULE                       REPOSITORY
web1    blog-example-com  vhost  /var/www/blog     every 2h, weekly Tue 03:30     sftp:ltsbu-storage-web1:/srv/restic/web1/blog-example-com
web1    db                db     shop_db, blog_db  every 2h, weekly Sat 01:00     sftp:ltsbu-storage-web1:/srv/restic/web1/db
web1    shop-example-com  vhost  /var/www/shop     every 2h, weekly Thu 02:00     sftp:ltsbu-storage-web1:/srv/restic/web1/shop-example-com
```

### `ltsbu backup`

Backs up repos, then rotates them. This is what the timers run.

```bash
ltsbu backup --server web1 --repo shop-example-com
ltsbu backup --repo db                 # --server is optional when the repo name is unique
ltsbu backup --server web1 --all       # every repo of web1; --all alone: every server
ltsbu backup --repo db --weekly        # tag "weekly" and prune after forget
ltsbu backup --repo shop-example-com --include-git
```

In a database repo each database is backed up separately. If one fails, the others still run and the
command exits 1, naming the database that failed.

### `ltsbu snapshot`

Lists a repo's snapshots (`--json` for machine output), selected by the `server:<s>` and
`repo:<r>` tags, never by hostname.

### `ltsbu restore [SNAPSHOT]`

Restores **on the server**. `SNAPSHOT` is `latest` (the default) or an ID or ID prefix.

| Repo kind | Options | Action |
|---|---|---|
| vhost / folder | `--target DIR` | restore under `DIR` on the server; `--target /` restores in place (asks first) |
| db | `--database NAME [--into OTHER]` | stream the dump into `NAME`, or into `OTHER` which is created if missing (asks first) |

`--target` with a db repo, or `--database` with a files repo, is an error. Confirmation is skipped
with `--yes` and refused without it when there is no terminal.

### `ltsbu forget`

Rotation runs automatically after every backup. Use `forget` to apply a different policy once.

```bash
ltsbu forget --repo shop-example-com --yes
ltsbu forget --repo db --keep-daily 30 --prune --yes   # any --keep-* replaces the whole policy
```

An empty policy (everything 0) is refused, because it would delete every snapshot.

### `ltsbu credentials export [FILE]` / `import FILE`

Moves servers from one admin box to another: config, restic passwords, the admin SSH keys and the
**sites' database users** (user, host, `mysql_native_password` hash and database-level grants, read
from each database in a db repo). `--server` limits the export to one server. `--no-db-users` leaves
the users out.

`import` validates everything **before** writing anything. It:
- writes the secrets `0600` to this box's locations
- adds the SSH blocks
- recreates the database users on the server, building the SQL from validated fields and sending it on stdin

A server that already exists here needs `--force`, and then **keeps its local connection settings**
(see [disaster recovery](#moving-to-another-admin-box--disaster-recovery)).

> **The bundle is the key to your backups.** It can decrypt every snapshot and delete the repos.
> Pipe it over SSH (`ltsbu credentials export | ssh admin2 ltsbu credentials import -`), or
> `shred -u` every copy.

## Common options

| Option | Meaning |
|---|---|
| `--server LABEL`, `-s` | server to act on; optional when only one matches |
| `--repo NAME`, `-r` | repo on that server; optional when only one matches |
| `--dry-run` | print the commands that would change something instead of running them; read-only commands still run |
| `--verbose`, `-v` | log every external command (secrets are never on a command line) |
| `--config FILE` | alternative config file (default `~/.config/ltsbu/config.toml`); put it before the command |

Exit codes: `0` success, `1` error, `2` invalid usage, `3` doctor found failures.

## How backups work

- **Files** (vhost and folder repos):

  ```
  ssh <server> restic -r sftp:ltsbu-storage-<server>:<path>/<server>/<repo> backup --host <server> --tag … -- <paths>
  ```

  Nested `.git` directories are excluded unless the repo has `exclude_git = false`.
- **Databases** (db repo), one database at a time:

  ```
  ssh <server> bash -o pipefail -c 'mariadb-dump --defaults-extra-file=<0600 my.cnf> --single-transaction --quick --routines --triggers <db> | restic backup --stdin --stdin-filename <db>.sql --tag db:<db> …'
  ```

  The fixed file name `<db>.sql` makes each database its own restic group, so incremental dedup, parent
  detection and rotation all work per database. The dump has no `CREATE DATABASE`, so it can be loaded
  under any name.
- **Tags:** `ltsbu`, `server:<server>`, `repo:<repo>`, `db:<db>`, and `weekly` on weekly runs.
- **One at a time:** a lock (`~/.cache/ltsbu/backup.lock`) makes overlapping timer runs queue
  instead of loading the servers in parallel.
- Every argument sent over SSH is shell-quoted. Secrets reach the server **on stdin** and are written
  `0600` with `umask 077`. They never appear on a command line.

## Schedule and rotation

Each repo gets two systemd timers on the admin box:

| Timer | Default | Runs |
|---|---|---|
| `ltsbu-<server>-<repo>.timer` | `OnCalendar=*-*-* 00/2:MM:00`, where `MM` is a per-repo minute | `backup`, then `forget` |
| `ltsbu-<server>-<repo>-weekly.timer` | one night slot between 01:00 and 04:30, a different day/time for each repo on the same storage | `backup --weekly`, then `forget --prune` |

All timers have `Persistent=true`, so a run missed while the box was off happens at boot, and
`RandomizedDelaySec=5min`. The default keep policy is `hourly 12, daily 7, weekly 4, monthly 6`. It
uses restic's `--keep-*` options and can be changed per repo in `discover`. While a policy is not yet
full, restic ≥ 0.14 also keeps the oldest snapshot (restic 0.12 does not), so young repos may show
one snapshot more than you expect.

As a normal user, units go to `~/.config/systemd/user` and need `loginctl enable-linger $USER` to
run while you are logged out (doctor warns). As root they go to `/etc/systemd/system`.

## Files and configuration

| Where | Path | Mode | Contents |
|---|---|---|---|
| admin box | `~/.config/ltsbu/config.toml` | 0600 | servers and repos (no secrets) |
| admin box | `~/.config/ltsbu/servers/<server>/<repo>.pass` | 0600 | restic password (master copy) |
| admin box | `~/.config/systemd/user/ltsbu-*.{service,timer}` | | timers |
| server | `~/.config/ltsbu/my.cnf` | 0600 | MariaDB admin login (`[client]`, `host=localhost`) |
| server | `~/.config/ltsbu/<repo>.pass` | 0600 | restic password used on the server |

Example `config.toml`:

```toml
version = 2

[servers.web1]
ssh_host = "web1.example.com"
ssh_user = "root"
ssh_port = 22
ssh_identity = "/home/admin/.ssh/id_ltsbu"
secrets_dir = "/root/.config/ltsbu"
db_login = true

[servers.web1.storage]
host = "nas.example.com"
user = "restic"
port = 22
base_path = "/srv/restic"
identity = "/root/.ssh/id_storage"

[servers.web1.repos.db]
kind = "db"
databases = ["blog_db", "shop_db"]
password_file = "/home/admin/.config/ltsbu/servers/web1/db.pass"

[servers.web1.repos.db.schedule]
every_hours = 2
minute = 17
weekly_day = "Sat"
weekly_time = "01:00"

[servers.web1.repos.db.keep]
hourly = 12
daily = 7
weekly = 4
monthly = 6
```

The MariaDB admin login needs `SELECT`, `LOCK TABLES`, `SHOW VIEW` and `TRIGGER` for backups. Restores
also need `CREATE`, `DROP`, `INSERT`, `ALTER` and `INDEX`, and `credentials import` needs `CREATE USER`
and `GRANT OPTION`. On a Virtualmin server, use `root`.

## Managed SSH config blocks

ltsbu edits two `~/.ssh/config` files, and only between its tag comments:

- **On the admin box**, a block `ltsbu:<server>` with `Host ltsbu-<server>` for the login to the
  server. None is written when `HOST` is your own alias.
- **On the server**, a block `ltsbu:storage-<server>` with `Host ltsbu-storage-<server>` for restic's
  SFTP route to the storage.

```sshconfig
# >>> ltsbu:storage-web1 >>>
# Managed by lts-backup-cli. Edits inside this block are overwritten.
Host ltsbu-storage-web1
    HostName nas.example.com
    User restic
    Port 22
    IdentityFile /root/.ssh/id_storage
    IdentitiesOnly yes
    StrictHostKeyChecking accept-new
    ServerAliveInterval 60
    ServerAliveCountMax 240
# <<< ltsbu:storage-web1 <<<
```

Each edit is atomic and first saves a timestamped backup, `config.ltsbu-<timestamp>.bak`.
`StrictHostKeyChecking accept-new` trusts a host's key on first contact and rejects a changed key
afterwards, so unattended runs work on fresh machines.

## Restoring

```bash
ltsbu snapshot --repo shop-example-com                                   # what's there?
ltsbu restore --repo shop-example-com --target /tmp/shop-restore          # files -> /tmp/shop-restore/var/www/shop
ltsbu restore 4f2a9c1e --repo shop-example-com --target / --yes           # in place, from a specific snapshot
ltsbu restore --repo db --database shop_db --into shop_check --yes        # inspect a copy
ltsbu restore --repo db --database shop_db --yes                          # put it back
```

Plain restic works too, on the server:
`restic -r sftp:ltsbu-storage-web1:/srv/restic/web1/db --password-file ~/.config/ltsbu/db.pass snapshots`.

restic restores numeric uid/gid. If the site's unix user has a different uid on a rebuilt server,
fix ownership with `chown -R`.

## Moving to another admin box / disaster recovery

**New admin box, same servers:**

```bash
ltsbu credentials export | ssh admin2 ltsbu credentials import -
ssh admin2 'ltsbu discover web1.example.com && ltsbu doctor'   # re-installs the timers there
```

Disable the timers on the old admin box afterwards (`systemctl --user disable --now 'ltsbu-*'`), so
the two boxes never run the same backups.

**Rebuilt or replacement web server** (same label, new machine):

1. `ltsbu discover new-web1.example.com --server web1`. This re-points `web1`, writes the server-side
   secrets and the storage route, and keeps the repos and their passwords.
2. `ltsbu credentials import --force bundle.toml` (from an earlier export), if the sites' database
   users must be recreated. The local connection settings from step 1 are kept.
3. `ltsbu restore --repo db --database shop_db --yes`, and `ltsbu restore --repo <vhost> --target / --yes`.

## Troubleshooting

| Symptom | Fix |
|---|---|
| `cannot log in to ltsbu-<server>` | `ssh-copy-id` your key to the server, then `ssh ltsbu-<server> true` |
| doctor: **storage ssh FAIL** | on the server: `ssh ltsbu-storage-<server> true`; authorise the server's key on the storage |
| doctor: **mariadb login FAIL** | re-run `ltsbu discover <host>` and enter the admin login again |
| doctor: **database X FAIL** `database not found` | the database was dropped or renamed: re-run `discover` and update the selection |
| doctor: **timers FAIL** | re-run `ltsbu discover <host>` (timers are refreshed); check `systemctl --user list-timers 'ltsbu-*'` |
| doctor: **systemd linger WARN** | `loginctl enable-linger $USER` |
| `v1 config detected` | ltsbu 2 is a clean break: move the old config aside and run `ltsbu discover <host>` |
| `Access denied … LOCK TABLES` during a backup | grant the admin login `LOCK TABLES` and `SHOW VIEW` |
| `refusing without --yes (no terminal)` | add `--yes` in scripts |
| Ubuntu: a restic flag is unsupported | Ubuntu's restic 0.12 is old: `sudo restic self-update` |

`--verbose` shows every command ltsbu runs.

---

## Development

```bash
python3 -m venv .venv && . .venv/bin/activate
pip install -e '.[dev]'

ruff check . && ruff format --check . && mypy src   # lint + types
pytest -q --cov=lts_backup_cli                      # unit
behave --tags=~@e2e                                 # BDD acceptance (no network)

# Smoke: the built wheel in a clean venv
python -m build --wheel --outdir /tmp/dist . && python -m venv /tmp/smoke \
  && /tmp/smoke/bin/pip install /tmp/dist/*.whl \
  && PATH=/tmp/smoke/bin:$PATH PYTHON=/tmp/smoke/bin/python sh tests/smoke/smoke.sh

# E2E: real SSH, restic, MariaDB 10.4 and SFTP on both supported distros (smoke runs first)
docker compose -f tests/docker/docker-compose.yml run --rm --build rocky8
docker compose -f tests/docker/docker-compose.yml run --rm --build ubuntu2204
docker compose -f tests/docker/docker-compose.yml down && rm -rf tests/docker/.e2e
```

Design principles, the testing strategy and the Bitbucket CI/CD pipeline are described in
[CLAUDE.md](CLAUDE.md). The requirements are in [docs/SPEC2.md](docs/SPEC2.md) (v2) and
[docs/SPEC.md](docs/SPEC.md) (v1). Pushing a `vX.Y.Z` tag that matches `__version__` publishes the
package to PyPI.

## License

BSD 3-Clause. Copyright (c) 2026, joaomartins@logitools.pt and LTS, Lda. See [LICENSE](LICENSE).
