disks.py (6814B)
1 # drive scanning and partitioning 2 import json 3 import os 4 import subprocess 5 6 GiB = 1 << 30 7 MiB = 1 << 20 8 MIN_SIZE = 20 * GiB 9 ESP_TYPE = "c12a7328-f81f-11d2-ba4b-00a0c93ec93b" 10 11 12 def efi(): 13 return os.path.exists("/sys/firmware/efi") 14 15 16 def run(*cmd, input=None): 17 print("jiggity:", " ".join(cmd)) 18 r = subprocess.run(cmd, input=input, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 19 if r.stdout: 20 print(r.stdout.rstrip()) 21 if r.returncode: 22 last = (r.stdout or "").strip().splitlines() 23 raise RuntimeError("%s failed: %s" % (cmd[0], last[-1] if last else "exit code %d" % r.returncode)) 24 return r.stdout 25 26 27 def size_text(n): 28 if n >= 1000 * GiB: 29 return "%.1f TB" % (n / (1024 * GiB)) 30 if n >= GiB: 31 return "%.1f GB" % (n / GiB) 32 return "%d MB" % (n // MiB) 33 34 35 def live_medium(): 36 out = subprocess.run(["lsblk", "-J", "-o", "PATH,PKNAME,LABEL,FSTYPE"], text=True, stdout=subprocess.PIPE).stdout 37 for d in json.loads(out)["blockdevices"]: 38 for dev in [d] + d.get("children", []): 39 if dev.get("label") == "CHAMESLE" or dev.get("fstype") == "iso9660": 40 return d["path"] 41 return None 42 43 44 def part_path(disk, number): 45 return "%s%s%d" % (disk, "p" if disk[-1].isdigit() else "", number) 46 47 48 class Row: 49 def __init__(self, kind, disk, label, total, free, type_text, start=0, end=0, number=0): 50 self.kind, self.disk, self.label = kind, disk, label 51 self.total, self.free, self.type_text = total, free, type_text 52 self.start, self.end, self.number = start, end, number 53 54 @property 55 def usable(self): 56 return self.kind in ("drive", "free") and self.total >= MIN_SIZE 57 58 59 def parted_lines(disk): 60 r = subprocess.run(["parted", "-m", "-s", disk, "unit", "B", "print", "free"], text=True, 61 stdout=subprocess.PIPE, stderr=subprocess.PIPE) 62 return r.stdout.splitlines() 63 64 65 def scan(): 66 skip = live_medium() 67 out = subprocess.run(["lsblk", "-J", "-b", "-d", "-o", "PATH,SIZE,TYPE,MODEL,RO,TRAN"], text=True, 68 stdout=subprocess.PIPE).stdout 69 rows = [] 70 n = 0 71 for d in json.loads(out)["blockdevices"]: 72 # skip zram and empty card readers 73 if d["type"] != "disk" or d["ro"] or d["path"] == skip or d["path"].startswith("/dev/zram") or int(d["size"]) < GiB: 74 continue 75 name = "Drive %d" % n 76 model = (d.get("model") or "").strip() 77 rows.append(Row("drive", d["path"], "%s%s" % (name, ": " + model if model else ""), int(d["size"]), 0, 78 "Whole drive")) 79 lines = parted_lines(d["path"]) 80 label = lines[1].split(":")[5] if len(lines) > 1 else "unknown" 81 if label not in ("gpt", "msdos"): 82 rows.append(Row("free", d["path"], "%s Unallocated Space" % name, int(d["size"]), int(d["size"]), "", 83 0, int(d["size"]) - 1)) 84 n += 1 85 continue 86 for line in lines[2:]: 87 f = line.rstrip(";").split(":") 88 start, end, size = (int(x.rstrip("B")) for x in f[1:4]) 89 if f[4] == "free": 90 if size >= 64 * MiB: 91 rows.append(Row("free", d["path"], "%s Unallocated Space" % name, size, size, "", start, end)) 92 else: 93 num = int(f[0]) 94 fs, pname, flags = f[4], f[5], f[6] 95 kind = "System" if "esp" in flags or "boot" in flags and fs.startswith("fat") else \ 96 "MSR (Reserved)" if "msftres" in flags else "Recovery" if "msftdata" not in flags and "hidden" in flags \ 97 else fs or "Primary" 98 free = used_free(part_path(d["path"], num), fs, size) 99 rows.append(Row("part", d["path"], "%s Partition %d%s" % (name, num, ": " + pname if pname else ""), 100 size, free, kind, start, end, num)) 101 n += 1 102 return rows 103 104 105 def used_free(path, fs, size): 106 r = subprocess.run(["lsblk", "-J", "-b", "-o", "FSAVAIL", path], text=True, stdout=subprocess.PIPE, 107 stderr=subprocess.DEVNULL) 108 try: 109 avail = json.loads(r.stdout)["blockdevices"][0]["fsavail"] 110 return int(avail) if avail is not None else size 111 except (ValueError, KeyError, IndexError): 112 return size 113 114 115 def numbers(disk): 116 nums = set() 117 for line in parted_lines(disk)[2:]: 118 f = line.rstrip(";").split(":") 119 if f[4] != "free": 120 nums.add(int(f[0])) 121 return nums 122 123 124 def settle(): 125 subprocess.run(["partprobe"], stderr=subprocess.DEVNULL) 126 subprocess.run(["udevadm", "settle"]) 127 128 129 def has_esp(disk): 130 for line in parted_lines(disk)[2:]: 131 f = line.rstrip(";").split(":") 132 if f[4] != "free" and "esp" in f[6]: 133 return part_path(disk, int(f[0])) 134 return None 135 136 137 def has_bios_grub(disk): 138 return any("bios_grub" in line for line in parted_lines(disk)[2:]) 139 140 141 class Plan: 142 # boot is only set with encryption, grub can't read luks2 143 efi = boot = root = None 144 format_efi = False 145 146 147 def make(row, encrypt): 148 disk = row.disk 149 plan = Plan() 150 if row.kind == "drive" or parted_lines(disk)[1:2] and parted_lines(disk)[1].split(":")[5] not in ("gpt", "msdos"): 151 run("wipefs", "-a", disk) 152 run("parted", "-s", disk, "mklabel", "gpt") 153 start, end = MiB, None 154 else: 155 start = (row.start + MiB - 1) // MiB * MiB 156 end = (row.end + 1) // MiB * MiB 157 label = parted_lines(disk)[1].split(":")[5] 158 pieces = [] 159 if efi(): 160 plan.efi = has_esp(disk) 161 if not plan.efi: 162 pieces.append(("efi", 512 * MiB)) 163 plan.format_efi = True 164 elif label == "gpt" and not has_bios_grub(disk): 165 pieces.append(("bios_grub", MiB)) 166 if encrypt: 167 pieces.append(("boot", GiB)) 168 pieces.append(("root", None)) 169 at = start 170 for what, size in pieces: 171 before = numbers(disk) 172 stop = "100%" if size is None and end is None else "%dB" % ((at + size if size else end) - 1) 173 if label == "gpt": 174 run("parted", "-s", "-a", "optimal", disk, "unit", "B", "mkpart", "chamesle-" + what, "%dB" % at, stop) 175 else: 176 run("parted", "-s", "-a", "optimal", disk, "unit", "B", "mkpart", "primary", "%dB" % at, stop) 177 num = (numbers(disk) - before).pop() 178 path = part_path(disk, num) 179 if what == "efi": 180 run("parted", "-s", disk, "set", str(num), "esp", "on") 181 plan.efi = path 182 elif what == "bios_grub": 183 run("parted", "-s", disk, "set", str(num), "bios_grub", "on") 184 elif what == "boot": 185 plan.boot = path 186 else: 187 plan.root = path 188 if size: 189 at += size 190 settle() 191 return plan