Debian Codegraph @

docs/src/configuration.md

raw
1 # Configuration
2
3 ---
4
5 ## General
6
7 ### DBBACKUP_DATABASES
8
9 List of key entries for `settings.DATABASES` which shall be used to
10 connect and create database backups.
11
12 Default: `list(settings.DATABASES.keys())` (keys of all entries listed)
13
14 ### DBBACKUP_TMP_DIR
15
16 Local directory used for creating temporary files (for example while streaming
17 command output before uploading to storage).
18
19 Default: `tempfile.gettempdir()`
20
21 ### DBBACKUP_TMP_FILE_READ_SIZE
22
23 Read chunk size (in bytes) when streaming temporary files. Increase this if
24 you're working with very large backups and want fewer read system calls; decrease
25 for memory constrained environments.
26
27 Default: `1024 * 1000` (≈1 MB)
28
29 ### DBBACKUP_TMP_FILE_MAX_SIZE
30
31 Maximum size in bytes for file handling in memory before a temporary
32 file is written in `DBBACKUP_TMP_DIR`.
33
34 Default: `10*1024*1024`
35
36 ### DBBACKUP_CLEANUP_KEEP and DBBACKUP_CLEANUP_KEEP_MEDIA
37
38 Number of most recent backups to keep when you pass the `--clean <amount>`
39 option to `dbbackup` or `mediabackup`. Older files beyond this count are
40 deleted. `DBBACKUP_CLEANUP_KEEP_MEDIA` defaults to the same value unless set.
41
42 Default: `10`
43
44 ### DBBACKUP_CLEANUP_KEEP_FILTER
45
46 Optional callable for custom retention logic run during cleanup. Receives the
47 filename of a candidate backup slated for deletion and returns `True` to keep
48 or `False` to delete. Combine this with `--clean` to implement e.g. “keep all
49 end of month backups”.
50
51 Default: `lambda filename: False`
52
53 ### DBBACKUP_DATE_FORMAT
54
55 `strftime` format string used when expanding `{datetime}` in filename
56 templates. Must contain only alphanumeric characters plus `_ - %`.
57
58 Default: `'%Y-%m-%d-%H%M%S'`
59
60 ### DBBACKUP_HOSTNAME
61
62 Used to identify a backup by a server name in the file name.
63
64 Default: `socket.gethostname()`
65
66 ### DBBACKUP_FILENAME_TEMPLATE
67
68 Template used to construct database backup filenames. May be a format string
69 or a callable. Default: `'{databasename}-{servername}-{datetime}.{extension}'`.
70 If you supply a function it must accept the keyword arguments shown below and
71 return the complete filename string (without path).
72
73 ```python
74 def backup_filename(databasename, servername, datetime, extension, content_type):
75 pass
76
77 DBBACKUP_FILENAME_TEMPLATE = backup_filename
78 ```
79
80 Use a custom function if you need hierarchical prefixes (e.g. `year/month/`),
81 or naming compatible with automatic life cycle / expiration rules of your
82 object storage provider. `{datetime}` is rendered using `DBBACKUP_DATE_FORMAT`.
83
84 Note on cleanup (--clean): the cleanup logic matches backup files to a
85 database using the `{databasename}` value (the database alias/key from
86 `settings.DATABASES` or `DBBACKUP_CONNECTORS`). If you rely on the
87 `--clean` option to remove older database backups, ensure your
88 `DBBACKUP_FILENAME_TEMPLATE` includes `{databasename}` so files can be
89 correctly identified and filtered for deletion. When backing up a single
90 database using the default `databasename` (often `default`) this may not be
91 necessary, but it is required when you manage more than one database or use
92 custom connector keys.
93
94 ### DBBACKUP_MEDIA_FILENAME_TEMPLATE
95
96 Same as `DBBACKUP_FILENAME_TEMPLATE`, but used for media backups.
97
98 Default: `'{servername}-{datetime}.{extension}'`
99
100 ### DBBACKUP_MEDIA_PATH
101
102 Filesystem path whose contents are archived by the `mediabackup` command. By
103 default this is `settings.MEDIA_ROOT`.
104
105 Default: `settings.MEDIA_ROOT`
106
107 ---
108
109 ## Encryption
110
111 Backups may contain personal or otherwise sensitive data. When storing them
112 outside trusted infrastructure you should encrypt them. Keep your private
113 keys secure and ensure you have tested decryption in a disaster scenario.
114
115 You can encrypt a backup with the `--encrypt` option. The backup is done
116 using GPG.
117
118 ```bash
119 python manage.py dbbackup --encrypt
120 ```
121
122 ...or when restoring from an encrypted backup:
123
124 ```bash
125 python manage.py dbrestore --decrypt
126 ```
127
128 Requirements:
129
130 - Install the python package python-gnupg: `pip install python-gnupg>=0.5.0`.
131 - You need a GPG key. ([GPG manual](https://www.gnupg.org/gph/en/manual/c14.html))
132 - Set the setting `DBBACKUP_GPG_RECIPIENT` to the name of the GPG key.
133
134 Note (Windows): The `gpg` executable must be installed and on your PATH for encryption/decryption. If it is absent, django-dbbackup still works; only encryption-related features are unavailable. The test suite will automatically skip encryption tests when `gpg` is not found.
135
136 ### DBBACKUP_GPG_ALWAYS_TRUST
137
138 If GPG does not fully trust the public key, encryption can fail. Setting this
139 to `True` adds `--trust-model always` to bypass trust checks (only do this in
140 controlled environments).
141
142 ### DBBACKUP_GPG_RECIPIENT
143
144 Recipient (key ID, fingerprint, or email) used for GPG encryption. Required
145 when using `--encrypt` and for automatic decryption with `--decrypt`.
146
147 ### DBBACKUP_CONNECTORS
148
149 Allows for overriding the connector used for specific Django database(s).
150 This mapping is similar to `DATABASES`. Lets you define different
151 credentials / hosts exclusively for backup / restore operations
152 (e.g. read from a replica). Keys correspond to database aliases.
153
154 See the [Databases](databases.md) section for details on how to configure
155 connectors.
156
157 Default: `{}`
158
159 ### DBBACKUP_CONNECTOR_MAPPING
160
161 Map custom database engine names (e.g. from wrappers like `transaction_hooks`
162 or third party observability packages) to a DBBackup connector class.
163 Useful when you are using a third party backend that subclasses a supported
164 Django database backend.
165
166 See the [Databases](databases.md) section for details on how to configure the
167 connector mapping.
168
169 Default: `{}`
170
171 ---
172
173 ## Email
174
175 ### DBBACKUP_SEND_EMAIL
176
177 Controls whether django-dbbackup sends an error email when an uncaught
178 exception is raised.
179
180 Default: `True`
181
182 ### DBBACKUP_SERVER_EMAIL
183
184 The email address that error messages come from, such as those sent to
185 `DBBACKUP_ADMINS`.
186
187 Default: `django.conf.settings.SERVER_EMAIL`
188
189 ### DBBACKUP_ADMINS
190
191 A list of recipients that receive error emails when `DEBUG=False` and an
192 unhandled exception occurs in a DBBackup command. Follows Django's standard
193 `ADMINS` tuple-of-tuples structure: `(('Full Name', '[email protected]'), ...)`.
194
195 Default: `django.conf.settings.ADMINS`
196
197 ### DBBACKUP_EMAIL_SUBJECT_PREFIX
198
199 Subject-line prefix for email messages sent by DBBackup.
200
201 Default: `'[dbbackup] '`
202
203 ---
204
205 ## Metadata
206
207 ### DBBACKUP_BACKUP_METADATA_SETTER
208
209 Function or dotted path (string) to a callable that returns a dictionary of extra metadata.
210
211 The function must accept a single argument: a metadata dictionary containing information about the current backup operation. If a dictionary is returned, it will be merged into the current backup's metadata file. If `None` is returned, it is treated as an empty dictionary.
212
213 Default: `None`
214
215 ```python
216 def metadata_set(metadata):
217 last_backup_time = datetime.now().isoformat()
218 if metadata and metadata.get('engine') == 'my.custom.Engine':
219 region = os.environ.get('AWS_REGION')
220 return {'environment': 'AWS', 'region': region, 'backup_time': last_backup_time}
221 else:
222 return {'backup_time': last_backup_time}
223
224 DBBACKUP_BACKUP_METADATA_SETTER = metadata_set
225 ```
226
227 ### DBBACKUP_RESTORE_METADATA_VALIDATOR
228
229 Function or dotted path (string) to a callable that performs additional validation on the backup's metadata during restore operations. This validator runs **after** the built-in validation (e.g. database engine checks).
230
231 The callable should accept a single argument: the metadata dictionary loaded from the current restore operation's metadata file. If this function returns `True`, the metadata is valid, `False` means the restore operation will be aborted. `None` can be returned to do nothing and allow `dbbackup` to decide. It may raise a `CommandError` with a descriptive message if validation fails.
232
233 Default: `None`
234
235 ```python
236 import os
237
238 def validate_restore(metadata):
239 region = os.environ.get('AWS_REGION')
240 if not metadata.get('region') == region:
241 raise CommandError(f"Backup region does not match current region {region}; cross region restores are not allowed due to SMP-0123.")
242
243 last_backup_time = metadata.get('backup_time')
244 if datetime.now() - datetime.fromisoformat(last_backup_time) > timedelta(days=120):
245 return False # Skip restore since it is stale (>120 days)
246
247 if os.environ.get('AWS_REGION') == None:
248 return None # Do nothing if performing a backup outside AWS_REGION
249
250 return True
251
252 DBBACKUP_RESTORE_METADATA_VALIDATOR = validate_restore
253 ```
254
255 ---
256
257 ## Database
258
259 By default DBBackup uses values from `settings.DATABASES`. Use
260 `DBBACKUP_CONNECTORS` (documented above) for backup specific overrides. See
261 [Database settings](databases.md) for backend specific options.
262
263 ---
264
265 ## Storage
266
267 You must configure a storage backend (`STORAGES['dbbackup']`) to persist
268 backups. See [Storage settings](storage.md) for supported options.