alongside.py (4691B)
1 # install next to windows: find it, shrink it, make a partition in the space freed up 2 import json 3 import os 4 import re 5 import subprocess 6 import time 7 8 GB = 1000 ** 3 9 MIB = 1024 * 1024 10 MIN_CHAMESLE = 20 * GB 11 # windows needs room to breathe after we take our share 12 WINDOWS_SPARE = 10 * GB 13 ESP_GUID = "c12a7328-f81f-11d2-ba4b-00a0c93ec93b" 14 MOUNT = "/tmp/alongside" 15 16 17 def run(cmd, input=None): 18 return subprocess.run(cmd, input=input, capture_output=True, text=True) 19 20 21 def lsblk(): 22 out = run(["lsblk", "-J", "-b", "-o", "NAME,PATH,FSTYPE,SIZE,TYPE,PKNAME,PTTYPE,PARTTYPE,PARTN,MOUNTPOINT"]).stdout 23 found = [] 24 25 def walk(devs): 26 for d in devs: 27 found.append(d) 28 walk(d.get("children", [])) 29 walk(json.loads(out)["blockdevices"]) 30 return found 31 32 33 def has_windows(path): 34 os.makedirs(MOUNT, exist_ok=True) 35 if run(["mount", "-o", "ro", path, MOUNT]).returncode != 0: 36 return False 37 try: 38 return os.path.isdir(os.path.join(MOUNT, "Windows", "System32")) 39 finally: 40 run(["umount", MOUNT]) 41 42 43 def min_size(path): 44 # the smallest ntfsresize says the filesystem can go, None if it can't be resized (hibernated, dirty...) 45 r = run(["ntfsresize", "--info", "--force", "--no-progress-bar", path]) 46 m = re.search(r"You might resize at (\d+) bytes", r.stdout) 47 return int(m.group(1)) if m else None 48 49 50 def find_windows(): 51 """the biggest ntfs partition with windows on it, as a dict, or None""" 52 devs = lsblk() 53 best = None 54 for d in devs: 55 if d.get("type") != "part" or d.get("fstype") != "ntfs" or d.get("mountpoint"): 56 continue 57 disk = "/dev/" + d["pkname"] 58 parts = [p for p in devs if p.get("pkname") == d["pkname"] and p.get("type") == "part"] 59 if d.get("pttype") == "dos" and len(parts) >= 4: 60 continue # no room for another primary partition 61 if not has_windows(d["path"]): 62 continue 63 smallest = min_size(d["path"]) 64 if smallest is None: 65 continue 66 size = int(d["size"]) 67 room = size - smallest - WINDOWS_SPARE 68 if room < MIN_CHAMESLE: 69 continue 70 if best is None or size > best["size"]: 71 best = {"path": d["path"], "disk": disk, "partn": int(d["partn"]), "name": d["name"], 72 "size": size, "min": smallest + WINDOWS_SPARE, "pttype": d.get("pttype")} 73 return best 74 75 76 def find_esp(disk): 77 for d in lsblk(): 78 if d.get("type") == "part" and "/dev/" + (d.get("pkname") or "") == disk: 79 if (d.get("parttype") or "").lower() in (ESP_GUID, "0xef"): 80 return d["path"] 81 return None 82 83 84 def shrink_and_make_room(win, chamesle_bytes): 85 """shrink windows so chamesle gets chamesle_bytes after it, returns the new partition's path""" 86 sector = 512 87 with open("/sys/class/block/%s/start" % win["name"]) as f: 88 start = int(f.read()) 89 with open("/sys/class/block/%s/size" % win["name"]) as f: 90 old_sectors = int(f.read()) 91 92 keep = (win["size"] - chamesle_bytes) // MIB * MIB 93 if keep < win["min"]: 94 raise Exception("Windows can't be made that small") 95 96 # the filesystem first, then the partition around it (1 MiB bigger, to be safe) 97 r = run(["ntfsresize", "--force", "--no-progress-bar", "--size", str(keep), win["path"]], input="y\n") 98 if r.returncode != 0: 99 raise Exception("Couldn't shrink Windows:\n" + r.stdout + r.stderr + 100 "\nStart Windows, turn off Fast Startup and shut it down fully, then try again.") 101 part_sectors = (keep + MIB) // sector 102 r = run(["sfdisk", "--no-reread", "--no-tell-kernel", "-N", str(win["partn"]), win["disk"]], 103 input=",%d\n" % part_sectors) 104 if r.returncode != 0: 105 raise Exception("Couldn't resize the Windows partition:\n" + r.stderr) 106 107 # the new one goes in the space that was freed, lined up on 1 MiB 108 new_start = (start + part_sectors + 2047) // 2048 * 2048 109 new_sectors = start + old_sectors - new_start 110 before = {d["path"] for d in lsblk()} 111 kind = "L" if win["pttype"] == "gpt" else "83" 112 r = run(["sfdisk", "--no-reread", "--no-tell-kernel", "--append", win["disk"]], 113 input="%d,%d,%s\n" % (new_start, new_sectors, kind)) 114 if r.returncode != 0: 115 raise Exception("Couldn't create the new partition:\n" + r.stderr) 116 run(["partx", "-u", win["disk"]]) 117 run(["udevadm", "settle"]) 118 for _ in range(20): 119 new = [d["path"] for d in lsblk() if d["path"] not in before and d.get("type") == "part"] 120 if new: 121 return new[0] 122 time.sleep(0.5) 123 raise Exception("The new partition didn't show up")