nextcloud-s3-backup 1.0.0__py3-none-any.whl

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.
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
File without changes
@@ -0,0 +1,430 @@
1
+ import hashlib
2
+ import logging
3
+ import shutil
4
+ import statistics
5
+ import time
6
+ from collections import namedtuple
7
+ from dataclasses import dataclass
8
+ from datetime import datetime
9
+ from pathlib import Path
10
+ from time import perf_counter
11
+
12
+ from cloudpathlib import CloudPath
13
+
14
+ from nc_s3_backup.api.config import (
15
+ NextcloudDirectoryConfig,
16
+ NextCloudS3BackupConfig,
17
+ PathLike,
18
+ )
19
+ from nc_s3_backup.api.db import DaoNextcloudFiles, NextcloudFile
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ REPOSITORY_DIRNAME = ".data"
25
+ SNAPSHOT_DIRNAME = "snapshots"
26
+ GB = 1024 * 1024 * 1024
27
+ time_reports = {}
28
+
29
+ PurgedFile = namedtuple("PurgedFile", ["size"])
30
+
31
+
32
+ def timer(func):
33
+ def wrap_func(*args, **kwargs):
34
+ t1 = perf_counter()
35
+ result = func(*args, **kwargs)
36
+ t2 = perf_counter()
37
+ if func.__name__ not in time_reports.keys():
38
+ time_reports[func.__name__] = []
39
+ time_reports[func.__name__].append(t2 - t1)
40
+ return result
41
+
42
+ return wrap_func
43
+
44
+
45
+ @dataclass
46
+ class NextcloudS3Backup:
47
+ """Main class that download files on the locale FS"""
48
+
49
+ dao: DaoNextcloudFiles
50
+ config: NextCloudS3BackupConfig
51
+ _backup_exceptions = 0
52
+ _current_backup_formatted_date: datetime = None
53
+
54
+ _sha1_file_per_inode: dict[int, Path] = None
55
+
56
+ @timer
57
+ def populate_sha1_file_per_inode(self, dir_config: NextcloudDirectoryConfig):
58
+ sha1_dir = dir_config.backup_root_path / REPOSITORY_DIRNAME / "sha1"
59
+ if sha1_dir.exists():
60
+ self._sha1_file_per_inode = self._populate_sha1_file_per_inode(
61
+ dir_config.backup_root_path / REPOSITORY_DIRNAME / "sha1", {}
62
+ )
63
+ else:
64
+ self._sha1_file_per_inode = {}
65
+
66
+ def _populate_sha1_file_per_inode(
67
+ self, directory: Path, inodes: dict[int, Path] = None
68
+ ) -> set[int]:
69
+ for child in directory.iterdir():
70
+ if child.is_dir():
71
+ inodes = self._populate_sha1_file_per_inode(child, inodes=inodes)
72
+ else:
73
+ inodes[child.stat().st_ino] = child
74
+ return inodes
75
+
76
+ def _ensure_sha1_file_per_inode_exists(self, repo_file):
77
+ self._sha1_file_per_inode[repo_file.stat().st_ino] = repo_file
78
+
79
+ @property
80
+ def current_backup_formatted_date(self):
81
+ if not self._current_backup_formatted_date:
82
+ self._current_backup_formatted_date = datetime.now().strftime(
83
+ self.config.backup_date_format
84
+ )
85
+ return self._current_backup_formatted_date
86
+
87
+ def backup(self):
88
+ logger.info("%s mapping to backup", len(self.config.mapping))
89
+ self._backup_exceptions = 0
90
+ for dir_config in self.config.mapping:
91
+ self.populate_sha1_file_per_inode(dir_config)
92
+ self._backup_directory(dir_config)
93
+
94
+ self.print_timer_info()
95
+ logger.info("Backup done (with %d errors)", self._backup_exceptions)
96
+ return self._backup_exceptions
97
+
98
+ @property
99
+ def distinct_backup_root_paths(self):
100
+ return list({conf.backup_root_path for conf in self.config.mapping})
101
+
102
+ @timer
103
+ def purge(self):
104
+ purged = []
105
+ logger.info("Purging %d directories", len(self.distinct_backup_root_paths))
106
+ for root_path in self.distinct_backup_root_paths:
107
+ snapshots_inodes = self._get_inodes(root_path / SNAPSHOT_DIRNAME)
108
+ repo_purged = self._purge_directory(
109
+ root_path / REPOSITORY_DIRNAME / "sha1", snapshots_inodes
110
+ )
111
+ logger.info(
112
+ "**SHA1** Directory: %s - %d file(s) removed that represent %.3f GB",
113
+ root_path,
114
+ len(repo_purged),
115
+ sum([f.size for f in repo_purged]),
116
+ )
117
+ purged.extend(repo_purged)
118
+ # purging etag separately because:
119
+ # * sha1 and etags are hard linked to and we just purge sha1
120
+ # files that are not present in snapshots
121
+ # * we don't want to sum etag and sha1 file size
122
+ etag_purged = self._purge_directory(
123
+ root_path / REPOSITORY_DIRNAME / "etag", snapshots_inodes
124
+ )
125
+ logger.info(
126
+ "**Etag** Directory: %s - %d file(s) removed that represent %.3f GB",
127
+ root_path,
128
+ len(etag_purged),
129
+ sum([f.size for f in etag_purged]),
130
+ )
131
+ self.print_timer_info()
132
+ logger.info(
133
+ "Total purged: %d file(s) removed that represent %.3f GB",
134
+ len(repo_purged) + len(etag_purged),
135
+ sum([f.size for f in repo_purged]),
136
+ )
137
+
138
+ @timer
139
+ def _get_inodes(self, directory: Path, inodes: set[int] = None) -> set[int]:
140
+ if not inodes:
141
+ inodes = set()
142
+ for child in directory.iterdir():
143
+ if child.is_dir():
144
+ inodes = self._get_inodes(child, inodes=inodes)
145
+ else:
146
+ inodes |= {child.stat().st_ino}
147
+ return inodes
148
+
149
+ @timer
150
+ def _purge_directory(
151
+ self, repo_directory: Path, snapshots_inodes: set[int]
152
+ ) -> list[PurgedFile]:
153
+ purged = []
154
+ for child in repo_directory.iterdir():
155
+ if child.is_dir():
156
+ purged.extend(self._purge_directory(child, snapshots_inodes))
157
+ else:
158
+ purged.extend(self._purge_file(child, snapshots_inodes))
159
+ return purged
160
+
161
+ @timer
162
+ def _purge_file(
163
+ self, repo_file: Path, snapshots_inodes: set[int]
164
+ ) -> list[PurgedFile]:
165
+ unlink_file_stat = []
166
+ if repo_file.stat().st_ino not in snapshots_inodes:
167
+ unlink_file_stat.append(PurgedFile(size=repo_file.stat().st_size / GB))
168
+ repo_file.unlink()
169
+ return unlink_file_stat
170
+
171
+ def print_timer_info(self):
172
+ logger.info("Timmer info...")
173
+ for method_name, times in time_reports.items():
174
+ logger.info(
175
+ "Method %s - Calls count: %d - Total time: %.1f - AVG: %.5f - MEDIAN: %.5f",
176
+ method_name,
177
+ len(times),
178
+ sum(times),
179
+ statistics.mean(times),
180
+ statistics.median(times),
181
+ )
182
+
183
+ def _backup_directory(self, dir_config: NextcloudDirectoryConfig):
184
+ logger.info(
185
+ "Backup-ing %s - %s ...", dir_config.user_name, dir_config.nextcloud_path
186
+ )
187
+ for nc_file in self.dao.get_nc_subtree(
188
+ dir_config.storage_id,
189
+ dir_config.nextcloud_path,
190
+ self.config.excluded_mimetype_ids,
191
+ ):
192
+ try:
193
+ self._backup_file(nc_file, dir_config)
194
+ except Exception as ex:
195
+ self._backup_exceptions += 1
196
+ if self._backup_exceptions > self.config.allowed_ignored_errors:
197
+ raise ex
198
+ else:
199
+ logging.warning(
200
+ "Ignoring (%d/%d allowed ignored errors) file %s with error: %r",
201
+ self._backup_exceptions,
202
+ self.config.allowed_ignored_errors,
203
+ nc_file,
204
+ ex,
205
+ )
206
+
207
+ @timer
208
+ def _backup_file(
209
+ self, nc_file: NextcloudFile, dir_config: NextcloudDirectoryConfig
210
+ ):
211
+ local_file = (
212
+ dir_config.backup_root_path
213
+ / SNAPSHOT_DIRNAME
214
+ / self.current_backup_formatted_date
215
+ / dir_config.user_name
216
+ ) / nc_file.path
217
+ if nc_file.size == 0:
218
+ # mainly caused by this issue
219
+ # https://github.com/nextcloud/desktop/issues/4909
220
+ # (files with data store in resource fork only are not synced
221
+ # by nextcloud client) we got a lot of empty file in our nextcloud
222
+ # so we get the hardlink count limit maximum (~65000 links with less
223
+ # than 30 snapshots)
224
+ # In such case of empty file we leave placeholder creating new empty file
225
+ # instead hard links based on the nextcloud table information
226
+ local_file.parent.mkdir(parents=True, exist_ok=True)
227
+ local_file.touch()
228
+ return local_file
229
+
230
+ s3_path = dir_config.bucket / f"urn:oid:{nc_file.fileid}"
231
+ logger.debug(
232
+ "Backup-ing %s - %s - %s to %s...",
233
+ dir_config.user_name,
234
+ nc_file.path,
235
+ s3_path,
236
+ local_file,
237
+ )
238
+ if nc_file.checksum and nc_file.checksum.lower().startswith("sha1"):
239
+ repo_file = self._backup_file_with_sha1(nc_file, dir_config, s3_path)
240
+ if not repo_file:
241
+ return
242
+ else:
243
+ repo_file = self._backup_file_without_sha1(nc_file, dir_config, s3_path)
244
+ if not repo_file:
245
+ return
246
+ self._ensure_sha1_file_per_inode_exists(repo_file)
247
+ local_file.parent.mkdir(parents=True, exist_ok=True)
248
+ local_file.hardlink_to(repo_file)
249
+ return local_file
250
+
251
+ @timer
252
+ def _download_s3_file(self, s3_path: PathLike, download_path: Path):
253
+ if isinstance(s3_path, CloudPath):
254
+ s3_path.download_to(download_path)
255
+ else:
256
+ shutil.copy(s3_path, download_path)
257
+
258
+ @classmethod
259
+ @timer
260
+ def _compute_sha1(cls, file: Path) -> str:
261
+ with file.open("rb") as f:
262
+ return f"SHA1:{hashlib.file_digest(f, 'sha1').hexdigest()}" # nosec
263
+
264
+ @timer
265
+ def _backup_file_with_sha1(
266
+ self,
267
+ nc_file: NextcloudFile,
268
+ dir_config: NextcloudDirectoryConfig,
269
+ s3_path: Path,
270
+ ) -> Path:
271
+ repo_file = dir_config.backup_root_path / REPOSITORY_DIRNAME / nc_file.hash_path
272
+ if not repo_file.exists():
273
+ if s3_path.exists():
274
+ downloading_path = repo_file.with_suffix(".downloading")
275
+ downloading_path.parent.mkdir(parents=True, exist_ok=True)
276
+ self._download_s3_file(s3_path, downloading_path)
277
+ sha1 = self._compute_sha1(downloading_path)
278
+ if sha1.lower() != nc_file.checksum.lower():
279
+ logger.warning(
280
+ "SHA1 hash mismatched on file %s (%s). "
281
+ "NC table: %s - downloaded: %s. "
282
+ "Use local downloaded file hash instead.",
283
+ nc_file.fileid,
284
+ nc_file.path,
285
+ nc_file.checksum,
286
+ sha1,
287
+ )
288
+ nc_file.checksum = sha1
289
+ repo_file = (
290
+ dir_config.backup_root_path
291
+ / REPOSITORY_DIRNAME
292
+ / nc_file.hash_path
293
+ )
294
+ repo_file.parent.mkdir(parents=True, exist_ok=True)
295
+ downloading_path.rename(repo_file)
296
+ else:
297
+ logger.warning(
298
+ "Ignoring Nextcloud record DB file not found on s3. "
299
+ "Storage: %s - path %s",
300
+ nc_file.storage,
301
+ s3_path,
302
+ )
303
+ return
304
+ return repo_file
305
+
306
+ @timer
307
+ def _backup_file_without_sha1(
308
+ self,
309
+ nc_file: NextcloudFile,
310
+ dir_config: NextcloudDirectoryConfig,
311
+ s3_path: Path,
312
+ ):
313
+ if s3_path.exists():
314
+ return self._backup_file_with_etag(
315
+ nc_file,
316
+ dir_config,
317
+ s3_path,
318
+ f"ETAG:{self._get_s3_stat_etag(s3_path)}",
319
+ )
320
+ else:
321
+ logger.warning(
322
+ "Ignoring Nextcloud record DB file not found on s3. "
323
+ "Storage: %s - path %s",
324
+ nc_file.storage,
325
+ s3_path,
326
+ )
327
+ return
328
+
329
+ def _get_s3_stat_etag(
330
+ self,
331
+ s3_path: PathLike,
332
+ ):
333
+ """retry"""
334
+ etag = None
335
+ latest_exception = None
336
+ for tries in range(0, self.config.s3_head_object_retries):
337
+ try:
338
+ raw_etag = s3_path.etag
339
+ etag = raw_etag.strip('"') if raw_etag else raw_etag
340
+ break
341
+ except Exception as ex:
342
+ logging.warning(
343
+ "(try %d/%d) Ignoring following error while getting etag "
344
+ "on %s (waiting %ds before retry): %r",
345
+ tries + 1,
346
+ self.config.s3_head_object_retries,
347
+ s3_path,
348
+ self.config.s3_head_object_interval_s,
349
+ ex,
350
+ )
351
+ latest_exception = ex
352
+ time.sleep(self.config.s3_head_object_interval_s)
353
+ else:
354
+ raise latest_exception
355
+ return etag
356
+
357
+ @timer
358
+ def _find_sha1_from_inode(
359
+ self, dir_config: NextcloudDirectoryConfig, searched_file: Path
360
+ ) -> Path:
361
+ sha1_directory = dir_config.backup_root_path / REPOSITORY_DIRNAME / "sha1"
362
+ repo_file = self._find_files_with_same_inode_as(sha1_directory, searched_file)
363
+ if repo_file:
364
+ # only the first one we shouldn't get two here
365
+ return repo_file
366
+ logger.warning(
367
+ "No sha1 files found searching files %s (inode: %s) in %s",
368
+ searched_file,
369
+ searched_file.stat().st_ino,
370
+ sha1_directory,
371
+ )
372
+ return repo_file
373
+
374
+ def _find_files_with_same_inode_as(
375
+ self, root_search_directory: Path, searched_file: Path
376
+ ):
377
+ return self._sha1_file_per_inode.get(searched_file.stat().st_ino)
378
+
379
+ @timer
380
+ def _backup_file_with_etag(
381
+ self,
382
+ nc_file: NextcloudFile,
383
+ dir_config: NextcloudDirectoryConfig,
384
+ s3_path: Path,
385
+ etag: str,
386
+ ) -> Path:
387
+ nc_file.checksum = etag
388
+ etag_repo_file = (
389
+ dir_config.backup_root_path / REPOSITORY_DIRNAME / nc_file.hash_path
390
+ )
391
+ repo_file = None
392
+ if not etag_repo_file.exists():
393
+ downloading_path = etag_repo_file.with_suffix(".downloading")
394
+ downloading_path.parent.mkdir(parents=True, exist_ok=True)
395
+ self._download_s3_file(s3_path, downloading_path)
396
+ nc_file.checksum = self._compute_sha1(downloading_path)
397
+ repo_file = (
398
+ dir_config.backup_root_path / REPOSITORY_DIRNAME / nc_file.hash_path
399
+ )
400
+ if repo_file.exists():
401
+ downloading_path.unlink()
402
+ etag_repo_file.hardlink_to(repo_file)
403
+ else:
404
+ downloading_path.rename(etag_repo_file)
405
+ repo_file.parent.mkdir(parents=True, exist_ok=True)
406
+ repo_file.hardlink_to(etag_repo_file)
407
+ else:
408
+ repo_file = self._find_sha1_from_inode(dir_config, etag_repo_file)
409
+ if not repo_file or not repo_file.exists():
410
+ # weird case
411
+ nc_file.checksum = self._compute_sha1(etag_repo_file)
412
+ repo_file = (
413
+ dir_config.backup_root_path / REPOSITORY_DIRNAME / nc_file.hash_path
414
+ )
415
+ if repo_file.exists():
416
+ # assuming inconsistency data wrongly synced
417
+ # .data losing hardlink
418
+ # in such case the best thing to do is to recreate
419
+ # etag from sha1 as long snapshot files point to sha1 files
420
+ # we do not want to remove sha1
421
+ etag_repo_file.unlink()
422
+ etag_repo_file.hardlink_to(repo_file)
423
+ else:
424
+ repo_file.parent.mkdir(parents=True, exist_ok=True)
425
+ repo_file.hardlink_to(etag_repo_file)
426
+ else:
427
+ sha1 = "".join(repo_file.parts[:2])
428
+ nc_file.checksum = f"SHA1:{sha1}"
429
+
430
+ return repo_file
@@ -0,0 +1,54 @@
1
+ from dataclasses import field
2
+ from pathlib import Path
3
+ from typing import Annotated
4
+
5
+ from cloudpathlib import AnyPath, CloudPath
6
+ from pydantic import BeforeValidator, ConfigDict, PlainSerializer
7
+ from pydantic.dataclasses import dataclass
8
+
9
+ PathLike = CloudPath | Path
10
+
11
+
12
+ def _parse_any_path(value: str | Path | CloudPath | None) -> PathLike | None:
13
+ if value is None or isinstance(value, (Path, CloudPath)):
14
+ return value
15
+ return AnyPath(value)
16
+
17
+
18
+ def _serialize_any_path(value: PathLike | None) -> str | None:
19
+ if value is None:
20
+ return None
21
+ return str(value)
22
+
23
+
24
+ AnyPathField = Annotated[
25
+ PathLike | None,
26
+ BeforeValidator(_parse_any_path),
27
+ PlainSerializer(_serialize_any_path, return_type=str | None),
28
+ ]
29
+
30
+
31
+ @dataclass(config=ConfigDict(arbitrary_types_allowed=True))
32
+ class NextcloudDirectoryConfig:
33
+ storage_id: int | None = None
34
+ user_name: str | None = None
35
+ bucket: AnyPathField = None
36
+ nextcloud_path: str | None = None
37
+ backup_root_path: Path | None = None
38
+
39
+
40
+ @dataclass(config=ConfigDict(arbitrary_types_allowed=True))
41
+ class NextCloudS3BackupConfig:
42
+ """Config file contains tree mapping to backup"""
43
+
44
+ backup_date_format: str = "%y%m%d-%H%M"
45
+ excluded_mimetype_ids: list[int] = field(default_factory=list)
46
+ s3_head_object_retries: int = 10
47
+ """Number of retry while retrieve s3_path.etag value"""
48
+ s3_head_object_interval_s: float = 3.0
49
+ """Number of second to wait between two try"""
50
+
51
+ allowed_ignored_errors: int = 0
52
+ """Number of allowed ignored errors while saving files"""
53
+
54
+ mapping: list[NextcloudDirectoryConfig] = field(default_factory=list)
nc_s3_backup/api/db.py ADDED
@@ -0,0 +1,138 @@
1
+ import logging
2
+ from dataclasses import dataclass
3
+ from pathlib import PurePath
4
+
5
+ import psycopg2
6
+ from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
7
+
8
+ logger = logging.getLogger(__name__)
9
+ SAVEPOINT_NAME = "nc_s3_backup_save_point"
10
+
11
+
12
+ @dataclass
13
+ class NextcloudFile:
14
+ """
15
+ used? | Field name | info | data example
16
+ * | fileid | oid, file stored in S3
17
+ bucket as urn:oid:579 | 579
18
+ * | storage | storage id |2
19
+ * | path | path as seen by users | files/test/test.txt
20
+ | path_hash | hash of path field | d2ecf433b...317757e331
21
+ | parent | directory fileid in
22
+ this table | 549
23
+ | name | file name | f2_fichier_modifie_sur_poste_1
24
+ | mimetype | mimetype id | 9
25
+ | mimepart | first part mimetype id
26
+ text/md => text | 3
27
+ | size | | 67
28
+ | mtime | | 1640342159
29
+ | storage_mtime | | 1640342164
30
+ | encrypted | | 0
31
+ | unencrypted_size | | 0
32
+ | etag | | 61c5a2940ccc7
33
+ | permissions | | 27
34
+ * | checksum | file hash | SHA1:00dea...94d34d1623
35
+ """
36
+
37
+ fileid: int
38
+ storage: int
39
+ path: str
40
+ checksum: str
41
+ size: int
42
+
43
+ @property
44
+ def hash_path(self):
45
+ """return relative path construct from file checksum
46
+
47
+ in order to store data as
48
+ hash_method / hash_begining / hash_end
49
+ """
50
+ method, hash_value = self.checksum.lower().split(":", 1)
51
+ return PurePath(method, hash_value[:2], hash_value[2:])
52
+
53
+
54
+ class Dao:
55
+ _cr = None
56
+ _cnx = None
57
+ _ids = 0
58
+ _schema = None
59
+ is_open = False
60
+
61
+ @classmethod
62
+ def open_cnx_cursor(cls, pg_url, schema="public"):
63
+ if not Dao._cnx:
64
+ Dao._cnx = psycopg2.connect(pg_url)
65
+ Dao._cr = Dao._cnx.cursor()
66
+ Dao._cnx.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)
67
+ Dao._schema = schema
68
+ Dao.set_default_schema(Dao._schema)
69
+ Dao._ids += 1
70
+ cls.is_open = True
71
+
72
+ def __init__(self, pg_url, schema="public"):
73
+ self.open_cnx_cursor(pg_url, schema=schema)
74
+
75
+ @classmethod
76
+ def set_default_schema(cls, schema):
77
+ Dao._cr.execute(f"SET search_path TO {schema}")
78
+
79
+ @classmethod
80
+ def commit(cls):
81
+ Dao._cnx.commit()
82
+
83
+ @classmethod
84
+ def add_save_point(cls, name=SAVEPOINT_NAME):
85
+ Dao._cr.execute(f"SAVEPOINT {name}")
86
+ Dao.set_default_schema(cls._schema)
87
+
88
+ @classmethod
89
+ def rollback_to_savepoint(cls, name=SAVEPOINT_NAME):
90
+ Dao._cr.execute(f"ROLLBACK TO SAVEPOINT {name}")
91
+
92
+ @classmethod
93
+ def rollback(cls):
94
+ Dao._cnx.rollback()
95
+ Dao.set_default_schema(cls._schema)
96
+
97
+ @classmethod
98
+ def close(cls):
99
+ if cls.is_open:
100
+ cls.is_open = False
101
+ Dao._ids -= 1
102
+ if Dao._ids == 0:
103
+ Dao._cnx.close()
104
+ Dao._cnx = None
105
+
106
+ def __del__(self):
107
+ try:
108
+ self.close()
109
+ except Exception as ex:
110
+ logger.error(
111
+ "Following exception occurred while trying to close connection: %s", ex
112
+ )
113
+
114
+
115
+ class DaoNextcloudFiles(Dao):
116
+ """Method to retrieve Nextcloud database information"""
117
+
118
+ def get_nc_subtree(
119
+ self, storage_id: int, root_path: str, excluded_mimetype: list[int]
120
+ ) -> list[NextcloudFile]:
121
+ search_path = root_path + "%"
122
+ # TODO: manage checksum null or empty
123
+ query = """
124
+ SELECT fileid, storage, path, checksum, size
125
+ FROM oc_filecache
126
+ WHERE storage=%(storage_id)s
127
+ AND path ILIKE %(path)s
128
+ AND mimetype NOT IN %(excluded_mimetype)s
129
+ """
130
+ self._cr.execute(
131
+ query,
132
+ {
133
+ "storage_id": storage_id,
134
+ "path": search_path,
135
+ "excluded_mimetype": tuple(excluded_mimetype),
136
+ },
137
+ )
138
+ return [NextcloudFile(*r) for r in self._cr.fetchall()]