py-jsync 0.2.31__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.

Potentially problematic release.


This version of py-jsync might be problematic. Click here for more details.

jsync/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ import importlib.metadata as importlib_metadata
2
+
3
+ from jsync.jsync import synchronize
4
+ from jsync.rsync import RSync
5
+ from jsync.syncer import Syncer
6
+
7
+
8
+ def _get_version() -> str:
9
+ # Distribution name can differ from import package name (e.g. "py-jsync" vs "jsync").
10
+ for dist in ("py-jsync", "jsync"):
11
+ try:
12
+ return importlib_metadata.version(dist)
13
+ except importlib_metadata.PackageNotFoundError:
14
+ continue
15
+ return "0.0.0"
16
+
17
+
18
+ __version__ = _get_version()
19
+
20
+ __all__ = ["RSync", "Syncer", "synchronize"]
jsync/columns.py ADDED
@@ -0,0 +1,42 @@
1
+ from rich.progress import (
2
+ Column,
3
+ Highlighter,
4
+ JustifyMethod,
5
+ ProgressColumn,
6
+ StyleType,
7
+ Task,
8
+ Text,
9
+ )
10
+
11
+
12
+ class FlexiColumn(ProgressColumn):
13
+ """A column containing Download Rate"""
14
+
15
+ def __init__(
16
+ self,
17
+ func: callable,
18
+ style: StyleType = "none",
19
+ justify: JustifyMethod = "left",
20
+ markup: bool = True,
21
+ highlighter: Highlighter | None = None,
22
+ table_column: Column | None = None,
23
+ ) -> None:
24
+ self.func = func
25
+ self.justify: JustifyMethod = justify
26
+ self.style = style
27
+ self.markup = markup
28
+ self.highlighter = highlighter
29
+ super().__init__()
30
+
31
+ def render(self, task: "Task") -> Text:
32
+ _text = self.func(task)
33
+
34
+ if self.markup:
35
+ text = Text.from_markup(_text, style=self.style, justify=self.justify)
36
+ else:
37
+ text = Text(_text, style=self.style, justify=self.justify)
38
+
39
+ if self.highlighter:
40
+ self.highlighter.highlight(text)
41
+
42
+ return text
jsync/job.py ADDED
@@ -0,0 +1,196 @@
1
+ import random
2
+ import re
3
+
4
+ from humanize import naturalsize
5
+ from rich.progress import Progress, TaskID
6
+
7
+ from .rsync import RSync
8
+ from .utils import dehumanize_rate, elapsed_time, parse_bytes_token
9
+
10
+
11
+ class Job:
12
+ id: int
13
+ files: list
14
+ progress: Progress
15
+ task: TaskID
16
+ color: int
17
+ running: bool
18
+ rsync: RSync
19
+ file: str
20
+ size: int
21
+ total: int
22
+ total_size: int
23
+ percent: float
24
+ rate: float
25
+ callback: callable
26
+ error_buf: str
27
+
28
+ def __init__(
29
+ self,
30
+ id: int,
31
+ files: list,
32
+ progress: Progress,
33
+ rsync: RSync,
34
+ callback: callable,
35
+ total_size: int = 0,
36
+ ) -> None:
37
+ self.id = id
38
+ self.files = files
39
+ self.progress = progress
40
+ self.rsync = rsync
41
+ self.running = False
42
+ self.color = random.randint(20, 230)
43
+ self.rate = 0
44
+ self.file = ''
45
+ self.percent = 0
46
+ self.size = 0
47
+ self.total = 0
48
+ self.total_size = total_size
49
+ self.callback = callback
50
+ self.error_buf = ''
51
+ self.task = progress.add_task(
52
+ f"rsync [bold yellow]#{id}",
53
+ rate=0,
54
+ filename='',
55
+ percent='',
56
+ eta='',
57
+ total=0,
58
+ style=f'[color({self.color})]',
59
+ )
60
+
61
+ def start(self):
62
+ self.progress.start_task(self.task)
63
+ cmd = ' '.join(self.rsync.transfer_command())
64
+ num_files = len(self.files)
65
+ total_size_str = naturalsize(self.total_size, gnu=True)
66
+ self.progress.console.print(
67
+ f"[bright_cyan]Starting job #{self.id}:[/bright_cyan] {cmd} "
68
+ f"({total_size_str} in {num_files:,} files)",
69
+ highlight=False,
70
+ )
71
+ # Set an initial total immediately (from itemize), so progress UI does not stay 0B/0B
72
+ # until the first progress2 line arrives.
73
+ if self.total_size:
74
+ self.total = self.total_size
75
+ self.progress.update(
76
+ self.task,
77
+ total=self.total_size,
78
+ completed=0,
79
+ rate=0,
80
+ )
81
+ # Kick master progress to include this job's total right away.
82
+ self.callback(0, self)
83
+ self.running = True
84
+
85
+ def active(self):
86
+ return self.running
87
+
88
+ def process_progress(self, line):
89
+ # file transferred:
90
+ # folder1/folder2/IMG_7440.xmp
91
+ # progress reported:
92
+ # 123455332 0% 263.33MB/s 0:00:00 (xfr#2, to-chk=22854/22861)
93
+ # 123345 0% 4.73MB/s 1:05:31
94
+ # 4538368 100% 136.61kB/s 0:00:32 (xfr#554, to-chk=0/557)
95
+ percent = 0
96
+ delta = None
97
+ s = line.lstrip()
98
+ if s and s[0].isdigit() and '%' in line:
99
+ try:
100
+ ndone = ntotal = None
101
+ if m := re.search(r'\(xfr#(\d+), to-chk=(\d+)/(\d+)\)', line):
102
+ ndone = int(m.group(1))
103
+ ntotal = int(m.group(3))
104
+
105
+ parts = line.split()
106
+ if len(parts) < 4:
107
+ return
108
+ size, percent, rate, eta = parts[:4]
109
+
110
+ size = parse_bytes_token(size)
111
+ percent = int(percent.replace('%', ''))
112
+ self.rate = dehumanize_rate(rate)
113
+ except Exception:
114
+ # Don't crash the whole transfer due to an unexpected rsync progress format.
115
+ return
116
+
117
+ if percent < 10 and ntotal:
118
+ # within 10% - use number of files to estimate progress
119
+ size_percent = 100 * ndone / ntotal
120
+ else:
121
+ size_percent = percent
122
+
123
+ if size_percent > 0:
124
+ self.percent = percent
125
+ delta = size - self.size
126
+ else:
127
+ percent = total = 0
128
+
129
+ self.size = size
130
+ # Prefer byte-accurate total computed from itemize stage.
131
+ if self.total_size:
132
+ total = self.total_size
133
+ self.total = total
134
+ elif size_percent > 0:
135
+ total = int(size * 100 / size_percent)
136
+ else:
137
+ total = self.total
138
+
139
+ # print(
140
+ # f'({self.id}) {line} total={total} size={size} '
141
+ # f'percent={percent}%({size_percent:4.2f}%) '
142
+ # f'delta={delta} scan={ndone}/{ntotal}'
143
+ # )
144
+
145
+ self.progress.update(
146
+ self.task,
147
+ total=total,
148
+ completed=size,
149
+ rate=self.rate,
150
+ eta=elapsed_time(total, size, self.rate),
151
+ )
152
+
153
+ # Update progress on current file
154
+ self.callback(delta, self)
155
+ else:
156
+ self.file = line
157
+ self.progress.console.print(
158
+ f"[color({self.color})]{line}",
159
+ highlight=False,
160
+ )
161
+ self.progress.update(self.task, filename=self.file)
162
+
163
+ def process_error(self, err):
164
+ self.error_buf += err
165
+
166
+ errors = self.error_buf.split('\n')
167
+ self.error_buf = errors.pop() # last part - not finished line, keep it
168
+
169
+ for e in errors:
170
+ self.progress.console.print(f"[red][bold]{self.id}[/bold][/red] Error: {e}")
171
+
172
+ async def transfer(self):
173
+ if not self.files:
174
+ self.progress.console.print(
175
+ f"[bright_red]Job {self.id}: Nothing to do - no files",
176
+ highlight=False,
177
+ )
178
+ return
179
+
180
+ try:
181
+ await self.rsync.transfer(
182
+ self.files,
183
+ progress_callback=self.process_progress,
184
+ error_callback=self.process_error,
185
+ )
186
+
187
+ self.progress.update(self.task, filename='done', rate=None, eta='')
188
+
189
+ except Exception as e:
190
+ self.progress.update(
191
+ self.task,
192
+ filename=f'rsync error: {e}',
193
+ rate=None,
194
+ eta='-failed-',
195
+ )
196
+ raise
jsync/jsync.py ADDED
@@ -0,0 +1,82 @@
1
+ import asyncio
2
+ import sys
3
+ import traceback
4
+
5
+ from .rsync import RSync
6
+ from .syncer import Syncer
7
+
8
+
9
+ def usage(e=''):
10
+ print(
11
+ f"""{e}
12
+
13
+ USAGE:
14
+
15
+ --job=<num-jobs> -j<n> - Parallelize rsync run in number of jobs
16
+ --debug - Print raw rsync output lines as seen by jsync (or set JSYNC_DEBUG=1)
17
+ ... rsync options ...
18
+
19
+ """,
20
+ file=sys.stderr,
21
+ )
22
+ sys.exit(1)
23
+
24
+
25
+ async def main(argv):
26
+ jobs_num = 6
27
+ verbose = False
28
+ debug = False
29
+
30
+ try:
31
+ cut = None
32
+ for i in range(len(argv)):
33
+ a = argv[i]
34
+ if a == '-j' or a == '--jobs':
35
+ jobs_num = int(argv[i + 1])
36
+ cut = (i, i + 2)
37
+ break
38
+ elif a.startswith('-j'):
39
+ jobs_num = int(argv[i][2:])
40
+ cut = (i, i + 1)
41
+ elif a.startswith('--jobs='):
42
+ jobs_num = int(argv[i][7:])
43
+ cut = (i, i + 1)
44
+ elif a == '--help' or a == '-h':
45
+ usage()
46
+ elif a == '--debug':
47
+ debug = True
48
+ cut = (i, i + 1)
49
+ break
50
+
51
+ if len(a) > 1 and a[0] == '-' and a[1] != '-' and 'v' in a:
52
+ verbose = True
53
+
54
+ if cut:
55
+ argv = argv[0 : cut[0]] + argv[cut[1] :]
56
+
57
+ if len(argv) < 2:
58
+ raise Exception("Not enough rsync options provided")
59
+
60
+ except Exception as e:
61
+ usage(e)
62
+
63
+ try:
64
+ with Syncer(jobs_num, RSync(*argv, debug=debug)) as s:
65
+ await s.itemize()
66
+ await s.transfer()
67
+
68
+ except Exception as e:
69
+ print(f'Error: {e}', file=sys.stderr)
70
+ if verbose:
71
+ print(*traceback.format_exception(e), file=sys.stderr)
72
+
73
+
74
+ def synchronize(*argv):
75
+ try:
76
+ asyncio.run(main(argv or sys.argv[1:]))
77
+ except KeyboardInterrupt:
78
+ print("Interrupted", file=sys.stderr)
79
+
80
+
81
+ if __name__ == '__main__':
82
+ synchronize()
jsync/rsync.py ADDED
@@ -0,0 +1,265 @@
1
+ """Python class to wrap running of rsync binary in asynchroneous way"""
2
+
3
+ import asyncio
4
+ import os
5
+ import re
6
+ import sys
7
+ from dataclasses import dataclass
8
+
9
+ from .utils import parse_bytes_token
10
+
11
+
12
+ @dataclass
13
+ class FileInfo:
14
+ """Information about a file to be synced"""
15
+ filename: str
16
+ attrs: str
17
+ size: int
18
+ index: int = 0
19
+ is_dir: bool = False
20
+
21
+
22
+ class RSync:
23
+ rsync_cmd = 'rsync'
24
+ args_transfer = [
25
+ '--files-from=-',
26
+ '--dirs', # Process directories, but don't recurse into them from --files-from
27
+ '--info=progress2',
28
+ '--no-verbose',
29
+ '--no-human-readable',
30
+ '-v',
31
+ ]
32
+
33
+ args_itemize = [
34
+ '--dry-run',
35
+ '--itemize-changes',
36
+ '--out-format=%i %l %n',
37
+ '--no-verbose',
38
+ '--no-human-readable',
39
+ '--info=progress2',
40
+ ]
41
+
42
+ def __init__(self, *args, debug: bool = False) -> None:
43
+ # Force byte-only output regardless of user's shorthand flags.
44
+ # `-h/--human-readable` affects both progress and `%l` formatting.
45
+ human_flags = {'-h', '--human-readable', '--humanreadable'}
46
+ self.debug = debug or os.environ.get("JSYNC_DEBUG", "") not in ("", "0", "false", "False")
47
+ self.opts = [a for a in args if a and a[0] == '-' and a not in human_flags]
48
+ self.args = list(filter(lambda x: x[0] != '-', args))
49
+ self.args_transfer = self.opts + RSync.args_transfer
50
+ self.args_itemize = self.opts + RSync.args_itemize
51
+
52
+ def sources(self):
53
+ """all source aguments"""
54
+ return self.args[0:-1]
55
+
56
+ def destination(self):
57
+ """destination argiment"""
58
+ return self.args[-1]
59
+
60
+ def source(self):
61
+ """common source argument"""
62
+ ret = []
63
+ srcs = self.sources()
64
+ for i in range(0, len(srcs[0].split('/'))):
65
+ p = srcs[0].split('/')[i]
66
+ for s in srcs[1:]:
67
+ if p != s.split('/')[i]:
68
+ return '/'.join(ret[0:-1])
69
+
70
+ ret.append(p)
71
+
72
+ if len(ret) > 1:
73
+ return '/'.join(ret[0:-1])
74
+
75
+ return '.'
76
+
77
+ def get_readlinecr(self):
78
+ async def readlinecr(self):
79
+ """overrides StreamReader.readline to make \r delimiter"""
80
+ sep = b'\r'
81
+ seplen = len(sep)
82
+ try:
83
+ line = await self.readuntil(sep)
84
+ except asyncio.exceptions.IncompleteReadError as e:
85
+ return e.partial
86
+ except asyncio.exceptions.LimitOverrunError as e:
87
+ if self._buffer.startswith(sep, e.consumed):
88
+ del self._buffer[: e.consumed + seplen]
89
+ else:
90
+ self._buffer.clear()
91
+ self._maybe_resume_transport()
92
+ raise ValueError(e.args[0]) from e
93
+ return line
94
+
95
+ return readlinecr
96
+
97
+ def _skip_info_line(self, line: str) -> bool:
98
+ if line in (
99
+ "sending incremental file list",
100
+ "building file list ... done",
101
+ "receiving file list ... done",
102
+ ) or line.startswith("created directory "):
103
+ return True
104
+ if re.match(r"sent \S+ bytes received \S+ bytes \S+ bytes/sec", line):
105
+ return True
106
+ if re.match(r"total size is \S+ speedup is \S+", line):
107
+ return True
108
+ return False
109
+
110
+ def _looks_like_progress(self, line: str) -> bool:
111
+ s = line.lstrip()
112
+ return bool(s and s[0].isdigit() and "%" in line)
113
+
114
+ async def _read_stream_lines(self, stream, on_line, debug_prefix: str):
115
+ buf = ""
116
+ while chunk := await stream.read(n=4096):
117
+ text = chunk.decode(errors="replace")
118
+ buf += text
119
+ parts = re.split(r"[\r\n]+", buf)
120
+ buf = parts.pop() # last part might be incomplete
121
+ for line in parts:
122
+ if not line or self._skip_info_line(line):
123
+ continue
124
+ if self.debug:
125
+ print(f"[jsync-debug] {debug_prefix}: {line!r}", file=sys.stderr)
126
+ on_line(line)
127
+
128
+ if buf and not self._skip_info_line(buf):
129
+ if self.debug:
130
+ print(f"[jsync-debug] {debug_prefix}: {buf!r}", file=sys.stderr)
131
+ on_line(buf)
132
+
133
+ def itemize_command(self):
134
+ return [self.rsync_cmd] + self.args + self.args_itemize
135
+
136
+ async def read_listing(self, proc, files, callback):
137
+ while buf := await proc.stdout.readline():
138
+ for line in re.split(r'[\r\n]+', buf.decode()):
139
+ if line:
140
+ cdir = 'created directory '
141
+ if line[0] == ' ':
142
+ callback(line)
143
+ elif line.startswith(cdir):
144
+ callback(line)
145
+ else:
146
+ # Format: %i %l %n -> ">f++++++++++ 259678 filename"
147
+ # First 12 chars are attributes, then size, then filename
148
+ attr = line[:12]
149
+ rest = line[13:].strip()
150
+
151
+ # Check if this is a directory (attributes start with 'd' or 'cd')
152
+ is_dir = attr[0] == 'd' or attr.startswith('cd')
153
+
154
+ # Parse size and filename
155
+ # Split by space, first part is size, rest is filename
156
+ parts = rest.split(None, 1)
157
+ if len(parts) >= 2:
158
+ size_str, filename = parts[0], parts[1]
159
+ try:
160
+ size = parse_bytes_token(size_str)
161
+ except Exception:
162
+ size = 0
163
+ else:
164
+ # Fallback for old format (no size)
165
+ filename = rest
166
+ size = 0
167
+
168
+ # cut trailing slash
169
+ # (due to different meaning in rsync files-from)
170
+ if filename[-1] == '/':
171
+ filename = filename[0:-1]
172
+
173
+ # Use current length of files list as index to preserve original order
174
+ index = len(files)
175
+ files.append(
176
+ FileInfo(
177
+ filename=filename,
178
+ attrs=attr,
179
+ size=size,
180
+ index=index,
181
+ is_dir=is_dir,
182
+ )
183
+ )
184
+
185
+ proc._transport.get_pipe_transport(1).close()
186
+
187
+ async def itemize(self, progress_callback, error_callback):
188
+ proc = await asyncio.create_subprocess_exec(
189
+ *self.itemize_command(),
190
+ stdout=asyncio.subprocess.PIPE,
191
+ stderr=asyncio.subprocess.PIPE,
192
+ )
193
+
194
+ def stderr_dispatch(line: str):
195
+ if self._looks_like_progress(line):
196
+ progress_callback(line)
197
+ else:
198
+ error_callback(line)
199
+
200
+ files = []
201
+ await asyncio.gather(
202
+ self.read_listing(proc, files, progress_callback),
203
+ self._read_stream_lines(proc.stderr, stderr_dispatch, "stderr"),
204
+ )
205
+
206
+ await proc.wait()
207
+
208
+ if proc.returncode != 0:
209
+ raise Exception(
210
+ f'Error collecting list of files for synchronization: rc={proc.returncode}'
211
+ )
212
+
213
+ return files
214
+
215
+ async def feed_input(self, proc, files):
216
+ for f in files:
217
+ proc.stdin.write((f.filename + '\n').encode('utf-8'))
218
+ await proc.stdin.drain()
219
+
220
+ proc.stdin.close()
221
+
222
+ async def read_progress(self, proc, callback):
223
+ await self._read_stream_lines(proc.stdout, callback, "stdout")
224
+ proc._transport.get_pipe_transport(1).close()
225
+
226
+ async def read_errors(self, proc, callback):
227
+ def dispatch(line: str):
228
+ # Many rsync builds print progress to stderr; route those to progress callback
229
+ # in transfer() (this method is still used in itemize()).
230
+ callback(line)
231
+
232
+ await self._read_stream_lines(proc.stderr, dispatch, "stderr")
233
+ proc._transport.get_pipe_transport(2).close()
234
+
235
+ def transfer_command(self):
236
+ return [self.rsync_cmd] + self.args_transfer + [self.source(), self.destination()]
237
+
238
+ async def transfer(self, files, progress_callback, error_callback):
239
+ proc = await asyncio.create_subprocess_exec(
240
+ *self.transfer_command(),
241
+ stdin=asyncio.subprocess.PIPE,
242
+ stdout=asyncio.subprocess.PIPE,
243
+ stderr=asyncio.subprocess.PIPE,
244
+ )
245
+
246
+ def stderr_dispatch(line: str):
247
+ if self._looks_like_progress(line):
248
+ progress_callback(line)
249
+ else:
250
+ error_callback(line)
251
+
252
+ await asyncio.gather(
253
+ self.feed_input(proc, files),
254
+ self.read_progress(proc, progress_callback),
255
+ self._read_stream_lines(proc.stderr, stderr_dispatch, "stderr"),
256
+ )
257
+
258
+ await proc.wait()
259
+
260
+ if proc.returncode > 0:
261
+ print(f'rsync processes exited with rc={proc.returncode}')
262
+ raise Exception(f'Error running rsync: rc={proc.returncode}')
263
+ elif proc.returncode < 0:
264
+ print(f'rsync processes exited due to signal {-proc.returncode}')
265
+ raise Exception(f'Error running rsync: signal {-proc.returncode}')
jsync/syncer.py ADDED
@@ -0,0 +1,210 @@
1
+ import asyncio
2
+ import re
3
+ from types import TracebackType
4
+
5
+ from humanize import naturalsize
6
+ from rich.console import Console
7
+ from rich.progress import (
8
+ BarColumn,
9
+ Progress,
10
+ SpinnerColumn,
11
+ TaskID,
12
+ TaskProgressColumn,
13
+ )
14
+
15
+ from .columns import FlexiColumn
16
+ from .job import Job
17
+ from .rsync import RSync
18
+ from .utils import elapsed_time, transfer_rate
19
+
20
+
21
+ class Syncer:
22
+ jobs: list[Job]
23
+ njobs: int
24
+ total: int
25
+ progress: Progress | None
26
+ master: TaskID
27
+ rsync: RSync
28
+
29
+ def __init__(self, njobs, rsync=None) -> None:
30
+ self.rsync = rsync or RSync()
31
+ self.total = 0
32
+
33
+ self.jobs = []
34
+ self.njobs = njobs
35
+ self.console = Console()
36
+ self.progress = None
37
+
38
+ def init_progress(self):
39
+ def sz(size):
40
+ return naturalsize(size, gnu=True)
41
+
42
+ self.progress = Progress(
43
+ "{task.description}",
44
+ SpinnerColumn(),
45
+ BarColumn(),
46
+ TaskProgressColumn(text_format='[bright_magenta]{task.percentage:>3.0f}%'),
47
+ FlexiColumn(
48
+ lambda t: f'{sz(t.completed):>8} / {sz(t.total):<8}',
49
+ style="progress.download",
50
+ ),
51
+ FlexiColumn(lambda t: f'{t.fields["eta"]:>10}', style='cyan'),
52
+ FlexiColumn(lambda t: f'{transfer_rate(t.fields["rate"]):>12}', style='bright_green'),
53
+ FlexiColumn(lambda t: f' {t.fields["style"]}{t.fields["filename"]:<64}'),
54
+ )
55
+
56
+ self.master = self.progress.add_task(
57
+ "total",
58
+ rate=0,
59
+ filename='',
60
+ percent='',
61
+ style='',
62
+ eta='',
63
+ )
64
+
65
+ self.progress.start()
66
+
67
+ def process_progress(self, advance, job):
68
+ if not self.progress:
69
+ self.init_progress()
70
+
71
+ rate = sum([j.rate for j in self.jobs])
72
+ size = sum([j.size for j in self.jobs])
73
+ total = sum([j.total_size or j.total for j in self.jobs])
74
+
75
+ self.progress.update(
76
+ self.master,
77
+ rate=rate,
78
+ total=total,
79
+ completed=size,
80
+ eta=elapsed_time(total, size, rate),
81
+ )
82
+
83
+ def process_itemize_progress(self, line):
84
+ if not self.progress:
85
+ self.init_progress()
86
+
87
+ if '%' in line:
88
+ ndone = ntotal = None
89
+ if m := re.search(r'\(xfr#(\d+), ir-chk=(\d+)/(\d+)\)', line):
90
+ size, percent, rate, eta, _, rest = line.split(None, 6)
91
+ ndone = int(m.group(1))
92
+ ntotal = int(m.group(3))
93
+ else:
94
+ return
95
+
96
+ task = self.progress._tasks[self.master]
97
+ if task.total != ntotal:
98
+ self.progress.update(self.master, total=ntotal, completed=ndone)
99
+ else:
100
+ self.progress.advance(self.master, advance=(ndone - task.completed))
101
+
102
+ def process_itemize_error(self, err):
103
+ if not self.progress:
104
+ self.init_progress()
105
+
106
+ self.progress.console.print(f"[red][bold]Error[/bold][/red]: {err}")
107
+
108
+ async def itemize(self):
109
+ cmd = ' '.join(self.rsync.itemize_command())
110
+ self.console.print("Calculating list of files for synchronization")
111
+ self.console.print(
112
+ f"[bright_cyan]Executing:[/bright_cyan] {cmd}",
113
+ highlight=False,
114
+ )
115
+
116
+ files = await self.rsync.itemize(
117
+ progress_callback=self.process_itemize_progress,
118
+ error_callback=self.process_itemize_error,
119
+ )
120
+
121
+ if not files:
122
+ raise Exception('Nothing to do - no files to sync')
123
+
124
+ if not self.progress:
125
+ self.init_progress()
126
+
127
+ # Distribute files by size to balance workload across jobs
128
+ self.progress.update(self.master, total=len(files))
129
+
130
+ # Initialize job lists and their current sizes
131
+ job_files = [[] for _ in range(self.njobs)]
132
+ job_sizes = [0] * self.njobs
133
+
134
+ # Sort files by size (descending) for better load balancing
135
+ # This is the "First Fit Decreasing" (FFD) / "Longest Processing Time" (LPT) algorithm
136
+ # It ensures large files are distributed first, leading to more balanced distribution
137
+ sorted_files = sorted(files, key=lambda f: f.size, reverse=True)
138
+
139
+ # Distribute files to jobs using greedy algorithm on sorted list
140
+ # Assign each file to the job with smallest current size
141
+ for file in sorted_files:
142
+ # Find job with smallest current size
143
+ min_job_idx = min(range(self.njobs), key=lambda i: job_sizes[i])
144
+
145
+ # Assign file to this job
146
+ job_files[min_job_idx].append(file)
147
+ job_sizes[min_job_idx] += file.size
148
+
149
+ # Restore original order within each job
150
+ for i in range(self.njobs):
151
+ job_files[i].sort(key=lambda f: f.index)
152
+
153
+ # Create jobs with distributed files
154
+ for i in range(self.njobs):
155
+ self.jobs.append(
156
+ Job(
157
+ i + 1,
158
+ job_files[i],
159
+ progress=self.progress,
160
+ rsync=self.rsync,
161
+ callback=self.process_progress,
162
+ total_size=job_sizes[i],
163
+ )
164
+ )
165
+
166
+ def start(self):
167
+ if not self.progress:
168
+ self.init_progress()
169
+
170
+ self.progress.start()
171
+
172
+ def __enter__(self):
173
+ return self
174
+
175
+ def __exit__(
176
+ self,
177
+ exc_type: type[BaseException] | None,
178
+ exc_val: BaseException | None,
179
+ exc_tb: TracebackType | None,
180
+ ):
181
+ if self.progress:
182
+ self.progress.stop()
183
+
184
+ def active(self):
185
+ return any(j.active() for j in self.jobs)
186
+
187
+ async def transfer(self):
188
+ if not self.progress:
189
+ self.init_progress()
190
+
191
+ self.progress.start_task(self.master)
192
+
193
+ for j in self.jobs:
194
+ j.start()
195
+
196
+ result = await asyncio.gather(
197
+ *[job.transfer() for job in self.jobs], return_exceptions=True
198
+ )
199
+
200
+ nerrors = 0
201
+ for r, j in zip(result, self.jobs, strict=True):
202
+ if isinstance(r, Exception):
203
+ nerrors += 1
204
+ self.progress.console.print(
205
+ f'[bright_red][bold]Job #{j.id} Error: {r}[/bold][/bright_red]\n',
206
+ j.error_buf,
207
+ )
208
+
209
+ if nerrors:
210
+ raise Exception(f'{nerrors} rsyncs failed')
jsync/utils.py ADDED
@@ -0,0 +1,70 @@
1
+ import re
2
+
3
+ from humanize import naturalsize
4
+
5
+
6
+ def parse_bytes_token(token: str) -> int:
7
+ """
8
+ Parse rsync byte counters that may include commas and an optional trailing 'B'.
9
+
10
+ Examples:
11
+ - "575" -> 575
12
+ - "575B" -> 575
13
+ - "123,456" -> 123456
14
+ - "123,456B" -> 123456
15
+ """
16
+ s = token.strip().replace(',', '')
17
+ if s.endswith('B') and s[:-1].isdigit():
18
+ s = s[:-1]
19
+ return int(s)
20
+
21
+
22
+ def dehumanize_rate(ssize):
23
+ """Converts rate string to number (like 231.89MB/s) of bytes per second"""
24
+
25
+ s = ssize.strip().replace(',', '')
26
+ if not s:
27
+ return 0
28
+
29
+ # Some rsync builds may emit a plain number for the rate when human-readable is off.
30
+ if s.replace('.', '', 1).isdigit():
31
+ return float(s)
32
+
33
+ # Also accept "12345 bytes/sec"
34
+ if m := re.match(r'^([\d\.]+)\s*bytes/sec$', s, flags=re.IGNORECASE):
35
+ return float(m.group(1))
36
+
37
+ m = re.match(r'^([\d\.]+)\s*([BKMGTPEZY]?)\s*B/s+$', s, flags=re.IGNORECASE)
38
+
39
+ if not m:
40
+ raise Exception(f'Wrong rate format {ssize}')
41
+
42
+ u = m.group(2)
43
+ ret = float(m.group(1))
44
+
45
+ if u != '':
46
+ for unit in "KMGTPEZY":
47
+ ret *= 1000
48
+ if unit == u.upper():
49
+ break
50
+
51
+ return ret
52
+
53
+
54
+ def elapsed_time(total, size, rate):
55
+ # Show ETA only when it can be computed meaningfully.
56
+ if not rate or total <= 0 or size <= 0 or size > total:
57
+ return ''
58
+
59
+ sec_remaining = int((total - size) / rate)
60
+ minutes, seconds = divmod(sec_remaining, 60)
61
+ hours, minutes = divmod(minutes, 60)
62
+ return f"{hours:3d}:{minutes:02d}:{seconds:02d}"
63
+
64
+
65
+ def transfer_rate(size):
66
+ if size is None:
67
+ return '-'
68
+
69
+ ret = naturalsize(size, gnu=True)
70
+ return ret + ("/s" if ret[-1].lower() == 'b' else "B/s")
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.5
2
+ Name: py-jsync
3
+ Version: 0.2.31
4
+ Summary: Tool to run rsync utility in parallel
5
+ Author-email: Vladimir Grebenshchikov <vova@zote.me>
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: humanize<5,>=4.9
9
+ Requires-Dist: rich<15,>=14.0
10
+ Provides-Extra: dev
11
+ Requires-Dist: ruff>=0.9.9; extra == 'dev'
12
+ Description-Content-Type: text/markdown
13
+
14
+ # JSync - Parallel Rsync Tool
15
+
16
+ The Parallel Rsync Tool is a powerful utility designed to significantly enhance the performance of synchronizing large file trees between remote hosts using the popular rsync tool. By harnessing parallel execution and leveraging multiple TCP streams, this tool offers substantial improvements in speed and efficiency compared to traditional rsync operations.
17
+
18
+ ## Features
19
+
20
+ ### Parallel Execution
21
+
22
+ The tool splits the file synchronization process into multiple parts and runs multiple rsync processes concurrently, maximizing resource utilization and reducing overall synchronization time.
23
+
24
+ ### Optimized for Large File Trees
25
+
26
+ Whether dealing with massive file repositories or extensive directory structures, the tool efficiently handles synchronization tasks of any scale.
27
+
28
+ ### Multiple TCP Streams
29
+
30
+ By utilizing multiple TCP streams for remote transfer, the tool maximizes network bandwidth usage over multipath networks, further enhancing synchronization speed and performance.
31
+
32
+ ### Progress Reporting
33
+
34
+ Detailed progress reports provide real-time visibility into the synchronization process, allowing users to monitor the status of each file transfer and overall progress.
35
+
36
+ ## How It Works
37
+
38
+ ### FileList Calculation
39
+
40
+ The tool first calculates the list of files to be synchronized between the remote hosts, ensuring accuracy and completeness.
41
+ It does it running rsync in dry run (-n) mode and gathering output.
42
+
43
+ ## Partitioning
44
+
45
+ The file list is partitioned into equal chunks, optimizing the workload distribution for parallel execution.
46
+
47
+ ## Parallel Rsync Execution
48
+
49
+ Multiple rsync processes are initiated simultaneously, each tasked with synchronizing a specific partition of the file list.
50
+ Orchestration: The tool orchestrates the execution of rsync processes, ensuring proper synchronization sequence and resource management.
51
+ Progress Reporting: Throughout the synchronization process, detailed progress reports are generated and displayed, keeping users informed about the status of individual transfers and overall progress.
52
+ Getting Started
53
+
54
+ ### Installation
55
+
56
+ Clone the repository, build and install package
57
+
58
+ ```shell
59
+ git clone https://github.com/vgrebenschikov/fsync.git
60
+ $ cd fsync
61
+ $ uv venv
62
+ $ uv sync
63
+ ```
64
+
65
+ Install from PyPI:
66
+
67
+ ```shell
68
+ $ uv pip install py-jsync
69
+ ```
70
+
71
+ For development (linting, etc):
72
+
73
+ ```shell
74
+ $ uv sync --extra dev
75
+ $ uv run ruff check .
76
+ ```
77
+
78
+ Alternative (without using `uv.lock`):
79
+
80
+ ```shell
81
+ $ uv pip install -e ".[dev]"
82
+ $ uv run ruff check .
83
+ ```
84
+
85
+ ### Execute the tool
86
+
87
+ ```shell
88
+ $ jsync --help
89
+ ... to get help ...
90
+
91
+ $ jsync -j 8 <rsync-options>
92
+ ... to execute rsync in 8 jobs parallel
93
+ ```
94
+
95
+ Monitor the progress using total progress-bar and rsync progress-bar to track the synchronization process in real-time.
96
+
97
+ ## Contributions and Support
98
+
99
+ Contributions to the Parallel Rsync Tool are welcome!
100
+ Feel free to submit bug reports, feature requests, or pull requests via GitHub.
101
+
102
+ ## License
103
+
104
+ This project is licensed under the [MIT License](https://en.wikipedia.org/wiki/MIT_License).
@@ -0,0 +1,12 @@
1
+ jsync/__init__.py,sha256=ycrj5bJotuXmf3tkZYyQJg9URfft1wUewuM6gOOznLo,543
2
+ jsync/columns.py,sha256=TbAol4YG3WXnhqjgLhj-l32-iEwheJ_vdUAv5P7xQdM,1042
3
+ jsync/job.py,sha256=zf38Y5RGXGj93c910Hi_BXCPKtn4mIVsv7MqFlRAY0U,5994
4
+ jsync/jsync.py,sha256=XbrtLm84pgN6wVAxAc1HFykYsYdNqSgidLfkJyHfYeg,1927
5
+ jsync/rsync.py,sha256=ex1qhjAiRfHWV3Oa_wz8JCnwJQeI2YMbW0OESQ41XP4,9474
6
+ jsync/syncer.py,sha256=0W_MvsSHw11p0z5lZpy_pNbexIxZfVQXdz9DSy52X9Q,6409
7
+ jsync/utils.py,sha256=IKeLE9vN6ihJz4zF_OG7H8XPohvT-PqSK56Xdek-9Zo,1771
8
+ py_jsync-0.2.31.dist-info/METADATA,sha256=OvZZH3d-AGJ449QHBPSe1nz4-LMn75s-FT5pPaw9bco,3400
9
+ py_jsync-0.2.31.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ py_jsync-0.2.31.dist-info/entry_points.txt,sha256=--10De1ZxWeRjFW6AuhUuotgSzZSjEppmj6tUjdS56E,44
11
+ py_jsync-0.2.31.dist-info/licenses/LICENSE,sha256=mhIEMZHMe04DMd4mVYz3BiErMB83dV8-JbvQDAjxVpw,1071
12
+ py_jsync-0.2.31.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ jsync = jsync:synchronize
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 vgrebenschikov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.