File size: 8,407 Bytes
fab5954
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#!/usr/bin/env python3
"""Multi-connection HTTP Range download with resume (sidecar progress file)."""
from __future__ import annotations

import json
import os
import sys
import threading
import time
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed

URL = os.environ.get(
    "DL_URL",
    "https://data.bris.ac.uk/datasets/tar/2v6cgv1x04ol22qp9rm9x2j6a7.zip",
)
DEST = os.environ.get(
    "DL_DEST",
    os.path.join(os.path.dirname(os.path.abspath(__file__)), "2v6cgv1x04ol22qp9rm9x2j6a7.zip"),
)
WORKERS = int(os.environ.get("DL_WORKERS", "16"))
CHUNK = int(os.environ.get("DL_CHUNK", str(32 * 1024 * 1024)))
PROGRESS_PATH = DEST + ".progress.json"
LOCK_PATH = DEST + ".lock"

print_lock = threading.Lock()
progress_lock = threading.Lock()
bytes_lock = threading.Lock()
session_bytes = 0


def log(msg: str) -> None:
    with print_lock:
        print(msg, flush=True)


def head_length(url: str) -> int:
    req = urllib.request.Request(url, method="HEAD")
    with urllib.request.urlopen(req, timeout=60) as resp:
        length = resp.headers.get("Content-Length")
        accept = resp.headers.get("Accept-Ranges", "")
        if "bytes" not in accept.lower():
            log(f"WARN Accept-Ranges={accept!r}")
        if not length:
            raise SystemExit("no Content-Length")
        return int(length)


def load_progress(total: int, dest_size: int) -> list[list[int]]:
    if os.path.exists(PROGRESS_PATH):
        with open(PROGRESS_PATH) as f:
            data = json.load(f)
        if data.get("url") == URL and data.get("total") == total:
            return merge_intervals(data.get("completed") or [])
    if 0 < dest_size < total:
        return [[0, dest_size]]
    return []


def save_progress(total: int, completed: list[list[int]]) -> None:
    tmp = PROGRESS_PATH + ".tmp"
    payload = {"url": URL, "total": total, "completed": merge_intervals(completed)}
    with open(tmp, "w") as f:
        json.dump(payload, f)
    os.replace(tmp, PROGRESS_PATH)


def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
    if not intervals:
        return []
    items = sorted((int(a), int(b)) for a, b in intervals if b > a)
    out = [list(items[0])]
    for a, b in items[1:]:
        if a <= out[-1][1]:
            out[-1][1] = max(out[-1][1], b)
        else:
            out.append([a, b])
    return out


def gaps(total: int, completed: list[list[int]]) -> list[tuple[int, int]]:
    done = merge_intervals(completed)
    pos = 0
    missing: list[tuple[int, int]] = []
    for a, b in done:
        if pos < a:
            missing.append((pos, a))
        pos = max(pos, b)
    if pos < total:
        missing.append((pos, total))
    return missing


def split_gaps(missing: list[tuple[int, int]], chunk: int) -> list[tuple[int, int]]:
    tasks = []
    for a, b in missing:
        s = a
        while s < b:
            e = min(s + chunk, b)
            tasks.append((s, e))
            s = e
    return tasks


def fetch_range(url: str, start: int, end: int, fd: int, retries: int = 8) -> int:
    """Download [start, end) into fd. Returns bytes written."""
    last_err: Exception | None = None
    for attempt in range(retries):
        written = 0
        offset = start
        try:
            req = urllib.request.Request(
                url,
                headers={
                    "Range": f"bytes={start}-{end - 1}",
                    "User-Agent": "parallel-resume-get/1.0",
                },
            )
            with urllib.request.urlopen(req, timeout=120) as resp:
                if resp.status not in (200, 206):
                    raise RuntimeError(f"HTTP {resp.status}")
                while offset < end:
                    want = min(1024 * 1024, end - offset)
                    buf = resp.read(want)
                    if not buf:
                        raise RuntimeError(f"short read at {offset}")
                    os.pwrite(fd, buf, offset)
                    n = len(buf)
                    offset += n
                    written += n
                    with bytes_lock:
                        global session_bytes
                        session_bytes += n
            if offset != end:
                raise RuntimeError(f"incomplete {offset} != {end}")
            return written
        except (urllib.error.URLError, TimeoutError, OSError, RuntimeError) as exc:
            last_err = exc
            time.sleep(min(2 ** attempt, 30))
    raise RuntimeError(f"range {start}-{end} failed: {last_err}")


def main() -> int:
    if os.path.exists(LOCK_PATH):
        try:
            with open(LOCK_PATH) as f:
                old = int(f.read().strip() or "0")
            os.kill(old, 0)
            log(f"another downloader is running (pid {old})")
            return 1
        except (OSError, ValueError):
            pass
    with open(LOCK_PATH, "w") as f:
        f.write(str(os.getpid()))

    try:
        total = head_length(URL)
        dest_size = os.path.getsize(DEST) if os.path.exists(DEST) else 0
        completed = load_progress(total, dest_size)
        log(f"url={URL}")
        log(f"dest={DEST}")
        log(f"total={total} ({total / 1024**3:.2f} GiB) workers={WORKERS} chunk={CHUNK}")
        log(f"already={sum(b - a for a, b in completed)} bytes in {len(completed)} interval(s)")

        flags = os.O_RDWR | os.O_CREAT
        fd = os.open(DEST, flags, 0o644)
        try:
            if dest_size != total:
                os.ftruncate(fd, total)
            tasks = split_gaps(gaps(total, completed), CHUNK)
            if not tasks:
                log("nothing to download")
                return 0
            log(f"tasks={len(tasks)} remaining={sum(e - s for s, e in tasks)}")
            t0 = time.time()
            done_tasks = 0

            def worker(se: tuple[int, int]) -> tuple[int, int]:
                s, e = se
                fetch_range(URL, s, e, fd)
                with progress_lock:
                    completed.append([s, e])
                    save_progress(total, completed)
                return s, e

            with ThreadPoolExecutor(max_workers=WORKERS) as pool:
                futs = [pool.submit(worker, se) for se in tasks]
                last_report = t0
                last_bytes = 0
                pending = set(futs)
                while pending:
                    finished = []
                    for fut in list(pending):
                        if fut.done():
                            finished.append(fut)
                            pending.remove(fut)
                    for fut in finished:
                        fut.result()
                        done_tasks += 1
                    now = time.time()
                    if now - last_report >= 5 or not pending:
                        with bytes_lock:
                            cur = session_bytes
                        dt = now - last_report
                        inst = (cur - last_bytes) / dt if dt > 0 else 0
                        avg = cur / (now - t0) if now > t0 else 0
                        remain = sum(e - s for s, e in tasks) - cur
                        eta = remain / inst if inst > 0 else float("inf")
                        log(
                            f"chunks {done_tasks}/{len(tasks)}  "
                            f"+{cur / 1024**3:.2f} GiB this run  "
                            f"{inst / 1024**2:.2f} MiB/s inst  "
                            f"{avg / 1024**2:.2f} MiB/s avg  "
                            f"eta {eta / 60:.1f} min"
                        )
                        last_report = now
                        last_bytes = cur
                    if pending:
                        time.sleep(0.4)
        finally:
            os.close(fd)

        final = merge_intervals(completed)
        if gaps(total, final):
            log(f"INCOMPLETE gaps={gaps(total, final)[:5]}")
            return 1
        size = os.path.getsize(DEST)
        if size != total:
            log(f"size mismatch {size} != {total}")
            return 1
        log(f"DONE {DEST} size={size}")
        try:
            os.remove(PROGRESS_PATH)
        except OSError:
            pass
        return 0
    finally:
        try:
            os.remove(LOCK_PATH)
        except OSError:
            pass


if __name__ == "__main__":
    raise SystemExit(main())