django-cloud-backup 0.1.2__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. {django_cloud_backup-0.1.2/django_cloud_backup.egg-info → django_cloud_backup-0.1.3}/PKG-INFO +4 -2
  2. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/README.md +3 -1
  3. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/status.py +11 -2
  4. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/storages/base.py +4 -3
  5. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/storages/s3.py +62 -17
  6. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/tasks.py +40 -2
  7. django_cloud_backup-0.1.3/cloud_backup/tests/test_retries.py +84 -0
  8. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/tests/test_s3_trash.py +12 -3
  9. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/tests/test_status.py +13 -3
  10. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3/django_cloud_backup.egg-info}/PKG-INFO +4 -2
  11. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/django_cloud_backup.egg-info/SOURCES.txt +1 -0
  12. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/pyproject.toml +1 -1
  13. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/LICENSE +0 -0
  14. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/MANIFEST.in +0 -0
  15. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/__init__.py +0 -0
  16. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/admin.py +0 -0
  17. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/apps.py +0 -0
  18. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/backup.py +0 -0
  19. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/backup_azure.py +0 -0
  20. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/backup_azure_s3.py +0 -0
  21. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/backup_db.py +0 -0
  22. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/backup_local_files.py +0 -0
  23. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/backup_s3.py +0 -0
  24. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/base_backup.py +0 -0
  25. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/compression.py +0 -0
  26. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/config.py +0 -0
  27. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/db_tiers.py +0 -0
  28. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/encryption.py +0 -0
  29. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/enhanced_views.py +0 -0
  30. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/management/__init__.py +0 -0
  31. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/management/commands/__init__.py +0 -0
  32. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/management/commands/backup_status.py +0 -0
  33. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/management/commands/backup_website.py +0 -0
  34. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/management/commands/restore_db.py +0 -0
  35. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/management/commands/storage_setup.py +0 -0
  36. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/migrations/0001_initial.py +0 -0
  37. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/migrations/__init__.py +0 -0
  38. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/modals.py +0 -0
  39. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/models.py +0 -0
  40. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/prune_backups.py +0 -0
  41. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/runs.py +0 -0
  42. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/sql_functions.py +0 -0
  43. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/storage_setup.py +0 -0
  44. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/storages/__init__.py +0 -0
  45. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/storages/azure.py +0 -0
  46. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/storages/gdrive.py +0 -0
  47. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/templates/cloud_backup/backup.html +0 -0
  48. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/templates/cloud_backup/backup_content.html +0 -0
  49. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/templates/cloud_backup/info.html +0 -0
  50. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/templates/cloud_backup/runs_content.html +0 -0
  51. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/templates/cloud_backup/storage_setup_content.html +0 -0
  52. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/tests/__init__.py +0 -0
  53. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/tests/test_backup_azure.py +0 -0
  54. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/tests/test_db_tiers.py +0 -0
  55. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/tests/test_extensions.py +0 -0
  56. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/urls.py +0 -0
  57. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/utils.py +0 -0
  58. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/cloud_backup/views.py +0 -0
  59. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/django_cloud_backup.egg-info/dependency_links.txt +0 -0
  60. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/django_cloud_backup.egg-info/requires.txt +0 -0
  61. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/django_cloud_backup.egg-info/top_level.txt +0 -0
  62. {django_cloud_backup-0.1.2 → django_cloud_backup-0.1.3}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: django-cloud-backup
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Backs up django postgres databases, local folders and S3 folders to Google Drive, S3-compatible storage (AWS, Backblaze B2, Cloudflare R2) or Azure Blob Storage.
5
5
  Author: Ian Jones
6
6
  License-Expression: MIT
@@ -403,7 +403,9 @@ the name, date and size still look right, and the real version sits hidden under
403
403
  until the purge. So for tiered configs the status check also audits the bucket's
404
404
  versions: dumps get unique names and are only ever hidden by expiry once they are
405
405
  `expire_days` old, so a dump hidden younger than that, anything hidden under `monthly/`,
406
- or a key holding two real versions is someone else's doing. The `Version audit` row
406
+ or a key holding two real versions is someone else's doing. Versions that are all the
407
+ same size and hash are not counted: that is a server-side copy the client retried after
408
+ a timeout, the same bytes written twice. The `Version audit` row
407
409
  names them, says whether they are `hidden` (still recoverable), `overwritten` or already
408
410
  `purged`, and gives the deadline the purge clock sets - run `backup_status` more often
409
411
  than `purge_days`.
@@ -365,7 +365,9 @@ the name, date and size still look right, and the real version sits hidden under
365
365
  until the purge. So for tiered configs the status check also audits the bucket's
366
366
  versions: dumps get unique names and are only ever hidden by expiry once they are
367
367
  `expire_days` old, so a dump hidden younger than that, anything hidden under `monthly/`,
368
- or a key holding two real versions is someone else's doing. The `Version audit` row
368
+ or a key holding two real versions is someone else's doing. Versions that are all the
369
+ same size and hash are not counted: that is a server-side copy the client retried after
370
+ a timeout, the same bytes written twice. The `Version audit` row
369
371
  names them, says whether they are `hidden` (still recoverable), `overwritten` or already
370
372
  `purged`, and gives the deadline the purge clock sets - run `backup_status` more often
371
373
  than `purge_days`.
@@ -285,13 +285,22 @@ def name_time(key):
285
285
  return datetime.datetime.fromisoformat(match.group('month') + '-01') if match else None
286
286
 
287
287
 
288
+ def same_content(versions):
289
+ """Whether every version of a key is the same bytes - by size and the storage's
290
+ hash, so never true where the backend reports no hash."""
291
+ contents = {(v.get('size'), v.get('hash')) for v in versions}
292
+ return len(contents) == 1 and all(v.get('hash') for v in versions)
293
+
294
+
288
295
  def audit_versions(entries, expire_days):
289
296
  """(unexplained, explained): what the retention policy does not account for among a
290
297
  db folder's versions and delete markers. Dumps get unique names and are only ever
291
298
  hidden by expiry - the bucket's rule or the app's prune - once they are expire_days
292
299
  old, so a dump hidden younger than that, anything hidden in a tier that never
293
300
  expires, and a key holding two real versions (an overwrite) are someone else's
294
- doing. Each finding is {'key', 'kind': 'hidden'|'overwritten'|'purged', 'at', 'age'}:
301
+ doing. The one overwrite that is ours is a copy the client retried after a timeout:
302
+ the same bytes written twice, so versions that all share a size and hash are not a
303
+ finding. Each finding is {'key', 'kind': 'hidden'|'overwritten'|'purged', 'at', 'age'}:
295
304
  'purged' is a young dump whose hidden version is already gone - evidence, no longer
296
305
  recoverable."""
297
306
  by_key = {}
@@ -301,7 +310,7 @@ def audit_versions(entries, expire_days):
301
310
  unexplained, explained = [], 0
302
311
  for key, group in by_key.items():
303
312
  versions = sorted(group['versions'], key=lambda v: v['modified'])
304
- if len(versions) > 1:
313
+ if len(versions) > 1 and not same_content(versions):
305
314
  unexplained.append({'key': key, 'kind': 'overwritten', 'at': versions[-1]['modified'],
306
315
  'age': versions[-1]['modified'] - versions[0]['modified']})
307
316
  tier = tier_in_key(key)
@@ -171,9 +171,10 @@ class BackupStorage:
171
171
 
172
172
  def list_versions(self, prefix):
173
173
  """Every object version and delete marker under a key prefix, as
174
- {'key', 'version_id', 'modified' (naive local), 'size', 'is_latest', 'marker'} -
175
- what the status check's version audit reads. None where the backend has no
176
- versions; raises where they exist but cannot be listed."""
174
+ {'key', 'version_id', 'modified' (naive local), 'size', 'hash', 'is_latest',
175
+ 'marker'} - what the status check's version audit reads. hash is whatever the
176
+ backend gives that only identical content shares (an S3 ETag), or None. None
177
+ where the backend has no versions; raises where they exist but cannot be listed."""
177
178
  return None
178
179
 
179
180
  def versioned(self):
@@ -2,11 +2,13 @@ import concurrent.futures
2
2
  import os
3
3
  import threading
4
4
  from datetime import datetime, timedelta, timezone
5
+ from functools import cached_property
5
6
  from io import BytesIO
6
7
 
7
8
  import boto3
8
9
  import requests
9
10
  from boto3.s3.transfer import TransferConfig
11
+ from botocore.config import Config
10
12
  from botocore.exceptions import ClientError
11
13
 
12
14
  from ..db_tiers import DEFAULT_EXPIRE_DAYS, DEFAULT_PURGE_DAYS
@@ -45,6 +47,30 @@ class S3Storage(BackupStorage):
45
47
  metadata_workers = 8
46
48
  # CopyObject's ceiling - above it the copy has to be done in parts
47
49
  copy_object_limit = 5 * 1024 * 1024 * 1024
50
+ # Three clients, because one timeout/retry budget cannot suit every call. Every
51
+ # attempt can wait out a whole timeout, so a call's worst case against an endpoint
52
+ # that accepts the connection and then never answers is about attempts x
53
+ # read_timeout, plus standard mode's jittered backoff (at most 20 s a wait).
54
+ # Attempts are totals, the first try included.
55
+ retry_mode = 'standard'
56
+ connect_timeout = 10
57
+ # self.s3 - heads, listings, deletes, retention. The web UI, the status check and
58
+ # storage_setup make only these calls, so they give up in ~3.5 minutes on a stalled
59
+ # endpoint (~35 s on an unreachable one) rather than hang a request for most of an
60
+ # hour. A backup that hits that is retried by the scheduled task (tasks.TRANSIENT_RETRY)
61
+ read_timeout = 60
62
+ max_attempts = 3
63
+ # self.transfer_s3 - uploads and downloads. botocore's default (legacy mode, 5
64
+ # attempts, at most ~15 s of backoff) gave up on a B2 connection reset partway
65
+ # through a dump's multipart upload; this rides out a few minutes of resets
66
+ # (ConnectionClosedError, EndpointConnectionError, timeouts). Backups only
67
+ transfer_max_attempts = 10
68
+ # self.copy_s3 - server-side copies. CopyObject only answers once the whole copy is
69
+ # done, and a dump of a few hundred MB can take over botocore's default 60 seconds -
70
+ # the retry that follows a timeout writes the same object again, an overwrite the
71
+ # version audit then has to explain. Few attempts, so a stall costs ~20 minutes
72
+ copy_read_timeout = 300
73
+ copy_max_attempts = 4
48
74
 
49
75
  def __init__(self, bucket, access_key_id=None, secret_key=None, endpoint_url=None,
50
76
  region=None, b2=False, lock=None):
@@ -53,13 +79,30 @@ class S3Storage(BackupStorage):
53
79
  if region is None:
54
80
  # https://s3.<region>.backblazeb2.com
55
81
  region = endpoint_url.split('.')[1]
56
- self.s3 = boto3.client('s3', aws_access_key_id=access_key_id, aws_secret_access_key=secret_key,
57
- endpoint_url=endpoint_url, region_name=region)
82
+ self.client_args = dict(aws_access_key_id=access_key_id, aws_secret_access_key=secret_key,
83
+ endpoint_url=endpoint_url, region_name=region)
84
+ self.s3 = self.client(self.read_timeout, self.max_attempts)
58
85
  self.bucket = bucket
59
86
  self.lock = lock or {}
60
87
  self.lock_mode = self.lock.get('mode', 'COMPLIANCE')
61
88
  self.transfer_config = TransferConfig(multipart_threshold=64 * 1024 * 1024)
62
89
 
90
+ def client(self, read_timeout, attempts):
91
+ return boto3.client('s3', **self.client_args,
92
+ config=Config(connect_timeout=self.connect_timeout, read_timeout=read_timeout,
93
+ # total, the first try included - botocore's
94
+ # 'max_attempts' key would count retries only
95
+ retries={'total_max_attempts': attempts, 'mode': self.retry_mode}))
96
+
97
+ # built on first use, so a page that only lists never creates them
98
+ @cached_property
99
+ def transfer_s3(self):
100
+ return self.client(self.read_timeout, self.transfer_max_attempts)
101
+
102
+ @cached_property
103
+ def copy_s3(self):
104
+ return self.client(self.copy_read_timeout, self.copy_max_attempts)
105
+
63
106
  def _lock_args(self, lock_days, lock_mode=None):
64
107
  """Object-lock parameters for an upload/copy - the bucket must have Object Lock
65
108
  enabled or these requests are rejected. Retention is per object, so locking one
@@ -178,10 +221,10 @@ class S3Storage(BackupStorage):
178
221
  if head.get('ContentType'):
179
222
  extra_args['ContentType'] = head['ContentType']
180
223
  if head['ContentLength'] <= self.copy_object_limit:
181
- self.s3.copy_object(Bucket=self.bucket, Key=key, CopySource=source,
182
- MetadataDirective='REPLACE', **extra_args)
224
+ self.copy_s3.copy_object(Bucket=self.bucket, Key=key, CopySource=source,
225
+ MetadataDirective='REPLACE', **extra_args)
183
226
  else:
184
- self.s3.copy(source, self.bucket, key, ExtraArgs=extra_args, Config=self.transfer_config)
227
+ self.copy_s3.copy(source, self.bucket, key, ExtraArgs=extra_args, Config=self.transfer_config)
185
228
  restored = self.get_file(key)
186
229
  if restored['size'] != head['ContentLength']:
187
230
  raise IOError(f'Restored {key} is {restored["size"]} bytes, expected {head["ContentLength"]}')
@@ -227,16 +270,16 @@ class S3Storage(BackupStorage):
227
270
  key = f"{folder['id']}/{name}"
228
271
  extra_args = {'Metadata': {k: str(v) for k, v in metadata.items()}} if metadata else {}
229
272
  extra_args.update(self._lock_args(lock_days))
230
- self.s3.upload_fileobj(stream, self.bucket, key, ExtraArgs=extra_args or None,
231
- Config=self.transfer_config)
273
+ self.transfer_s3.upload_fileobj(stream, self.bucket, key, ExtraArgs=extra_args or None,
274
+ Config=self.transfer_config)
232
275
  return self.get_file(key)
233
276
 
234
277
  def keep_version(self, stored_file, lock_days=None):
235
278
  # server-side managed copy (handles > 5GB multipart) - no data transfer or
236
279
  # delete permission needed, and the copy gets its own object lock
237
280
  version_key = self.version_name(stored_file['id'])
238
- self.s3.copy({'Bucket': self.bucket, 'Key': stored_file['id']}, self.bucket, version_key,
239
- ExtraArgs=self._lock_args(lock_days) or None, Config=self.transfer_config)
281
+ self.copy_s3.copy({'Bucket': self.bucket, 'Key': stored_file['id']}, self.bucket, version_key,
282
+ ExtraArgs=self._lock_args(lock_days) or None, Config=self.transfer_config)
240
283
  return version_key
241
284
 
242
285
  def copy_stored_file(self, stored_file, folder, name, extra_metadata=None, lock_days=None,
@@ -250,13 +293,13 @@ class S3Storage(BackupStorage):
250
293
  if head.get('ContentType'):
251
294
  extra_args['ContentType'] = head['ContentType']
252
295
  if head['ContentLength'] <= self.copy_object_limit:
253
- self.s3.copy_object(Bucket=self.bucket, Key=key, CopySource=source,
254
- MetadataDirective='REPLACE', **extra_args)
296
+ self.copy_s3.copy_object(Bucket=self.bucket, Key=key, CopySource=source,
297
+ MetadataDirective='REPLACE', **extra_args)
255
298
  else:
256
299
  # the managed copy switches to a multipart copy, which starts from
257
300
  # CreateMultipartUpload and so takes the metadata from ExtraArgs - there is
258
301
  # no MetadataDirective on that path and nothing is inherited from the source
259
- self.s3.copy(source, self.bucket, key, ExtraArgs=extra_args, Config=self.transfer_config)
302
+ self.copy_s3.copy(source, self.bucket, key, ExtraArgs=extra_args, Config=self.transfer_config)
260
303
  copied = self.get_file(key)
261
304
  if copied['size'] != head['ContentLength']:
262
305
  raise IOError(f'Copy of {stored_file["id"]} to {key} is {copied["size"]} bytes, '
@@ -310,12 +353,12 @@ class S3Storage(BackupStorage):
310
353
 
311
354
  def download(self, stored_file, local_folder=None):
312
355
  if local_folder:
313
- self.s3.download_file(self.bucket, stored_file['id'],
314
- os.path.join(local_folder, stored_file['name']),
315
- Config=self.transfer_config)
356
+ self.transfer_s3.download_file(self.bucket, stored_file['id'],
357
+ os.path.join(local_folder, stored_file['name']),
358
+ Config=self.transfer_config)
316
359
  return stored_file['name']
317
360
  stream = BytesIO()
318
- self.s3.download_fileobj(self.bucket, stored_file['id'], stream, Config=self.transfer_config)
361
+ self.transfer_s3.download_fileobj(self.bucket, stored_file['id'], stream, Config=self.transfer_config)
319
362
  stream.seek(0)
320
363
  return stream
321
364
 
@@ -419,11 +462,13 @@ class S3Storage(BackupStorage):
419
462
  entries.append({'key': version['Key'], 'version_id': version.get('VersionId'),
420
463
  'modified': self.to_local_naive(version['LastModified']),
421
464
  'size': version.get('Size'), 'is_latest': version.get('IsLatest', False),
465
+ 'hash': (version.get('ETag') or '').strip('"') or None,
422
466
  'marker': False})
423
467
  for marker in page.get('DeleteMarkers', []):
424
468
  entries.append({'key': marker['Key'], 'version_id': marker.get('VersionId'),
425
469
  'modified': self.to_local_naive(marker['LastModified']),
426
- 'size': None, 'is_latest': marker.get('IsLatest', False), 'marker': True})
470
+ 'size': None, 'is_latest': marker.get('IsLatest', False), 'hash': None,
471
+ 'marker': True})
427
472
  return entries
428
473
 
429
474
  def versioned(self):
@@ -1,5 +1,7 @@
1
1
  import logging
2
+ import socket
2
3
 
4
+ import requests
3
5
  from celery import shared_task
4
6
  from django.db import connection, transaction
5
7
 
@@ -10,14 +12,50 @@ from .utils import allowed_to_restore, RESTORE_BLOCKED_MESSAGE
10
12
 
11
13
  logger = logging.getLogger(__name__)
12
14
 
15
+ # Network failures that outlast the storage client's own retries. A scheduled backup that
16
+ # hits one runs again from the start a few minutes later rather than leaving a gap until
17
+ # the next slot; anything else (a pg_dump error, a bad credential) fails straight away.
18
+ # The builtins are what Google Drive raises - googleapiclient runs on httplib2 over raw
19
+ # sockets (ConnectionResetError, socket.timeout - not TimeoutError before Python 3.10);
20
+ # requests' own errors are not builtin ConnectionErrors, so are listed separately
21
+ TRANSIENT_ERRORS = (ConnectionError, TimeoutError, socket.timeout,
22
+ requests.ConnectionError, requests.Timeout)
23
+ try:
24
+ from httplib2 import ServerNotFoundError # a DNS failure on the Google Drive path
13
25
 
14
- @shared_task
26
+ TRANSIENT_ERRORS += (ServerNotFoundError,)
27
+ except ModuleNotFoundError:
28
+ pass
29
+ try:
30
+ from botocore.exceptions import ConnectionError as BotoConnectionError, HTTPClientError
31
+
32
+ # ConnectionClosedError and ReadTimeoutError are HTTPClientErrors;
33
+ # EndpointConnectionError and ConnectTimeoutError are ConnectionErrors
34
+ TRANSIENT_ERRORS += (BotoConnectionError, HTTPClientError)
35
+ except ModuleNotFoundError: # no s3 extra
36
+ pass
37
+ try:
38
+ from azure.core.exceptions import ServiceRequestError, ServiceResponseError
39
+
40
+ # the request could not be sent / the connection broke before the response came
41
+ TRANSIENT_ERRORS += (ServiceRequestError, ServiceResponseError)
42
+ except ModuleNotFoundError: # no azure extra
43
+ pass
44
+
45
+ # Each retry dumps afresh under a new time-stamped name, so it is newer than the slot it
46
+ # replaces and the status check grades it as that slot's run. Two retries 5 minutes apart
47
+ # finish well before the next slot of a schedule that runs every hour or two. Only the
48
+ # exhausted last attempt raises, so a blip that the retry gets past does not reach Sentry
49
+ TRANSIENT_RETRY = dict(autoretry_for=TRANSIENT_ERRORS, max_retries=2, default_retry_delay=5 * 60)
50
+
51
+
52
+ @shared_task(**TRANSIENT_RETRY)
15
53
  def backup(config=None):
16
54
  """Beat schedules can run several configs, e.g. kwargs={'config': 'staging'}"""
17
55
  Backup(config=config).backup_db_and_folders()
18
56
 
19
57
 
20
- @shared_task
58
+ @shared_task(**TRANSIENT_RETRY)
21
59
  def backup_all_schemas(config=None):
22
60
  Backup(config=config).backup_db_and_folders(all_schemas=True)
23
61
 
@@ -0,0 +1,84 @@
1
+ """Transient network failures: the S3 client's retry budget, and the scheduled backup task
2
+ running again when an upload fails anyway."""
3
+ import socket
4
+ import unittest
5
+ from unittest.mock import patch
6
+
7
+ from django.test import SimpleTestCase
8
+
9
+ from cloud_backup import tasks
10
+
11
+ try:
12
+ from botocore.exceptions import ConnectionClosedError, EndpointConnectionError
13
+
14
+ from cloud_backup.storages.s3 import S3Storage
15
+ except ImportError: # pragma: no cover - a Google Drive-only host project
16
+ S3Storage = None
17
+
18
+
19
+ @unittest.skipIf(S3Storage is None, 'boto3 is not installed')
20
+ class S3RetryConfigTest(SimpleTestCase):
21
+
22
+ def config(self, client):
23
+ config = client.meta.config
24
+ return (config.retries['mode'], config.retries['total_max_attempts'],
25
+ config.connect_timeout, config.read_timeout)
26
+
27
+ def test_each_client_has_its_own_budget(self):
28
+ # an explicit endpoint, so no B2 authorisation call is made
29
+ storage = S3Storage('b', 'key', 'secret', endpoint_url='https://s3.example.com', region='x')
30
+ self.assertNotIn('copy_s3', vars(storage), 'built on first use')
31
+ self.assertEqual(self.config(storage.s3), ('standard', S3Storage.max_attempts,
32
+ S3Storage.connect_timeout, S3Storage.read_timeout))
33
+ self.assertEqual(self.config(storage.transfer_s3), ('standard', S3Storage.transfer_max_attempts,
34
+ S3Storage.connect_timeout, S3Storage.read_timeout))
35
+ self.assertEqual(self.config(storage.copy_s3), ('standard', S3Storage.copy_max_attempts,
36
+ S3Storage.connect_timeout, S3Storage.copy_read_timeout))
37
+
38
+ def test_listing_client_gives_up_within_minutes(self):
39
+ """What the web UI and status check wait on - attempts x timeout, plus at most
40
+ 20 s of backoff between attempts."""
41
+ worst = S3Storage.max_attempts * S3Storage.read_timeout + (S3Storage.max_attempts - 1) * 20
42
+ self.assertLessEqual(worst, 5 * 60)
43
+
44
+
45
+ class BuiltinNetworkErrorRetryTest(SimpleTestCase):
46
+ """Google Drive's client (httplib2) raises the builtin socket errors - no boto3 needed."""
47
+
48
+ def test_connection_reset_is_retried(self):
49
+ with patch.object(tasks, 'Backup') as backup:
50
+ backup.return_value.backup_db_and_folders.side_effect = [ConnectionResetError(104, 'reset'), None]
51
+ result = tasks.backup.apply(kwargs={'config': 'database'})
52
+ self.assertEqual(backup.return_value.backup_db_and_folders.call_count, 2)
53
+ self.assertTrue(result.successful())
54
+
55
+ def test_socket_timeout_is_transient(self):
56
+ self.assertTrue(issubclass(socket.timeout, tasks.TRANSIENT_ERRORS))
57
+
58
+
59
+ @unittest.skipIf(S3Storage is None, 'boto3 is not installed')
60
+ class BackupTaskRetryTest(SimpleTestCase):
61
+
62
+ def run_task(self, task, error):
63
+ """Eager apply runs each retry straight away, ignoring the delay."""
64
+ with patch.object(tasks, 'Backup') as backup:
65
+ backup.return_value.backup_db_and_folders.side_effect = error
66
+ result = task.apply(kwargs={'config': 'database'})
67
+ return result, backup.return_value.backup_db_and_folders.call_count
68
+
69
+ def test_connection_reset_is_retried_then_raised(self):
70
+ error = ConnectionClosedError(endpoint_url='https://s3.example.com/b/k?partNumber=35')
71
+ result, calls = self.run_task(tasks.backup, error)
72
+ self.assertEqual(calls, 1 + tasks.TRANSIENT_RETRY['max_retries'])
73
+ self.assertIsInstance(result.result, ConnectionClosedError)
74
+
75
+ def test_retry_that_succeeds(self):
76
+ error = EndpointConnectionError(endpoint_url='https://s3.example.com')
77
+ result, calls = self.run_task(tasks.backup_all_schemas, [error, None])
78
+ self.assertEqual(calls, 2)
79
+ self.assertTrue(result.successful())
80
+
81
+ def test_other_errors_are_not_retried(self):
82
+ result, calls = self.run_task(tasks.backup, ValueError('pg_dump failed'))
83
+ self.assertEqual(calls, 1)
84
+ self.assertIsInstance(result.result, ValueError)
@@ -16,8 +16,9 @@ KEY = 'django_backup/db/hourly/2026/08/28/db_2026_08_28_07_50_02.dump'
16
16
  MONTHLY = 'django_backup/db/monthly/db_2026-07.dump'
17
17
 
18
18
 
19
- def version(key, version_id, when, latest=False, size=100):
20
- return {'Key': key, 'VersionId': version_id, 'LastModified': when, 'Size': size, 'IsLatest': latest}
19
+ def version(key, version_id, when, latest=False, size=100, etag='"abc"'):
20
+ return {'Key': key, 'VersionId': version_id, 'LastModified': when, 'Size': size, 'IsLatest': latest,
21
+ 'ETag': etag}
21
22
 
22
23
 
23
24
  def marker(key, version_id, when, latest=True):
@@ -30,7 +31,8 @@ class S3TrashTest(SimpleTestCase):
30
31
  def storage(self, versions, markers):
31
32
  storage = S3Storage.__new__(S3Storage)
32
33
  storage.bucket = 'b'
33
- storage.s3 = MagicMock()
34
+ # one mock behind all three clients, so the asserts need not say which
35
+ storage.s3 = storage.transfer_s3 = storage.copy_s3 = MagicMock()
34
36
  storage.transfer_config = None
35
37
  storage.s3.get_paginator.return_value.paginate.return_value = [
36
38
  {'Versions': versions, 'DeleteMarkers': markers}]
@@ -54,6 +56,13 @@ class S3TrashTest(SimpleTestCase):
54
56
  self.assertEqual(trash[0]['hidden'], S3Storage.to_local_naive(datetime.datetime(2026, 8, 28, 12, 0, tzinfo=UTC)))
55
57
  self.assertEqual(trash[1]['hidden'], S3Storage.to_local_naive(datetime.datetime(2026, 8, 28, 12, 1, tzinfo=UTC)))
56
58
 
59
+ def test_list_versions_carries_the_etag(self):
60
+ storage = self.storage(
61
+ [version(KEY, 'old', datetime.datetime(2026, 8, 28, 6, 50, tzinfo=UTC), etag='"e1"'),
62
+ version(KEY, 'new', datetime.datetime(2026, 8, 28, 6, 51, tzinfo=UTC), latest=True, etag='"e1"')],
63
+ [marker(MONTHLY, 'mk', datetime.datetime(2026, 8, 28, 12, 1, tzinfo=UTC))])
64
+ self.assertEqual([e['hash'] for e in storage.list_versions('django_backup/db/')], ['e1', 'e1', None])
65
+
57
66
  def test_nothing_hidden_on_an_unversioned_bucket(self):
58
67
  storage = self.storage([version(KEY, 'null', datetime.datetime(2026, 8, 28, 6, 50, tzinfo=UTC), latest=True)], [])
59
68
  self.assertEqual(storage.list_files({'id': 'django_backup/db'}, deleted=True), [])
@@ -241,10 +241,10 @@ def fake_backups(objects):
241
241
  return make
242
242
 
243
243
 
244
- def entry(key, modified, marker=False):
244
+ def entry(key, modified, marker=False, size=1, file_hash=None):
245
245
  """A storage.list_versions() entry."""
246
- return {'key': key, 'version_id': 'v', 'modified': modified, 'size': None if marker else 1, 'marker': marker,
247
- 'is_latest': False}
246
+ return {'key': key, 'version_id': 'v', 'modified': modified, 'size': None if marker else size, 'marker': marker,
247
+ 'hash': None if marker else file_hash, 'is_latest': False}
248
248
 
249
249
 
250
250
  class VersionAuditTest(SimpleTestCase):
@@ -281,6 +281,16 @@ class VersionAuditTest(SimpleTestCase):
281
281
  entry(self.HOURLY, datetime.datetime(2026, 8, 10, 11, 0))]
282
282
  self.assertEqual([u['kind'] for u in audit_versions(entries, self.EXPIRE)[0]], ['overwritten'])
283
283
 
284
+ def test_overwrite_with_the_same_content_is_a_retried_copy(self):
285
+ # the copy answered after the client's timeout, so the client sent it again
286
+ def versions(*contents):
287
+ return [entry(self.HOURLY, datetime.datetime(2026, 8, 10, 9, 50 + i), size=size, file_hash=file_hash)
288
+ for i, (size, file_hash) in enumerate(contents)]
289
+ self.assertEqual(audit_versions(versions((5, 'abc'), (5, 'abc')), self.EXPIRE), ([], 0))
290
+ for different in (versions((5, 'abc'), (5, 'abd')), versions((5, 'abc'), (6, 'abc')),
291
+ versions((5, 'abc'), (5, 'abc'), (5, 'abd')), versions((5, None), (5, None))):
292
+ self.assertEqual([u['kind'] for u in audit_versions(different, self.EXPIRE)[0]], ['overwritten'])
293
+
284
294
  def test_lone_marker_dated_from_the_name(self):
285
295
  # the version is already purged, but the name says the dump was 2 days old when hidden
286
296
  entries = [entry(self.HOURLY, datetime.datetime(2026, 8, 12, 9, 50), marker=True)]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: django-cloud-backup
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Backs up django postgres databases, local folders and S3 folders to Google Drive, S3-compatible storage (AWS, Backblaze B2, Cloudflare R2) or Azure Blob Storage.
5
5
  Author: Ian Jones
6
6
  License-Expression: MIT
@@ -403,7 +403,9 @@ the name, date and size still look right, and the real version sits hidden under
403
403
  until the purge. So for tiered configs the status check also audits the bucket's
404
404
  versions: dumps get unique names and are only ever hidden by expiry once they are
405
405
  `expire_days` old, so a dump hidden younger than that, anything hidden under `monthly/`,
406
- or a key holding two real versions is someone else's doing. The `Version audit` row
406
+ or a key holding two real versions is someone else's doing. Versions that are all the
407
+ same size and hash are not counted: that is a server-side copy the client retried after
408
+ a timeout, the same bytes written twice. The `Version audit` row
407
409
  names them, says whether they are `hidden` (still recoverable), `overwritten` or already
408
410
  `purged`, and gives the deadline the purge clock sets - run `backup_status` more often
409
411
  than `purge_days`.
@@ -50,6 +50,7 @@ cloud_backup/tests/__init__.py
50
50
  cloud_backup/tests/test_backup_azure.py
51
51
  cloud_backup/tests/test_db_tiers.py
52
52
  cloud_backup/tests/test_extensions.py
53
+ cloud_backup/tests/test_retries.py
53
54
  cloud_backup/tests/test_s3_trash.py
54
55
  cloud_backup/tests/test_status.py
55
56
  django_cloud_backup.egg-info/PKG-INFO
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django-cloud-backup"
7
- version = "0.1.2"
7
+ version = "0.1.3"
8
8
  description = "Backs up django postgres databases, local folders and S3 folders to Google Drive, S3-compatible storage (AWS, Backblaze B2, Cloudflare R2) or Azure Blob Storage."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"