chamesle-get (5960B)
1 #!/usr/bin/python3 2 # chamesle-get "APK ARGS" ...: apk commands, with the downloads done by curl first. 3 # apk's own downloader waits forever on a slow mirror; curl gives up on one and tries again. the files land in 4 # a local copy of the repo (the signed index and the packages it needs), then apk runs from that, offline. 5 # CHAMESLE_PROGRESS=FD gets "done/1000" lines for the whole thing: the package list and dry run are the first 3%, 6 # downloading up to 80%, installing the rest 7 # chamesle-get "fix --reinstall linux-firmware-amd" "upgrade" "add kde-plasma" 8 import os, re, shutil, subprocess, sys, threading, time 9 10 LOCAL = "/var/cache/chamesle-get" 11 DL = LOCAL + "/x86_64" 12 START = 30 13 DOWN = 800 14 15 fd = os.environ.get("CHAMESLE_PROGRESS") 16 out = os.fdopen(int(fd), "w", buffering=1) if fd else None 17 last = [-1] 18 19 20 def say(n): 21 n = max(0, min(1000, int(n))) 22 if out and n != last[0]: 23 last[0] = n 24 out.write("%d/1000\n" % n) 25 26 27 def repo(): 28 for line in open("/etc/apk/repositories"): 29 p = line.split() 30 if p and not line.startswith("#") and p[-1].startswith("http"): 31 return p[-1].rstrip("/") 32 sys.exit("chamesle-get: no http repo in /etc/apk/repositories") 33 34 35 def curl(url, path, size=0): 36 # under 300 KB/s for 8 s: that mirror crawls, drop it and go again where it left off. the redirect picks 37 # another one most times. the last tries take anything 38 for i in range(12): 39 slow = "300000" if i < 9 else "1000" 40 r = subprocess.run(["curl", "-fsSL", "-C", "-", "--connect-timeout", "15", "--speed-limit", slow, 41 "--speed-time", "8", "-o", path + ".part", url]) 42 if r.returncode == 0 and (not size or os.path.getsize(path + ".part") == size): 43 os.replace(path + ".part", path) 44 return True 45 if r.returncode == 33 or (size and os.path.exists(path + ".part") and os.path.getsize(path + ".part") > size): 46 os.remove(path + ".part") 47 time.sleep(2) 48 return False 49 50 51 def apk(args, progress=None): 52 cmd = ["apk", "--repositories-file", LOCAL + "/repositories", "--no-interactive"] + args 53 if progress is None: 54 return subprocess.run(cmd, capture_output=True, text=True) 55 r, w = os.pipe() 56 p = subprocess.Popen(cmd[:1] + ["--progress-fd", str(w)] + cmd[1:], pass_fds=(w,)) 57 os.close(w) 58 with os.fdopen(r) as f: 59 for line in f: 60 d, _, t = line.strip().partition("/") 61 if d.isdigit() and t.isdigit() and int(t): 62 progress(int(d) / int(t)) 63 return p.wait() 64 65 66 def sizes(): 67 # name-version -> file size, from the index 68 got, name, ver = {}, None, None 69 dump = subprocess.run(["apk", "adbdump", DL + "/Packages.adb"], capture_output=True, text=True).stdout 70 for line in dump.splitlines(): 71 if line.startswith(" - name: "): 72 name, ver = line[10:].strip(), None 73 elif line.startswith(" version: "): 74 ver = line[13:].strip() 75 elif line.startswith(" file-size: ") and name and ver: 76 got["%s-%s" % (name, ver)] = int(line[15:]) 77 return got 78 79 80 def main(): 81 steps = [s.split() for s in sys.argv[1:]] 82 if not steps: 83 sys.exit("usage: chamesle-get \"APK ARGS\" ...") 84 url = repo() 85 os.makedirs(DL, exist_ok=True) 86 with open(LOCAL + "/repositories", "w") as f: 87 f.write("v3 %s\n" % LOCAL) 88 say(0) 89 if not curl(url + "/x86_64/Packages.adb", DL + "/Packages.adb"): 90 sys.exit("chamesle-get: can't get the package list from %s" % url) 91 say(START / 2) 92 size = sizes() 93 94 # what apk would fetch, from a dry run of every step 95 want = {} 96 for s in steps: 97 r = apk(["--simulate"] + s) 98 if r.returncode: 99 sys.stderr.write(r.stdout + r.stderr) 100 sys.exit("chamesle-get: apk %s won't work" % " ".join(s)) 101 for line in r.stdout.splitlines(): 102 m = re.match(r"\(\s*\d+/\d+\) (Installing|Upgrading|Downgrading|Replacing|Reinstalling) (\S+) \((?:.* -> )?(\S+)\)", line) 103 if m: 104 pv = "%s-%s" % (m.group(2), m.group(3)) 105 want[pv] = size.get(pv, 0) 106 107 say(START) 108 total = sum(want.values()) or 1 109 done = {pv: n for pv, n in want.items() if os.path.exists("%s/%s.apk" % (DL, pv)) and os.path.getsize("%s/%s.apk" % (DL, pv)) == n} 110 todo = [pv for pv in want if pv not in done] 111 print("chamesle-get: %d packages, %d MB to download" % (len(want), sum(want[p] for p in todo) // 1048576), file=sys.stderr) 112 bad, lock = [], threading.Lock() 113 114 def worker(): 115 while True: 116 with lock: 117 if not todo: 118 return 119 pv = todo.pop(0) 120 if curl("%s/x86_64/%s.apk" % (url, pv), "%s/%s.apk" % (DL, pv), want[pv]): 121 with lock: 122 done[pv] = want[pv] 123 else: 124 with lock: 125 bad.append(pv) 126 threads = [threading.Thread(target=worker, daemon=True) for _ in range(6)] 127 for t in threads: 128 t.start() 129 while any(t.is_alive() for t in threads): 130 part = 0 131 for pv in want: 132 if pv not in done: 133 try: 134 part += os.path.getsize("%s/%s.apk.part" % (DL, pv)) 135 except OSError: 136 pass 137 with lock: 138 have = sum(done.values()) 139 say(START + (DOWN - START) * (have + part) / total) 140 time.sleep(0.5) 141 if bad: 142 sys.exit("chamesle-get: couldn't download %s" % ", ".join(bad)) 143 say(DOWN) 144 145 # now apk, offline, each step its share of the last 20% 146 share = (1000 - DOWN) / len(steps) 147 for i, s in enumerate(steps): 148 base = DOWN + i * share 149 if apk(s, lambda f, base=base: say(base + f * share)): 150 sys.exit("chamesle-get: apk %s failed" % " ".join(s)) 151 say(1000) 152 shutil.rmtree(LOCAL, ignore_errors=True) 153 154 155 if __name__ == "__main__": 156 main()