dark-instux 0.1.0__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.
Files changed (45) hide show
  1. dark_instux/__init__.py +3 -0
  2. dark_instux/builder.py +436 -0
  3. dark_instux/cli.py +399 -0
  4. dark_instux/config/__init__.py +159 -0
  5. dark_instux/config/edit.py +96 -0
  6. dark_instux/config/host.py +489 -0
  7. dark_instux/config/keyinfo.py +68 -0
  8. dark_instux/config/storage.py +175 -0
  9. dark_instux/config/template.py +90 -0
  10. dark_instux/disks/__init__.py +0 -0
  11. dark_instux/disks/inventory.py +87 -0
  12. dark_instux/disks/matchers.py +157 -0
  13. dark_instux/disks/model.py +45 -0
  14. dark_instux/disks/pmbr.py +27 -0
  15. dark_instux/disks/resolve.py +65 -0
  16. dark_instux/distro/__init__.py +36 -0
  17. dark_instux/distro/base.py +270 -0
  18. dark_instux/distro/debian.py +412 -0
  19. dark_instux/distro/network.py +132 -0
  20. dark_instux/distro/redhat.py +333 -0
  21. dark_instux/errors.py +41 -0
  22. dark_instux/installer/__init__.py +0 -0
  23. dark_instux/installer/main.py +208 -0
  24. dark_instux/installer/pipeline.py +463 -0
  25. dark_instux/installer/system.py +200 -0
  26. dark_instux/manifest/__init__.py +222 -0
  27. dark_instux/media/__init__.py +0 -0
  28. dark_instux/media/container.py +126 -0
  29. dark_instux/media/guard.py +102 -0
  30. dark_instux/media/layout.py +196 -0
  31. dark_instux/media/live.py +290 -0
  32. dark_instux/media/writer.py +340 -0
  33. dark_instux/profiles/__init__.py +1 -0
  34. dark_instux/profiles/raid1-lvm.yml +26 -0
  35. dark_instux/profiles/single-ext4.yml +19 -0
  36. dark_instux/profiles/single-lvm.yml +24 -0
  37. dark_instux/py.typed +0 -0
  38. dark_instux/repo/__init__.py +0 -0
  39. dark_instux/runner.py +226 -0
  40. dark_instux/util.py +130 -0
  41. dark_instux-0.1.0.dist-info/METADATA +852 -0
  42. dark_instux-0.1.0.dist-info/RECORD +45 -0
  43. dark_instux-0.1.0.dist-info/WHEEL +4 -0
  44. dark_instux-0.1.0.dist-info/entry_points.txt +3 -0
  45. dark_instux-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,3 @@
1
+ """dark-instux: offline, unattended Linux installation keys."""
2
+
3
+ __version__ = "0.1.0"
dark_instux/builder.py ADDED
@@ -0,0 +1,436 @@
1
+ """``dark-instux build``: from a distribution name to a written key.
2
+
3
+ Stages, each cached in the work directory so a failed build resumes:
4
+ 1. pull the distro container image, pinned by digest
5
+ 2. rootfs export it as rootfs.tar.gz
6
+ 3. repo resolve upgrades + baseline + requested packages, index them
7
+ 4. live build the live system (shared by every distro)
8
+ 5. stage lay out ESP, CONFIG and PAYLOAD directories, write the manifest, sign it
9
+ 6. write partition, format, copy and verify the device or image
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import datetime as dt
15
+ import json
16
+ import logging
17
+ import os
18
+ import re
19
+ import shutil
20
+ import uuid
21
+ from dataclasses import dataclass, field
22
+ from pathlib import Path
23
+
24
+ import dark_instux
25
+ from dark_instux import manifest as mf
26
+ from dark_instux.config import KeyInfo, validate_config
27
+ from dark_instux.config.template import HOST_TEMPLATE, storage_profile, storage_profiles
28
+ from dark_instux.distro import get_backend
29
+ from dark_instux.errors import DarkInstuxError, ProblemsError
30
+ from dark_instux.media import guard
31
+ from dark_instux.media.container import Engine
32
+ from dark_instux.media.layout import MIB, KeyLayout
33
+ from dark_instux.media.live import DEFAULT_PPR, build_live, stage_esp
34
+ from dark_instux.media.writer import block_device, find_bios_grub_install, write_key
35
+ from dark_instux.runner import Runner
36
+ from dark_instux.util import dir_size, human, sha256_file
37
+
38
+ LOG = logging.getLogger("dark_instux.build")
39
+
40
+ HOST_TOOLS = [
41
+ "sfdisk",
42
+ "wipefs",
43
+ "mkfs.vfat",
44
+ "mkfs.ext4",
45
+ "lsblk",
46
+ "losetup",
47
+ "partx",
48
+ "udevadm",
49
+ "mount",
50
+ "umount",
51
+ "tar",
52
+ "gzip",
53
+ "mksquashfs",
54
+ "ssh-keygen",
55
+ "cp",
56
+ ]
57
+ _PKG_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9+._:-]*$")
58
+
59
+
60
+ @dataclass
61
+ class BuildOptions:
62
+ distro: str
63
+ storage: str # a stock profile name or a file
64
+ device: str | None = None
65
+ image: Path | None = None
66
+ release: str | None = None
67
+ packages: list[str] = field(default_factory=list)
68
+ host: Path | None = None
69
+ workdir: Path = Path("/var/tmp/dark-instux")
70
+ engine: str | None = None
71
+ image_override: str | None = None
72
+ signing_key: Path | None = None
73
+ ppr_spec: str = DEFAULT_PPR
74
+ allow_fixed_disk: bool = False
75
+ rebuild: bool = False
76
+ title: str | None = None
77
+ uefi_only: bool = False # skip legacy BIOS support on the key and the installed systems
78
+ pmbr_boot_flag: bool = False # for old BIOSes that only boot a disk with an active MBR entry
79
+ install_recommends: bool = False # also Recommends (apt) / weak dependencies (dnf): desktops need them
80
+ apt_components: list[str] = field(default_factory=list) # e.g. main contrib non-free-firmware (Debian family)
81
+
82
+
83
+ @dataclass
84
+ class BuildResult:
85
+ build_id: str
86
+ fingerprint: str
87
+ manifest: mf.Manifest
88
+ target: str
89
+ problems_in_host: list[str] = field(default_factory=list)
90
+
91
+
92
+ def read_package_list(path: str | Path) -> list[str]:
93
+ """One package per line; blank lines and # comments ignored."""
94
+ pkgs = []
95
+ for line in Path(path).read_text().splitlines():
96
+ line = line.split("#", 1)[0].strip()
97
+ pkgs += line.split()
98
+ return pkgs
99
+
100
+
101
+ def check_packages(names: list[str]) -> None:
102
+ """Reject package names that are not plain package identifiers.
103
+
104
+ Args:
105
+ names: Package names requested on the command line or in a package file.
106
+
107
+ Raises:
108
+ DarkInstuxError: If any name contains characters outside the allowed set.
109
+ """
110
+ bad = [n for n in names if not _PKG_RE.match(n)]
111
+ if bad:
112
+ raise DarkInstuxError(f"invalid package name(s): {', '.join(bad)}")
113
+
114
+
115
+ def load_storage_text(spec: str) -> tuple[str, str]:
116
+ """(text, source description) for a profile name or a file path."""
117
+ p = Path(spec)
118
+ if p.is_file():
119
+ return p.read_text(), str(p.resolve())
120
+ if spec in storage_profiles():
121
+ return storage_profile(spec), f"profile:{spec}"
122
+ raise DarkInstuxError(f"--storage {spec!r}: no such file or stock profile ({', '.join(storage_profiles())})")
123
+
124
+
125
+ def preflight(opts: BuildOptions) -> str | None:
126
+ """Check the build machine; return its grub-install for BIOS keys (None with --uefi-only)."""
127
+ if os.geteuid() != 0:
128
+ raise DarkInstuxError("dark-instux build needs root (run it with sudo)")
129
+ missing = [t for t in HOST_TOOLS if not shutil.which(t)]
130
+ if missing:
131
+ raise DarkInstuxError(f"missing tools on this machine: {', '.join(missing)}")
132
+ if bool(opts.device) == bool(opts.image):
133
+ raise DarkInstuxError("give exactly one of --device or --image")
134
+ if opts.uefi_only:
135
+ if opts.pmbr_boot_flag:
136
+ raise DarkInstuxError("--pmbr-boot-flag is for legacy BIOS keys, not with --uefi-only")
137
+ return None
138
+ grub_install = find_bios_grub_install()
139
+ if not grub_install:
140
+ raise DarkInstuxError(
141
+ "legacy BIOS support needs GRUB for BIOS on this machine "
142
+ "(Debian/Ubuntu: apt install grub-pc-bin; Fedora/AlmaLinux: dnf install grub2-pc-modules grub2-tools), "
143
+ "or build a UEFI-only key with --uefi-only"
144
+ )
145
+ return grub_install
146
+
147
+
148
+ class _Stamp:
149
+ """Cache marker of a stage: its inputs, so a changed input rebuilds it."""
150
+
151
+ def __init__(self, path: Path, inputs: dict) -> None:
152
+ self.path = path
153
+ self.inputs = json.dumps(inputs, sort_keys=True)
154
+
155
+ def valid(self) -> bool:
156
+ return self.path.is_file() and self.path.read_text() == self.inputs
157
+
158
+ def done(self) -> None:
159
+ self.path.write_text(self.inputs)
160
+
161
+
162
+ def build(opts: BuildOptions, runner: Runner | None = None, *, confirm=None) -> BuildResult:
163
+ """Build a key: pull, resolve, stage, sign and write it to a device or image.
164
+
165
+ Each expensive stage is cached in the work directory (see the module docstring), so a failed
166
+ build resumes where it stopped. The device is checked before any download and again, with the
167
+ real payload size, before anything is written.
168
+
169
+ Args:
170
+ opts: What to build and where to write it.
171
+ runner: Command runner used for every external program. Defaults to a real ``Runner``.
172
+ confirm: Optional callback called with the target device information just before writing.
173
+ Returning a false value cancels the build.
174
+
175
+ Returns:
176
+ The build id, the manifest signing fingerprint, the manifest, the target and the problems
177
+ still present in the ``host.yml`` copied to the key.
178
+
179
+ Raises:
180
+ DarkInstuxError: On invalid options, missing packages or tools, an unsuitable device, or
181
+ when ``confirm`` declines.
182
+ ProblemsError: If a prerequisite check collects validation problems.
183
+ """
184
+ runner = runner or Runner()
185
+ grub_install = preflight(opts)
186
+ backend = get_backend(opts.distro)
187
+ spec = backend.spec
188
+ release = spec.normalize_release(opts.release)
189
+ image = opts.image_override or spec.image(release)
190
+ check_packages(opts.packages)
191
+ if opts.apt_components:
192
+ if spec.family != "debian":
193
+ raise DarkInstuxError("--apt-components only applies to Debian and Ubuntu")
194
+ bad = [c for c in opts.apt_components if not re.match(r"^[a-z0-9-]+$", c)]
195
+ if bad:
196
+ raise DarkInstuxError(f"invalid archive component(s): {', '.join(bad)}")
197
+ storage_text, storage_source = load_storage_text(opts.storage)
198
+
199
+ if opts.device: # fail before hours of downloads, size is checked again later
200
+ info = guard.check_device(opts.device, runner, allow_fixed=opts.allow_fixed_disk)
201
+ LOG.info("target device: %s", info.describe())
202
+
203
+ work = opts.workdir / f"{spec.name}-{release}"
204
+ if opts.rebuild and work.exists():
205
+ shutil.rmtree(work)
206
+ work.mkdir(parents=True, exist_ok=True)
207
+ engine = Engine.detect(runner, opts.engine)
208
+
209
+ # 1. pull
210
+ LOG.info("[1/6] pulling %s", image)
211
+ ref = engine.pull(image)
212
+ LOG.info("image pinned as %s", ref)
213
+
214
+ # 2. rootfs
215
+ rootfs = work / "rootfs.tar.gz"
216
+ stamp = _Stamp(work / "rootfs.stamp", {"ref": ref})
217
+ if not (stamp.valid() and rootfs.is_file()):
218
+ LOG.info("[2/6] exporting the root filesystem")
219
+ tar = work / "rootfs.tar"
220
+ engine.export(ref, tar)
221
+ runner.run(["gzip", "-6", "-f", tar])
222
+ stamp.done()
223
+ else:
224
+ LOG.info("[2/6] root filesystem cached")
225
+
226
+ # 3. repo
227
+ baseline = backend.baseline_packages()
228
+ uefi_pkgs = backend.boot_packages("uefi")
229
+ bios_pkgs = [] if opts.uefi_only else backend.boot_packages("bios")
230
+ wanted = list(dict.fromkeys([*baseline, *uefi_pkgs, *opts.packages]))
231
+ repo_out = work / "repo-out"
232
+ stamp = _Stamp(
233
+ work / "repo.stamp",
234
+ {
235
+ "ref": ref,
236
+ "packages": wanted,
237
+ "bios": bios_pkgs,
238
+ "script": backend.resolve_script(),
239
+ "recommends": opts.install_recommends,
240
+ "components": opts.apt_components,
241
+ },
242
+ )
243
+ if not (stamp.valid() and (repo_out / "repo").is_dir()):
244
+ LOG.info("[3/6] resolving %d packages and their dependencies", len(wanted) + len(bios_pkgs))
245
+ if repo_out.exists():
246
+ shutil.rmtree(repo_out)
247
+ repo_out.mkdir()
248
+ engine.run_script(
249
+ ref,
250
+ backend.resolve_script(),
251
+ wanted,
252
+ volumes=[(repo_out, "/out", "Z")],
253
+ env={
254
+ "DARK_INSTUX_BIOS_PACKAGES": " ".join(bios_pkgs),
255
+ "DARK_INSTUX_RECOMMENDS": "true" if opts.install_recommends else "false",
256
+ "DARK_INSTUX_APT_COMPONENTS": " ".join(opts.apt_components),
257
+ },
258
+ )
259
+ stamp.done()
260
+ else:
261
+ LOG.info("[3/6] repository cached")
262
+ codename = (repo_out / "codename").read_text().strip() if (repo_out / "codename").is_file() else release
263
+ available = frozenset((repo_out / "available-packages.txt").read_text().split())
264
+ missing = [p for p in [*wanted, *bios_pkgs] if p not in available]
265
+ if missing:
266
+ raise DarkInstuxError(f"the repository lacks: {', '.join(missing)}")
267
+
268
+ # 4. live
269
+ LOG.info("[4/6] live system")
270
+ live = build_live(engine, runner, opts.workdir / "live", opts.ppr_spec)
271
+
272
+ # 5. stage
273
+ LOG.info("[5/6] staging the key")
274
+ build_id = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex[:6]
275
+ staging = work / "staging"
276
+ if staging.exists():
277
+ shutil.rmtree(staging)
278
+ esp, config, payload = (staging / n for n in ("esp", "config", "payload"))
279
+ for d in (esp, config, payload):
280
+ d.mkdir(parents=True)
281
+
282
+ (payload / "live").mkdir()
283
+ _link_or_copy(live.squashfs, payload / "live/filesystem.squashfs")
284
+ _link_or_copy(rootfs, payload / "rootfs.tar.gz")
285
+ _link_tree(repo_out / "repo", payload / "repo")
286
+
287
+ payload_bytes = dir_size(payload)
288
+ payload_mib = int(payload_bytes * 1.08 / MIB) + 256 if opts.image else None
289
+ title = opts.title or f"dark-instux {spec.pretty} {release}"
290
+ layout = KeyLayout(build_id=build_id, title=title, payload_mib=payload_mib, bios=not opts.uefi_only)
291
+ stage_esp(esp, live, layout.grub_cfg(), build_id)
292
+
293
+ manifest = mf.Manifest(
294
+ build_id=build_id,
295
+ created=dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
296
+ dark_instux_version=dark_instux.__version__,
297
+ distro=spec.name,
298
+ family=spec.family,
299
+ release=release,
300
+ codename=codename,
301
+ image=image,
302
+ image_ref=ref,
303
+ packages_baseline=baseline,
304
+ packages_requested=list(opts.packages),
305
+ packages_uefi=uefi_pkgs,
306
+ packages_bios=bios_pkgs,
307
+ install_recommends=opts.install_recommends,
308
+ apt_components=list(opts.apt_components),
309
+ pmbr_boot_flag=opts.pmbr_boot_flag,
310
+ storage_source=storage_source,
311
+ storage_sha256="",
312
+ partitions={
313
+ "esp": layout.esp_partuuid,
314
+ "config": layout.config_partuuid,
315
+ "payload": layout.payload_partuuid,
316
+ },
317
+ )
318
+ (config / "storage.yml").write_text(storage_text)
319
+ manifest.storage_sha256 = sha256_file(config / "storage.yml")
320
+ (config / "certs").mkdir()
321
+ (config / "keys").mkdir()
322
+ if opts.host:
323
+ shutil.copyfile(opts.host, config / "host.yml")
324
+ for sub in ("certs", "keys"):
325
+ src = opts.host.parent / sub
326
+ if src.is_dir():
327
+ shutil.copytree(src, config / sub, dirs_exist_ok=True)
328
+ else:
329
+ (config / "host.yml").write_text(HOST_TEMPLATE)
330
+ (payload / "dark-instux").mkdir()
331
+ manifest.files = mf.checksum_payload(payload)
332
+ (payload / mf.MANIFEST).write_text(manifest.to_json())
333
+ key = opts.signing_key or mf.generate_signing_key(opts.workdir / "signing", runner)
334
+ fingerprint = mf.sign(payload, key, runner)
335
+ KeyInfo(
336
+ build_id=build_id,
337
+ distro=spec.name,
338
+ family=spec.family,
339
+ release=release,
340
+ codename=codename,
341
+ created=manifest.created,
342
+ dark_instux_version=dark_instux.__version__,
343
+ signing_fingerprint=fingerprint,
344
+ packages=available,
345
+ ).write(config)
346
+ (config / "dark-instux/logs").mkdir(parents=True, exist_ok=True)
347
+ (config / "README.txt").write_text(_config_readme(spec.pretty, release, build_id, fingerprint, layout.bios))
348
+
349
+ host_problems: list[str] = []
350
+ try:
351
+ validate_config(config / "host.yml")
352
+ except ProblemsError as exc:
353
+ host_problems = [str(p) for p in exc.problems]
354
+
355
+ # 6. write
356
+ target = str(opts.device or opts.image)
357
+ if opts.device:
358
+ info = guard.check_device(
359
+ opts.device,
360
+ runner,
361
+ needed_bytes=layout.min_device_bytes(int(payload_bytes * 1.08) + 256 * MIB),
362
+ allow_fixed=opts.allow_fixed_disk,
363
+ )
364
+ if confirm is not None and not confirm(info):
365
+ raise DarkInstuxError("cancelled: nothing was written")
366
+ LOG.info("[6/6] writing %s (%s of payload)", target, human(payload_bytes))
367
+ image_bytes = layout.image_bytes() if opts.image else None
368
+ with block_device(target, runner, image_bytes=image_bytes) as dev:
369
+ write_key(dev, layout, staging, runner, grub_install=grub_install, pmbr_boot_flag=opts.pmbr_boot_flag)
370
+ LOG.info("key %s written to %s; manifest signed by %s", build_id, target, fingerprint)
371
+ return BuildResult(build_id, fingerprint, manifest, target, host_problems)
372
+
373
+
374
+ def _same_fs(a: Path, b: Path) -> bool:
375
+ """Tell whether two paths live on the same filesystem (so hard links work)."""
376
+ try:
377
+ return a.stat().st_dev == b.stat().st_dev
378
+ except OSError:
379
+ return False
380
+
381
+
382
+ def _link_or_copy(src: Path, dst: Path) -> None:
383
+ """Hard-link ``src`` to ``dst`` when they share a filesystem, copy it otherwise."""
384
+ if _same_fs(src, dst.parent):
385
+ os.link(src, dst)
386
+ else:
387
+ shutil.copyfile(src, dst)
388
+
389
+
390
+ def _link_tree(src: Path, dst: Path) -> None:
391
+ """Recreate the directory tree ``src`` under ``dst`` with hard links or copies of the files."""
392
+ for p in sorted(src.rglob("*")):
393
+ rel = p.relative_to(src)
394
+ if p.is_dir():
395
+ (dst / rel).mkdir(parents=True, exist_ok=True)
396
+ elif p.is_file():
397
+ (dst / rel).parent.mkdir(parents=True, exist_ok=True)
398
+ _link_or_copy(p, dst / rel)
399
+
400
+
401
+ def _config_readme(pretty: str, release: str, build_id: str, fingerprint: str, bios: bool) -> str:
402
+ """Render the README.txt placed on the CONFIG partition.
403
+
404
+ Args:
405
+ pretty: Human readable distribution name.
406
+ release: Distribution release.
407
+ build_id: Identifier of this build.
408
+ fingerprint: Fingerprint of the manifest signing key.
409
+ bios: Whether the key also boots legacy BIOS machines.
410
+
411
+ Returns:
412
+ The text of the README.
413
+ """
414
+ modes = "UEFI (Secure Boot on or off) and legacy BIOS" if bios else "UEFI only (built with --uefi-only)"
415
+ return f"""\
416
+ dark-instux key -- {pretty} {release}
417
+ build {build_id}
418
+ manifest signing key {fingerprint}
419
+ boots: {modes}
420
+
421
+ 1. Edit host.yml (and storage.yml if needed). Put CA certificates in certs/
422
+ and repository keys in keys/.
423
+ 2. Check it: dark-instux validate host.yml
424
+ 3. Boot the target machine from this key. The installed system boots the way
425
+ the key was booted: UEFI or legacy BIOS (on machines that offer both, the
426
+ boot menu lists the key twice, e.g. "UEFI: SanDisk" and "SanDisk").
427
+ With install.mode: check the key only reports the disks it would use
428
+ (dark-instux/preflight.json, including "boot_mode") and powers off.
429
+ With install.mode: install it installs, then
430
+ - UEFI: reboots into the new system by itself;
431
+ - legacy BIOS: asks you to remove the key, and restarts once it is removed.
432
+
433
+ Results are written in dark-instux/: status.json, preflight.json, logs/.
434
+ After a successful install dark-instux/DONE exists and the key no longer installs;
435
+ delete that file to install the same host again.
436
+ """