Initial commit

This commit is contained in:
Michael Smith 2023-03-01 18:46:58 +01:00 committed by Michael Smith
commit dc0584f503
9 changed files with 436 additions and 0 deletions

2
.flake8 Normal file
View File

@ -0,0 +1,2 @@
[flake8]
max-line-length = 88

167
.gitignore vendored Normal file
View File

@ -0,0 +1,167 @@
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Ignore all logfiles and tempfiles.
/log/*
/tmp/*
!/log/.gitkeep
!/tmp/.gitkeep

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2023 Michael Smith
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

35
README.md Normal file
View File

@ -0,0 +1,35 @@
# Pirate PostgreSQL backup script
Pirate PostgreSQL backup script written in Python.
This script backs up an entire PostgreSQL database to a remote server using scp. Backup files are
compressed and labeled with a precise timestamp.
Configuration is taken from environment variables.
## Dependencies
- PostgreSQL
- Python 3.9+
## Configuration environment variables
| Name | Purpose |
| ------------------ | ------------------------------------------------------------------------------------------------------------------- |
| **PG_DUMPALL_CMD** | Full path to the `pg_dumpall` command included with the PostgreSQL installation. Defaults to `/usr/bin/pg_dumpall`. |
| **DATABASE_HOST** | Database server host or socket directory. Defaults to `localhost`. |
| **DATABASE_PORT** | Database server port number. Defaults to `5432`. |
| **DATABASE_USER** | Connect as specified database user. Defaults to `postgres`. |
| **SSH_HOST** | Scp connect string. E.g. `user@host:/some/path/` |
## Usage example
```sh
SSH_HOST="user@host:~/pirate-backup-directory/" /usr/bin/python3 pirate-backup.py
```
## Notes
- This script relies on [Trust Authentication](https://www.postgresql.org/docs/current/auth-trust.html) of the backup user on the local server and therefore does not support passing a password through an environment variable. This is usually sufficient for local connections, although peer authentication is often times recommended.
- This script relies on a working ssh connection for the local user to the remote machine using a public-private key pair. See [How To Configure SSH Key-Based Authentication on a Linux Server](https://www.digitalocean.com/community/tutorials/how-to-configure-ssh-key-based-authentication-on-a-linux-server) for instructions.

67
flake.lock generated Normal file
View File

@ -0,0 +1,67 @@
{
"nodes": {
"devshell": {
"inputs": {
"flake-utils": [
"flake-utils"
],
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1676293499,
"narHash": "sha256-uIOTlTxvrXxpKeTvwBI1JGDGtCxMXE3BI0LFwoQMhiQ=",
"owner": "numtide",
"repo": "devshell",
"rev": "71e3022e3ab20bbf1342640547ef5bc14fb43bf4",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "devshell",
"type": "github"
}
},
"flake-utils": {
"locked": {
"lastModified": 1676283394,
"narHash": "sha256-XX2f9c3iySLCw54rJ/CZs+ZK6IQy7GXNY4nSOyu2QG4=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "3db36a8b464d0c4532ba1c7dda728f4576d6d073",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1676177817,
"narHash": "sha256-OQnBnuKkpwkfNY31xQyfU5hNpLs1ilWt+hVY6ztEEOM=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "1b82144edfcd0c86486d2e07c7298f85510e7fb8",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-22.11",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"devshell": "devshell",
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

99
flake.nix Normal file
View File

@ -0,0 +1,99 @@
{
description = "Pirate PostgreSQL backup script";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-22.11";
flake-utils.url = "github:numtide/flake-utils";
devshell = {
url = "github:numtide/devshell";
inputs = {
flake-utils.follows = "flake-utils";
nixpkgs.follows = "nixpkgs";
};
};
};
outputs = { self, nixpkgs, flake-utils, devshell }:
flake-utils.lib.eachDefaultSystem (system: {
devShell =
let
pkgs = import nixpkgs {
inherit system;
overlays = [ devshell.overlay ];
};
in
pkgs.devshell.mkShell {
name = "Pirate Backup development shell";
packages = with pkgs; [
isort
nixpkgs-fmt
postgresql_14
python3
];
env = [
{
name = "PGDATA";
eval = "$PRJ_ROOT/tmp/postgres";
}
{
name = "DATABASE_HOST";
eval = "$PGDATA";
}
];
commands = [
{
name = "pg:setup";
category = "database";
help = "Set up PostgreSQL in project folder";
command = ''
initdb --encoding=UTF8 --no-locale -U postgres
echo "listen_addresses = ${"'"}${"'"}" >> $PGDATA/postgresql.conf
echo "unix_socket_directories = '$PGDATA'" >> $PGDATA/postgresql.conf
'';
}
{
name = "pg:start";
category = "database";
help = "Start PostgreSQL instance";
command = ''
[ ! -d $PGDATA ] && pg:setup
pg_ctl -D $PGDATA -U postgres start -l $PRJ_ROOT/log/postgres.log
'';
}
{
name = "pg:stop";
category = "database";
help = "Stop PostgreSQL instance";
command = ''
pg_ctl -D $PGDATA -U postgres stop
'';
}
{
name = "pg:import";
category = "database";
help = "Import sample data";
command = ''
psql -h $PGDATA -U postgres < $PRJ_ROOT/tmp/sample.sql
'';
}
{
name = "pg:console";
category = "database";
help = "Open database console";
command = ''
psql --host $PGDATA -U postgres
'';
}
{
name = "maintenance:lint";
category = "Maintenance";
help = "Lint all the files in project";
command = ''
nixpkgs-fmt *.nix
'';
}
];
};
});
}

1
log/.gitkeep Normal file
View File

@ -0,0 +1 @@
.keep

55
pirate-backup.py Normal file
View File

@ -0,0 +1,55 @@
import gzip
import os
import shutil
import subprocess
import sys
import tempfile
from datetime import datetime
def main():
pg_dumpall_cmd = os.environ.get("PG_DUMPALL_CMD", "/usr/bin/pg_dumpall")
database_host = os.environ.get("DATABASE_HOST", "localhost")
database_port = os.environ.get("DATABASE_PORT", "5432")
database_user = os.environ.get("DATABASE_USER", "postgres")
try:
ssh_host = os.environ["SSH_HOST"]
except KeyError:
sys.exit(
"Error: Please provide a valid ssh host configuration through the SSH_HOST "
'environment variable. E.g. SSH_HOST="user@host:/some/path/"'
)
backupfilename = (
f"all-databases-{datetime.now().strftime('%Y-%m-%d_%Hh%Mm%Ss.%A')}.sql"
)
with tempfile.TemporaryDirectory() as tmpdirname:
backupfilepath = os.path.join(tmpdirname, backupfilename)
subprocess.run(
[
pg_dumpall_cmd,
"-h",
database_host,
"-p",
database_port,
"-U",
database_user,
"-f",
backupfilepath,
]
)
compressedfilepath = os.path.join(tmpdirname, f"{backupfilename}.gz")
with open(backupfilepath, "rb") as backupfile:
with gzip.open(compressedfilepath, "wb") as compressedfile:
shutil.copyfileobj(backupfile, compressedfile)
subprocess.run(["scp", compressedfilepath, ssh_host])
if __name__ == "__main__":
main()

1
tmp/.gitkeep Normal file
View File

@ -0,0 +1 @@
.gitkeep