Debian Codegraph @

greenbone/feed/sync/rsync.py

raw
1 # SPDX-FileCopyrightText: 2022-2024 Greenbone AG
2 #
3 # SPDX-License-Identifier: GPL-3.0-or-later
4 #
5
6 import asyncio
7 import os
8 from pathlib import Path
9 from typing import Iterable, Optional, Union
10 from urllib.parse import urlsplit
11
12 from greenbone.feed.sync.errors import RsyncError
13
14
15 async def exec_rsync(*args: str) -> None:
16 """
17 Run rsync
18
19 Argument:
20 args: Arguments for rsync
21 """
22 process = await asyncio.create_subprocess_exec(
23 "rsync", *args, stderr=asyncio.subprocess.PIPE
24 )
25 _, stderr = await process.communicate()
26 returncode = await process.wait()
27 if returncode:
28 raise RsyncError(returncode, args, stderr=stderr)
29
30
31 DEFAULT_RSYNC_URL = "rsync://feed.community.greenbone.net/community"
32 DEFAULT_RSYNC_COMPRESSION_LEVEL = 9
33 DEFAULT_RSYNC_TIMEOUT: Optional[int] = (
34 None # in seconds. 0 means no timeout and None use rsync default
35 )
36 DEFAULT_RSYNC_SSH_PORT = 24
37 DEFAULT_RSYNC_SSH_OPTS = (
38 "-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"
39 )
40
41 PathLike = Union[os.PathLike, str]
42
43
44 class Rsync:
45 """
46 Class to sync the feed data via rsync
47
48 Args:
49 verbose: Enable verbose output
50 private_subdir: A private directory to exclude from from the sync
51 compression_level: Set an compression level explicitly.
52 Default is 9 (highest).
53 timeout: Set a specific timeout in seconds. Default timeout of rsync is
54 used of not set explicitly. 0 for no timeout.
55 ssh_key: SSH key for using ssh as rsync transport protocol.
56 exclude: An iterable of directories to exclude from the sync.
57
58 """
59
60 def __init__(
61 self,
62 *,
63 verbose: bool = False,
64 private_subdir: Optional[PathLike] = None,
65 compression_level: Optional[int] = DEFAULT_RSYNC_COMPRESSION_LEVEL,
66 timeout: Optional[int] = DEFAULT_RSYNC_TIMEOUT,
67 ssh_key: Optional[PathLike] = None,
68 exclude: Optional[Iterable[PathLike]] = None,
69 ) -> None:
70 self.verbose = verbose
71 self.private_subdir = private_subdir
72 self.compression_level = compression_level
73 self.timeout = timeout
74 self.ssh_key = ssh_key
75 self.exclude = exclude
76
77 async def sync(self, url: str, destination: PathLike) -> None:
78 """
79 Sync data from a remote URL to a destination path
80
81 Args:
82 url: URL to sync
83 destination: Path to store the downloaded data
84 """
85 dest = Path(destination)
86 dest.mkdir(parents=True, exist_ok=True)
87 splitted_url = urlsplit(url)
88
89 rsync_default_options = [
90 "--links",
91 "--times",
92 "--omit-dir-times",
93 "--recursive",
94 "--partial",
95 "--progress",
96 ]
97
98 if "ssh" in splitted_url.scheme:
99 port = splitted_url.port or DEFAULT_RSYNC_SSH_PORT
100 # we use ssh now
101 rsync_ssh_options = [
102 "-e",
103 f"ssh {DEFAULT_RSYNC_SSH_OPTS} -p {port} -i '{self.ssh_key}'",
104 ]
105 url = f"{splitted_url.netloc}:{splitted_url.path}"
106 else:
107 rsync_ssh_options = []
108
109 rsync_timeout = (
110 [
111 f"--timeout={self.timeout}",
112 ]
113 if self.timeout is not None
114 else []
115 )
116
117 rsync_compress = (
118 [
119 f"--compress-level={self.compression_level}",
120 ]
121 if self.compression_level is not None
122 else []
123 )
124
125 rsync_delete = [
126 "--delete",
127 ]
128
129 rsync_chmod = [
130 "--perms",
131 "--chmod=Fugo+r,Fug+w,Dugo-s,Dugo+rx,Dug+w",
132 ]
133
134 rsync_links = [
135 "--copy-unsafe-links",
136 "--hard-links",
137 ]
138
139 if self.private_subdir:
140 rsync_delete.extend(["--exclude", os.fspath(self.private_subdir)])
141
142 if self.exclude:
143 for exclude in self.exclude:
144 rsync_delete.extend(["--exclude", os.fspath(exclude)])
145
146 rsync_verbose = ["-v"] if self.verbose else ["-q"]
147
148 args = (
149 rsync_default_options
150 + rsync_ssh_options
151 + rsync_timeout
152 + rsync_verbose
153 + rsync_compress
154 + rsync_delete
155 + rsync_chmod
156 + rsync_links
157 + [url, str(dest.absolute())]
158 )
159
160 await exec_rsync(*args)