Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,31 @@ All notable changes to this project are documented here. The format is based on

### Fixed

- **Installing over an existing instance removed it.** The install never checked the name was free, and its
cleanup ran on a failure — or on Ctrl+C at the confirmation prompt — removing that instance's home, config,
unit and vhosts. A new instance now needs a free name (no system account or service such as `backup`, whose
home is `/var/backups`), Ctrl+C at the confirmation changes nothing, and a failure while running previews the
undo of what that run made and asks first; a data dir or role that was already there is kept.
- **The purge dropped other instances' databases.** Every filestore folder selected a database, with no owner
check, so on a shared `/var/lib/odoo` it dropped the others' databases and removed their filestores; a role
named after the instance was dropped even when another instance used it, and `postgres` was accepted as the
instance role. Databases are now selected by owner or exact name, superusers are refused, a shared data dir
loses only the selected filestores, and the Linux user is removed only when the tool made it.
- **Every install took `/var/log/odoo`** (`chown -R`), so the other instances could not write their logs, their
fail2ban jails saw nothing and logrotate's `su` failed. The directory is root's, each instance owns its log,
earlier logs get their owner back, and the logrotate policies lose `su`.
- **Delete instance** without nginx never dropped the database (`nginx -t` failed first); it now drops only a
database its role owns, reloads nginx only if installed, reads the data dir from the legacy config location
too, and removes the logrotate policy, as the purge does.
- **Copies:** a duplicate chowned the whole data dir (other instances' files when shared), nested the copy in an
existing target, and a refresh deleted the target filestore and asked for a phrase naming the source. The copy
now lands in the target, an existing one is moved aside, ownership is scoped, and a refresh asks for
`REPLACE <target>`. A replica's filestore went to `~/.local/share/Odoo` while its config named
`/var/lib/odoo/<target>`.
- **Backups:** a shared directory (`/tmp`, `/`) was accepted and made `700`; retention kept the newest by mtime,
so an old backup copied back in outlived newer ones. Backup directories must be dedicated and retention keeps
the newest names.

- **A failed install could drop a PostgreSQL role it had not created.** The cleanup of the PostgreSQL and
Odoo + PostgreSQL installs dropped the instance's role even when it existed before; it now drops it only when
this run created it.
Expand Down
12 changes: 6 additions & 6 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,15 @@ flowchart LR
confirm -- no --> menu
confirm -- yes --> apply["Apply in order<br/>(root only)"]
apply -- a step fails --> stop(["Stop at that step<br/>report it by name"])
stop -- install --> cleanup["Clean the install's residues"]
cleanup --> menu
stop -- install --> cleanup{"Undo what<br/>this run made?"}
cleanup -- yes or no --> menu
classDef step fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
classDef ask fill:#fef3c7,stroke:#d97706,color:#78350f
classDef guard fill:#dcfce7,stroke:#16a34a,color:#14532d
classDef stop fill:#fee2e2,stroke:#dc2626,color:#7f1d1d
class collect,build,apply step
class phrase,confirm ask
class preview,cleanup guard
class phrase,confirm,cleanup ask
class preview guard
class stop,menu stop
```

Expand All @@ -92,8 +92,8 @@ flowchart LR
- Destructive actions first ask for `confirm_with_phrase` — the operator types an exact phrase naming the
operation and instance — and only then show the plan.
- `preview_commands` renders the whole plan before anything runs; `apply_commands` runs it in order and stops
at the first failing step. An install that fails, or is interrupted with Ctrl+C, then removes what it created
and returns to the menu.
at the first failing step. An install that fails, or is interrupted with Ctrl+C while it runs, previews the
steps that undo what it made and asks before running them; then it returns to the menu.

## Diagram conventions

Expand Down
19 changes: 13 additions & 6 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ derived path):

1. Installs OS build dependencies and the PostgreSQL client (apt runs unattended and waits for the dpkg lock).
2. Creates the system user `<instance>` and the directory layout under `/opt/odoo/<instance>`
(`odoo`, `addons-oca`, `addons-custom`) plus `/etc/odoo/<instance>`, `/var/log/odoo` and the data dir
`/var/lib/odoo/<instance>` (filestores and sessions, outside the home).
(`odoo`, `addons-oca`, `addons-custom`) plus `/etc/odoo/<instance>` and the data dir
`/var/lib/odoo/<instance>` (filestores and sessions, outside the home). `/var/log/odoo` stays root's; the
instance owns only its own log, `/var/log/odoo/<instance>.log`.
3. Clones the core you chose — **Odoo** (official) or **OCB** (OCA's backports, same branches) — at the
requested branch (only if absent).
4. Builds the virtualenv with the Python interpreter the version needs (see below), installs pip, wheel and the
Expand Down Expand Up @@ -140,12 +141,18 @@ For HTTPS you pick a certificate strategy:
| **Let's Encrypt (managed externally)** | Adds no certificate commands — you manage LE outside the tool. |
| **Copy your own certificates** | Installs your CRT/KEY (+ optional intermediate), builds the fullchain, and **validates that the key matches the certificate** before Nginx is reconfigured. |

## The instance name must be free

The name becomes the instance's Linux user, systemd unit, home and log, so an install refuses a system account
or service name (`backup`, `nginx`, `postgres`, …) and a name the host already has a home, config, unit, vhost,
SSL directory or user for. To change an existing instance, use **Manage instances**.

## If an install fails

If an install plan fails partway, or you interrupt it with Ctrl+C, the tool runs a **best-effort cleanup** of
that instance's residues — service, config, home, Nginx vhosts, SSL dir, the new data dir while it holds no
filestore, and the DB role when this run created it (a role that already existed is kept) — and returns to the
menu, so you can retry cleanly.
Cancelling, or pressing Ctrl+C, at the plan confirmation changes nothing. If the plan fails partway, or you
interrupt it while it runs, the tool shows the steps that undo what that run made — service, config, home,
Nginx vhosts, SSL dir, log, logrotate policy, Linux user, the data dir if the run created it, and the DB role if
the run created it — and asks before running them. Then it returns to the menu, so you can retry cleanly.

## Related

Expand Down
5 changes: 3 additions & 2 deletions docs/operations/disk-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ Removes the oldest backups, **keeping the N most recent of each kind per databas
filestore archives (`.filestore.tar.gz`) are counted separately. Only names of the exact form
`<instance>--<db>--<timestamp>` are matched, so backups of another instance whose name starts the same way
(`shop_eu` next to `shop`) are never touched. Backups written before the database was part of the name
(`<instance>_<timestamp>`) are pruned as one more group. You choose N; the plan is previewed before it runs. A
missing backup directory is a no-op.
(`<instance>_<timestamp>`) are pruned as one more group. The most recent are the latest timestamps in the
names, so a backup copied back in later does not count as new. You choose N; the plan is previewed before it
runs. A missing backup directory is a no-op.

## Related

Expand Down
34 changes: 21 additions & 13 deletions docs/operations/instance-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ To go back, copy the files from the `config_preupdate/<timestamp>` directory and

### Backups

**Create backup** exports the database and/or filestore into the backup directory you choose:
**Create backup** exports the database and/or filestore into the backup directory you choose — a dedicated one,
such as `/var/backups/<instance>`; a shared directory (`/tmp`, `/var/backups`, …) is refused:

- Database → `pg_dump -Fc` → `<instance>--<db>--<timestamp>.dump`
- Filestore → gzipped tar → `<instance>--<db>--<timestamp>.filestore.tar.gz`
Expand All @@ -92,7 +93,8 @@ by root only: a dump holds password hashes, API keys and mail or payment secrets
### Restore and duplicate — copied vs moved

**Restore backup**, **Duplicate database** and **Duplicate instance** ask how the copy relates to its source,
and each asks for its confirmation phrase (`RESTORE <instance>` / `DUPLICATE <instance>`):
and each asks for its confirmation phrase (`RESTORE <instance>`, `DUPLICATE <source>`, or `REPLACE <target>`
for a refresh in place):

- **Copied (new UUID on target)** — the target gets its own `database.uuid`, `database.secret` and creation
date, as Odoo's own copy does.
Expand Down Expand Up @@ -140,7 +142,8 @@ what in a database can still act on the outside, rule by rule, and whether the m

Restore refuses to overwrite an existing target **database**. An existing target **filestore** needs an explicit
overwrite, and is then moved aside to `<filestore>.replaced-<timestamp>`, not deleted; the restored files are
handed to the instance user.
handed to the instance user. When the data dir may be shared with other instances (a custom `data_dir`), only
the restored database's filestore changes owner.

### Duplicate instance — replica or refresh

Expand All @@ -158,7 +161,9 @@ differs from the source database's owner.
- **Target exists → refresh in place.** The tool stops the target service, replaces its database and filestore
from the source, applies the semantics, and restarts it, without recreating its config or service. The
target's database is dropped only when it belongs to the target's own role (from its `odoo.conf`) and you
confirm the overwrite; the source instance or database can never be the target.
confirm the overwrite with `REPLACE <target>`; its previous filestore is moved aside, not deleted. The source
instance or database can never be the target, and a name that is a system account or a half-removed
instance is neither refreshed nor provisioned.

Every seeded database is **restricted to its owner** (`CONNECT` revoked from `PUBLIC`, granted to the owning
role), and the target's data dir is owned by the target user.
Expand All @@ -181,23 +186,26 @@ Two levels, both phrase-gated and asked before the plan is shown:

| Action | Removes | Phrase |
|--------|---------|--------|
| **Delete instance** (in *Manage instances*) | Service, backup timer, config, home, Nginx vhosts, SSL; optionally the database and one database's filestore | `DELETE <instance>` |
| **Remove instances** (main menu → total purge) | Everything above **plus** the Linux user, Odoo and Nginx logs, the fail2ban jail, the filestore root, the instance's databases, and its PostgreSQL roles | `DELETE-ALL <instance>` |
| **Delete instance** (in *Manage instances*) | Service, backup timer, config, logrotate policy, home, Nginx vhosts, SSL; optionally the database (if its owner is the instance's role) and one database's filestore | `DELETE <instance>` |
| **Remove instances** (main menu → total purge) | Everything above **plus** the Linux user, Odoo and Nginx logs, the fail2ban jail, the instance's filestores, its databases, and its PostgreSQL roles | `DELETE-ALL <instance>` |

Neither removes the instance's logrotate policy (`/etc/logrotate.d/odoo-<instance>`).
Both reload Nginx only when it is installed, and go on if `nginx -t` fails because of another site.

**Delete instance keeps the filestores you did not ask to delete.** An instance installed with
`data_dir = /var/lib/odoo/<instance>` keeps its data dir where it is. An older instance without a `data_dir`
keeps its filestores inside the home, so the plan first moves its data dir to
`/var/backups/<instance>/kept-data-dir-<timestamp>` and only then removes the home.

The **total purge** selects the databases the instance's DB role owns and the one named exactly like the
instance, plus those found in its filestore root and any you add. Databases whose name merely starts with the
instance name (`shop2`, `shop_eu` when purging `shop`) are listed as **not selected**; add them yourself if they
belong to it. When another instance connects with the same DB role, the purge says so, selects nothing by owner
and keeps the role. Without admin DB access it performs the local cleanup only. It removes the filestore root
(`<data_dir>/filestore`), not the rest of the data dir. The full contract is the
[removal spec](../../openspec/specs/instance-removal/spec.md).
instance, plus any you add. A filestore folder, or a name that merely starts with the instance name (`shop2`,
`shop_eu` when purging `shop`), is listed as **not selected**; add those yourself if they belong to it. The role
cannot be `postgres` or another superuser. When another instance connects with the same DB role, the purge says
so, selects nothing by owner and keeps the role. Without admin DB access it performs the local cleanup only.

The databases are dropped first, then their files. The instance's own data dir (`/var/lib/odoo/<instance>`) is
removed whole; from any other data dir, which other instances may share, only the selected databases'
filestores are removed. The Linux user is removed only when its home is `/opt/odoo/<instance>`. The full
contract is the [removal spec](../../openspec/specs/instance-removal/spec.md).

## Related

Expand Down
7 changes: 4 additions & 3 deletions docs/operations/log-rotation.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ policy for an instance's Odoo log (`/var/log/odoo/<instance>.log`).
- **Compression** — gzip the rotated files (adds `compress` + `delaycompress`).
- **Size threshold** (optional) — also rotate when the log exceeds a size (e.g. `50M`, `1G`).

The policy uses **`copytruncate`**, so Odoo keeps writing to the same file and does **not** need a restart. An
`su <instance> <instance>` directive lets logrotate rotate the instance-owned log safely. The plan installs
`logrotate` if missing and validates the file with `logrotate -d` before finishing.
The policy uses **`copytruncate`**, so Odoo keeps writing to the same file and does **not** need a restart.
`/var/log/odoo` belongs to root and each instance owns only its own log, so root rotates it with no `su`
directive. The plan installs `logrotate` if missing and validates the file with `logrotate -d` before
finishing.

Log rotation is also offered **at install time** (recommended, default yes), so a fresh instance starts with a
rotation policy in place.
Expand Down
36 changes: 36 additions & 0 deletions instance_manager/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -933,4 +933,40 @@ def tf(template: str, *args: object, **kwargs: object) -> str:
'certificate not found': 'certificado no encontrado',
'Custom': 'Personalizado',
'Incomplete TLS': 'TLS incompleto',
'Make /var/log/odoo root-owned (755)': 'Hacer /var/log/odoo propiedad de root (755)',
'Drop su from the Odoo logrotate policies (root rotates them)': 'Quitar su de las políticas logrotate de Odoo (las rota root)',
'Give each instance its own log back ({} included)': 'Devolver a cada instancia su propio log ({} incluido)',
'Check the source filestore {} exists': 'Comprobar que existe el filestore origen {}',
'Move a previous target filestore aside to {}': 'Apartar el filestore destino anterior a {}',
'{} is a shared directory: use a dedicated one, such as /var/backups/<instance>.': '{} es un directorio compartido: usa uno dedicado, como /var/backups/<instancia>.',
'Own the filestore of {} by the instance user': 'Dar el filestore de {} al usuario de la instancia',
'Something named {} already exists on this host ({}). Update or delete it from Manage instances, or choose another name.': 'Ya existe algo llamado {} en este host ({}). Actualízalo o bórralo desde Gestionar instancias, o elige otro nombre.',
'[Cleanup] Remove the instance log and logrotate policy': '[Limpieza] Eliminar el log de la instancia y su política logrotate',
'[Cleanup] Remove the instance Linux user': '[Limpieza] Eliminar el usuario Linux de la instancia',
'Undo what this installation made (the steps above)?': '¿Deshacer lo que ha creado esta instalación (los pasos de arriba)?',
'Cleanup finished. Review the messages above.': 'Limpieza terminada. Revisa los mensajes de arriba.',
'Nothing was undone: the steps above list what the installation may have left.': 'No se ha deshecho nada: los pasos de arriba indican lo que la instalación puede haber dejado.',
'[Cleanup] Remove the new data dir': '[Limpieza] Eliminar el data dir nuevo',
'The installation {}.': 'La instalación {}.',
'Remove the logrotate policy': 'Eliminar la política logrotate',
'Validate and reload Nginx (if installed)': 'Validar y recargar Nginx (si está instalado)',
'Database {} belongs to role {}, not to this instance ({}): it is not deleted.': 'La base de datos {} pertenece al rol {}, no a esta instancia ({}): no se borra.',
'{} is an administrator role, not an instance role.': '{} es un rol de administración, no de una instancia.',
'Could not check role {}: {}': 'No se pudo comprobar el rol {}: {}',
'{} is a superuser role, not an instance role.': '{} es un rol superusuario, no de una instancia.',
'Remove the instance Odoo/Nginx logs and logrotate policy': 'Eliminar los logs Odoo/Nginx de la instancia y su política logrotate',
'[INFO] Not selected — a filestore folder exists but role {} does not own the database: {}. Add any that belong to this instance below.': '[INFO] No seleccionadas — existe la carpeta de filestore pero el rol {} no es propietario de la base de datos: {}. Añade abajo las que sean de esta instancia.',
'Remove the instance data dir {}': 'Eliminar el data dir de la instancia {}',
'Remove the filestore {}': 'Eliminar el filestore {}',
'Linux user {} kept: its home is not {}': 'Usuario Linux {} conservado: su home no es {}',
'Role {} kept: it still owns objects or is in use.': 'Rol {} conservado: aún es propietario de objetos o está en uso.',
'home': 'home',
'config': 'configuración',
'systemd unit': 'unidad systemd',
'Nginx vhost': 'vhost de Nginx',
'SSL directory': 'directorio SSL',
'Linux user': 'usuario Linux',
'That name is a system account or service name. Choose another instance name.': 'Ese nombre es de una cuenta o un servicio del sistema. Elige otro nombre de instancia.',
'Data dirs': 'Data dirs',
'Filestore folders': 'Carpetas de filestore',
}
24 changes: 24 additions & 0 deletions instance_manager/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,30 @@
)


# Names a new instance must not take: the instance name is also its Linux user, its
# systemd unit, its home and log names, so a system account or service name would
# hand the tool an existing account (``userdel -r backup`` removes /var/backups) or
# shadow a distribution unit (``/etc/systemd/system/nginx.service``).
RESERVED_INSTANCE_NAMES = frozenset({
# Debian/Ubuntu base accounts and common service accounts
"root", "daemon", "bin", "sys", "sync", "games", "man", "lp", "mail", "news", "uucp",
"proxy", "backup", "list", "irc", "gnats", "nobody", "messagebus", "syslog", "sshd",
"uuidd", "tcpdump", "tss", "landscape", "pollinate", "lxd", "usbmux", "dnsmasq",
"polkitd", "postfix", "ntp", "chrony", "ubuntu", "debian", "admin", "www_data",
# services this tool configures or relies on
"postgres", "postgresql", "nginx", "ssh", "cron", "fail2ban", "ufw", "rsyslog",
"logrotate", "certbot", "systemd", "networking", "docker", "snapd", "dbus", "odoo",
# directory names the tool keeps beside the instances
"ssl", "default", "filestore", "sessions",
})


def reserved_name_error(name: str) -> str | None:
if name in RESERVED_INSTANCE_NAMES:
return "That name is a system account or service name. Choose another instance name."
return None


def is_valid_db_name(name: str) -> bool:
"""True if ``name`` is a database name Odoo accepts and every command can take."""
return bool(DB_NAME_RE.fullmatch(name or ""))
Expand Down
Loading
Loading