-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatomic_image_wizard.py
More file actions
4042 lines (3491 loc) · 161 KB
/
atomic_image_wizard.py
File metadata and controls
4042 lines (3491 loc) · 161 KB
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Atomic Image Wizard
A step-by-step GTK4 wizard for creating custom Fedora Atomic / bootc images.
"""
import gi
gi.require_version("Gtk", "4.0")
from gi.repository import Gtk, GLib, Pango
import subprocess
import threading
import sys
import os
import re
import json
import time
import urllib.request
import urllib.error
# =============================================================================
# Constants / data
# =============================================================================
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# Preferences file lives alongside the wizard in ~/bootc/ for self-containment
_PREFS_FILE = os.path.join(SCRIPT_DIR, "aiw_prefs.json")
# Bodhi API — used for kernel version checks
_BODHI_UPDATES_URL = (
"https://bodhi.fedoraproject.org/updates/"
"?packages=kernel&status=stable&rows_per_page=5"
)
RPM_FUSION_FREE_URL = "https://mirrors.rpmfusion.org/free/fedora/rpmfusion-free-release-{ver}.noarch.rpm"
RPM_FUSION_NONFREE_URL = "https://mirrors.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-{ver}.noarch.rpm"
REPO_DEFINITIONS = {
"RPM Fusion Free": {
"description": "Open-source packages not in Fedora (ffmpeg, VLC codecs, etc.)",
"run": f"dnf install -y {RPM_FUSION_FREE_URL} && dnf clean all",
},
"RPM Fusion Non-Free": {
"description": "Proprietary packages — NVIDIA drivers, Steam, etc.",
"run": f"dnf install -y {RPM_FUSION_NONFREE_URL} && dnf clean all",
"requires": "RPM Fusion Free",
},
}
PRESET_REPOS = [
("Tailscale",
"curl -fsSL https://pkgs.tailscale.com/stable/fedora/tailscale.repo "
"-o /etc/yum.repos.d/tailscale.repo"),
("VS Code",
"rpm --import https://packages.microsoft.com/keys/microsoft.asc && "
"curl -fsSL https://packages.microsoft.com/yumrepos/vscode/config.repo "
"-o /etc/yum.repos.d/vscode.repo"),
("Google Chrome",
"curl -fsSL https://dl.google.com/linux/chrome/rpm/stable/x86_64/google-chrome.repo "
"-o /etc/yum.repos.d/google-chrome.repo"),
("1Password",
"rpm --import https://downloads.1password.com/linux/keys/1password.asc && "
"curl -fsSL https://downloads.1password.com/linux/rpm/stable/x86_64/1password.repo "
"-o /etc/yum.repos.d/1password.repo"),
("Docker CE",
"curl -fsSL https://download.docker.com/linux/fedora/docker-ce.repo "
"-o /etc/yum.repos.d/docker-ce.repo"),
("Brave Browser",
"curl -fsSL https://brave-browser-rpm-release.s3.brave.com/brave-browser.repo "
"-o /etc/yum.repos.d/brave-browser.repo"),
]
# Service name used by scx-scheds — normalised to one constant everywhere
SCX_SERVICE = "scx_loader.service"
# Desktop variants to query from the registry
_ATOMIC_DESKTOPS = [
"silverblue",
"kinoite",
"sway-atomic",
"budgie-atomic",
"cosmic-atomic",
]
# How many past numeric releases to include in the dropdown (current + this many back)
_REGISTRY_RELEASE_DEPTH = 2
# =============================================================================
# Registry preset cache
# =============================================================================
_CACHE_DIR = os.path.join(GLib.get_user_cache_dir(), "atomic-image-wizard")
_CACHE_FILE = os.path.join(_CACHE_DIR, "presets.json")
_CACHE_TTL = 7 * 24 * 60 * 60 # 7 days in seconds
# Sentinel prefix used to mark non-selectable header/separator rows in the
# base-image dropdown. Any string starting with this prefix is treated as a
# visual divider — it is shown in the list but immediately rejected if the user
# actually selects it, bouncing back to the previous valid entry.
_DROPDOWN_HEADER_PREFIX = "─── "
# Header row inserted into the preset list before the ublue section.
_UBLUE_HEADER = "─── Universal Blue (ghcr.io/ublue-os) " + "─" * 28
def _load_cache() -> tuple[list[str] | None, bool, bool]:
"""
Load presets from the on-disk cache.
Returns (presets, is_fresh, from_cache):
presets — list of image strings, or None if no cache exists
is_fresh — True if within TTL
from_cache — True if any cached data was found at all
"""
try:
with open(_CACHE_FILE) as f:
data = json.load(f)
presets = data.get("presets", [])
timestamp = data.get("timestamp", 0)
if not presets:
return None, False, False
is_fresh = (time.time() - timestamp) < _CACHE_TTL
return presets, is_fresh, True
except (FileNotFoundError, json.JSONDecodeError, OSError):
return None, False, False
def _save_cache(presets: list[str]) -> None:
"""Write presets to disk cache with current timestamp."""
try:
os.makedirs(_CACHE_DIR, exist_ok=True)
with open(_CACHE_FILE, "w") as f:
json.dump({"timestamp": time.time(), "presets": presets}, f, indent=2)
except OSError:
pass # non-fatal — app works fine without a cache write
def _fetch_presets_from_registry() -> list[str] | None:
"""
Query the Quay.io API for available tags on each desktop repo and bootc.
Returns an ordered list of image strings, or None on failure.
Tag ordering: newest numeric releases first (per desktop), then rawhide, then latest.
Only the current + _REGISTRY_RELEASE_DEPTH previous numeric versions are included
to keep the dropdown manageable.
All per-repo tag fetches after the anchor query run concurrently via
ThreadPoolExecutor, reducing wall-clock time from ~15s sequential to ~2-3s.
Each repo is fetched exactly once — results are reused for both version
and rawhide checks.
"""
from concurrent.futures import ThreadPoolExecutor, as_completed
base = "quay.io/fedora-ostree-desktops"
bootc_org = "fedora"
bootc_repo = "fedora-bootc"
bootc_ref = "quay.io/fedora/fedora-bootc"
def _query_tags(org: str, repo: str) -> list[str]:
url = (f"https://quay.io/api/v1/repository/{org}/{repo}"
f"/tag/?limit=100&onlyActiveTags=true")
try:
req = urllib.request.Request(url, headers={"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=10) as r:
data = json.loads(r.read().decode())
return [t["name"] for t in data.get("tags", []) if "name" in t]
except (urllib.error.URLError, json.JSONDecodeError, OSError, KeyError):
return []
def _numeric_tags(tags: list[str]) -> list[int]:
nums = []
for t in tags:
if re.fullmatch(r"\d+", t):
try:
nums.append(int(t))
except ValueError:
pass
return sorted(set(nums), reverse=True)
# ── Step 1: anchor query (sequential — everything else depends on this) ──
# Silverblue is the most stable indicator of available releases.
anchor_tags = _query_tags("fedora-ostree-desktops", "silverblue")
if not anchor_tags:
return None # network failure — caller will use cache or fallback
numeric_releases = _numeric_tags(anchor_tags)[:_REGISTRY_RELEASE_DEPTH + 1]
if not numeric_releases:
return None
# ── Step 2: fetch all remaining repos concurrently, each exactly once ───
# Build the full set of (org, repo) pairs we need, excluding silverblue
# which we already have from the anchor query.
repos_to_fetch = (
[(bootc_org, bootc_repo)]
+ [("fedora-ostree-desktops", d)
for d in _ATOMIC_DESKTOPS if d != "silverblue"]
)
# tag_cache: (org, repo) → [tag, ...]
tag_cache: dict[tuple[str, str], list[str]] = {
("fedora-ostree-desktops", "silverblue"): anchor_tags,
}
with ThreadPoolExecutor(max_workers=len(repos_to_fetch)) as pool:
future_to_key = {
pool.submit(_query_tags, org, repo): (org, repo)
for org, repo in repos_to_fetch
}
for future in as_completed(future_to_key):
key = future_to_key[future]
try:
tag_cache[key] = future.result()
except Exception:
tag_cache[key] = [] # treat failed fetch as empty — non-fatal
# ── Step 3: assemble preset list from cached tag data ───────────────────
presets = []
# Numeric releases — newest first, desktops in _ATOMIC_DESKTOPS order
for ver in numeric_releases:
ver_str = str(ver)
for desktop in _ATOMIC_DESKTOPS:
tags = tag_cache.get(("fedora-ostree-desktops", desktop), [])
if ver_str in tags:
presets.append(f"{base}/{desktop}:{ver_str}")
bootc_tags = tag_cache.get((bootc_org, bootc_repo), [])
if ver_str in bootc_tags:
presets.append(f"{bootc_ref}:{ver_str}")
# Rawhide — reuse the same cached tag lists, no extra HTTP calls
for desktop in _ATOMIC_DESKTOPS:
tags = tag_cache.get(("fedora-ostree-desktops", desktop), [])
if "rawhide" in tags:
presets.append(f"{base}/{desktop}:rawhide")
bootc_tags = tag_cache.get((bootc_org, bootc_repo), [])
if "rawhide" in bootc_tags:
presets.append(f"{bootc_ref}:rawhide")
# latest — bootc only
if "latest" in bootc_tags:
presets.append(f"{bootc_ref}:latest")
if not presets:
return None
# Always append Universal Blue presets — they are on ghcr.io, not Quay.io,
# so the registry fetch above will never return them. Appending here
# ensures they survive a manual Refresh without a full app restart.
ublue = [
_UBLUE_HEADER,
"ghcr.io/ublue-os/aurora:stable",
"ghcr.io/ublue-os/aurora:stable-daily",
"ghcr.io/ublue-os/aurora:latest",
"ghcr.io/ublue-os/aurora-nvidia-open:stable",
"ghcr.io/ublue-os/aurora-nvidia-open:stable-daily",
"ghcr.io/ublue-os/aurora-nvidia-open:latest",
"ghcr.io/ublue-os/aurora-dx:stable",
"ghcr.io/ublue-os/aurora-dx:stable-daily",
"ghcr.io/ublue-os/aurora-dx:latest",
"ghcr.io/ublue-os/aurora-dx-nvidia-open:stable",
"ghcr.io/ublue-os/aurora-dx-nvidia-open:stable-daily",
"ghcr.io/ublue-os/aurora-dx-nvidia-open:latest",
"ghcr.io/ublue-os/bazzite:stable",
"ghcr.io/ublue-os/bazzite:latest",
"ghcr.io/ublue-os/bazzite-nvidia-open:stable",
"ghcr.io/ublue-os/bazzite-nvidia-open:latest",
"ghcr.io/ublue-os/bazzite-gnome:stable",
"ghcr.io/ublue-os/bazzite-gnome:latest",
"ghcr.io/ublue-os/bazzite-gnome-nvidia-open:stable",
"ghcr.io/ublue-os/bazzite-gnome-nvidia-open:latest",
"ghcr.io/ublue-os/bluefin:stable",
"ghcr.io/ublue-os/bluefin:stable-daily",
"ghcr.io/ublue-os/bluefin:latest",
"ghcr.io/ublue-os/bluefin-nvidia-open:stable",
"ghcr.io/ublue-os/bluefin-nvidia-open:stable-daily",
"ghcr.io/ublue-os/bluefin-nvidia-open:latest",
"ghcr.io/ublue-os/bluefin-dx:stable",
"ghcr.io/ublue-os/bluefin-dx:stable-daily",
"ghcr.io/ublue-os/bluefin-dx:latest",
"ghcr.io/ublue-os/bluefin-dx-nvidia-open:stable",
"ghcr.io/ublue-os/bluefin-dx-nvidia-open:stable-daily",
"ghcr.io/ublue-os/bluefin-dx-nvidia-open:latest",
]
existing = set(presets)
presets += [p for p in ublue if p not in existing]
return presets
# Initial preset list — populated from cache if available, otherwise empty until
# the async registry fetch completes on first run.
def _initial_presets() -> list[str]:
cached, _fresh, found = _load_cache()
if found:
return cached
return []
BASE_PRESETS = _initial_presets()
# (label, [packages], requires_rpmfusion_free, requires_rpmfusion_nonfree)
PACKAGE_PRESETS = [
("Multimedia codecs [RF]",
["gstreamer1-plugins-base", "gstreamer1-plugins-good",
"gstreamer1-plugins-bad-free", "gstreamer1-plugins-ugly",
"gstreamer1-plugin-openh264", "gstreamer1-plugins-bad-freeworld",
"ffmpeg"], True, True),
("FFmpeg [RF]", ["ffmpeg"], True, True),
("libavcodec [RF]", ["libavcodec-freeworld"], True, True),
("VLC [RF]", ["vlc"], True, True),
("DVD playback [RF]", ["libdvdcss"], True, True),
("Intel VA-API driver [RF]", ["intel-media-driver", "libva-utils"], True, False),
("AMD VA-API H.264/H.265 [RF]", ["mesa-va-drivers-freeworld", "libva-utils"], True, False),
("VA-API utils (vainfo) [RF]", ["libva-utils"], True, False),
("AMD ROCm OpenCL [RF]", ["rocm-opencl"], False, True),
("Steam [RF-NF]", ["steam"], True, True),
("Qemu/KVM", ["@virtualization"], False, False),
# ("htop + btop", ["htop", "btop"], False, False),
# ("zsh", ["zsh"], False, False),
# ("fish shell", ["fish"], False, False),
("Distrobox", ["distrobox"], False, False),
# ("fastfetch", ["fastfetch"], False, False),
# ("tmux", ["tmux"], False, False),
# ("vim", ["vim"], False, False),
# ("neovim", ["neovim"], False, False),
# ("bat", ["bat"], False, False),
# ("eza", ["eza"], False, False),
# ("ripgrep", ["ripgrep"], False, False),
# ("fd-find", ["fd-find"], False, False),
# ("jq", ["jq"], False, False),
]
# =============================================================================
# Shared UI helpers
# =============================================================================
def make_header(title: str, subtitle: str) -> Gtk.Box:
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
box.set_margin_bottom(16)
t = Gtk.Label(use_markup=True)
t.set_markup(f"<b><big>{GLib.markup_escape_text(title)}</big></b>")
t.set_xalign(0)
box.append(t)
s = Gtk.Label(label=subtitle)
s.set_xalign(0)
s.add_css_class("dim-label")
s.set_wrap(True)
box.append(s)
sep = Gtk.Separator()
sep.set_margin_top(8)
box.append(sep)
return box
def set_margins(widget, top=0, bottom=0, start=0, end=0):
widget.set_margin_top(top)
widget.set_margin_bottom(bottom)
widget.set_margin_start(start)
widget.set_margin_end(end)
def clear_listbox(lb: Gtk.ListBox):
while True:
row = lb.get_row_at_index(0)
if row is None:
break
lb.remove(row)
def clear_flowbox(fb: Gtk.FlowBox):
while True:
child = fb.get_child_at_index(0)
if child is None:
break
fb.remove(child)
def show_error(parent, text: str):
d = Gtk.MessageDialog(transient_for=parent, modal=True,
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.OK, text=text)
d.connect("response", lambda d, _: d.close())
d.present()
def _detect_deployed_tag() -> str | None:
"""
Read rpm-ostree status and return the image tag of the booted local image,
or None if the booted image is not a locally built containers-storage image.
Parses the booted line (marked with ●) and strips all ostree transport
prefixes to extract the bare image reference, e.g.:
● ostree-unverified-image:containers-storage:localhost/aurora-custom:latest
→ "localhost/aurora-custom:latest"
"""
try:
out = subprocess.check_output(
["rpm-ostree", "status"],
text=True, stderr=subprocess.DEVNULL, timeout=10
)
for line in out.splitlines():
if not line.startswith("●"):
continue
# Strip the leading bullet and whitespace
ref = line.lstrip("● ").strip()
# Strip all known ostree transport prefixes
for prefix in (
"ostree-unverified-image:",
"ostree-image-signed:",
"containers-storage:",
"docker://",
):
ref = ref.replace(prefix, "")
ref = ref.strip()
# Only use it if it looks like a local image tag
if ref.startswith("localhost/") and ":" in ref:
return ref
except Exception:
pass
return None
# =============================================================================
# Preferences
# =============================================================================
def _load_prefs() -> dict:
"""Load preferences from ~/bootc/aiw_prefs.json. Returns defaults if missing."""
defaults = {"kernel_check_enabled": False, "security_updates_enabled": False}
try:
with open(_PREFS_FILE) as f:
data = json.load(f)
defaults.update(data)
except (FileNotFoundError, json.JSONDecodeError, OSError):
pass
return defaults
def _save_prefs(prefs: dict) -> None:
"""Write preferences to ~/bootc/aiw_prefs.json."""
try:
with open(_PREFS_FILE, "w") as f:
json.dump(prefs, f, indent=2)
except OSError:
pass
# =============================================================================
# Kernel update check
# =============================================================================
def _get_running_kernel() -> str:
"""Return the running kernel version string from uname -r."""
try:
return subprocess.check_output(
["uname", "-r"], text=True, timeout=5
).strip()
except Exception:
return ""
def _get_fedora_release() -> str:
"""Return the current Fedora release number, e.g. '42'."""
try:
with open("/etc/os-release") as f:
for line in f:
if line.startswith("VERSION_ID="):
return line.split("=", 1)[1].strip().strip('"')
except Exception:
pass
return ""
def _parse_kernel_version(ver_str: str) -> tuple:
"""
Parse a kernel version string into a tuple for comparison.
e.g. '6.14.4-200.fc42.x86_64' -> (6, 14, 4, 200)
"""
nums = re.findall(r"\d+", ver_str)
try:
return tuple(int(n) for n in nums[:4])
except (ValueError, TypeError):
return (0,)
def _fetch_latest_fedora_kernel(release: str) -> str | None:
"""
Query the Bodhi API for the latest stable kernel version for the given
Fedora release. Returns the version string or None on failure.
"""
url = (
f"https://bodhi.fedoraproject.org/updates/"
f"?packages=kernel&status=stable&releases=F{release}&rows_per_page=5"
)
try:
req = urllib.request.Request(url, headers={"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=10) as r:
data = json.loads(r.read().decode())
updates = data.get("updates", [])
versions = []
for update in updates:
for build in update.get("builds", []):
nvr = build.get("nvr", "")
# nvr is like: kernel-6.14.4-200.fc42
m = re.match(r"^kernel-(.+)$", nvr)
if m:
versions.append(m.group(1))
if not versions:
return None
# Return the highest version
versions.sort(key=_parse_kernel_version, reverse=True)
return versions[0]
except (urllib.error.URLError, json.JSONDecodeError, OSError, KeyError):
return None
def _check_kernel_update_and_notify() -> None:
"""
Background thread: compare running kernel against latest Fedora stable.
Fires a notify-send desktop notification if a newer kernel is available.
"""
release = _get_fedora_release()
if not release:
return
running = _get_running_kernel()
if not running:
return
latest = _fetch_latest_fedora_kernel(release)
if not latest:
return
# Strip arch suffix from running kernel for fair comparison
# e.g. '6.13.9-200.fc42.x86_64' -> '6.13.9-200.fc42'
running_clean = re.sub(r"\.(x86_64|aarch64|i686)$", "", running)
running_ver = _parse_kernel_version(running_clean)
latest_ver = _parse_kernel_version(latest)
if latest_ver > running_ver:
body = (
f"Fedora {release} kernel {latest} is available.\n"
f"Your system is running {running_clean}.\n"
"Consider rebuilding your image."
)
try:
subprocess.Popen([
"notify-send",
"--app-name=Atomic Image Wizard",
"--icon=system-software-update",
"Kernel update available",
body,
])
except (FileNotFoundError, OSError):
pass # notify-send not available — silent fail
# =============================================================================
# Containerfile parser
# =============================================================================
class ContainerfileParser:
PERF_PKG_FLAGS = {
"cachyos-settings": "perf_cachyos_settings",
"cachyos-ksm-settings": "perf_ksm_settings",
"scx-scheds": "perf_scx_scheds",
"scx-tools": "perf_scx_scheds",
}
PERF_COPR = "bieszczaders/kernel-cachyos-addons"
SKIP_TOKENS = {"dnf5", "dnf", "install", "remove", "-y", "clean", "all", "&&", "\\",
"--allowerasing", "--skip-unavailable", "repoquery", "config-manager", "--add-repo"}
def __init__(self, path: str):
self.path = path
self.warnings = []
def parse_from(self) -> str:
try:
with open(self.path) as f:
for line in f:
line = line.strip()
if line.upper().startswith("FROM "):
return line[5:].strip()
except Exception as e:
self.warnings.append(f"Could not read Containerfile: {e}")
return ""
def apply_to_state(self, state) -> None:
try:
with open(self.path) as f:
text = f.read()
except Exception as e:
self.warnings.append(f"Could not read Containerfile: {e}")
return
self._validate(text)
flat = text.replace("\\\n", " ")
if "rpmfusion-free" in flat:
state.repos.add("RPM Fusion Free")
if "rpmfusion-nonfree" in flat:
state.repos.add("RPM Fusion Non-Free")
for m in re.finditer(r"^RUN (.+)$", flat, re.MULTILINE):
self._process_run(m.group(1).strip(), state)
def _validate(self, text: str):
stripped = text.strip()
if not stripped:
self.warnings.append("Containerfile is empty.")
return
has_from = any(
line.strip().upper().startswith("FROM ")
for line in stripped.splitlines()
)
if not has_from:
self.warnings.append("Containerfile has no FROM instruction.")
def _is_pkg_token(self, t: str) -> bool:
return (
bool(t)
and t not in self.SKIP_TOKENS
and not t.startswith("-")
and "://" not in t
and ".rpm" not in t
and "/" not in t
and "%" not in t
and not t.endswith(")")
and not t.startswith("'")
)
def _process_run(self, run_body: str, state) -> None:
cmds = [c.strip() for c in run_body.split("&&")]
recognised = False
for cmd in cmds:
cmd = cmd.strip()
if not cmd or cmd in ("dnf5 clean all", "dnf clean all"):
recognised = True
continue
recognised |= self._dispatch_cmd(cmd, state)
if not recognised:
self.warnings.append(
f"Unrecognised RUN command (skipped):\n {run_body[:120]}"
)
def _dispatch_cmd(self, cmd: str, state) -> bool:
if re.match(r"dnf5? install -y\b", cmd):
if "rpmfusion" in cmd:
return True
for token in cmd.split():
if not self._is_pkg_token(token):
continue
if token in self.PERF_PKG_FLAGS:
flag = self.PERF_PKG_FLAGS[token]
setattr(state, flag, True)
if flag == "perf_scx_scheds" and SCX_SERVICE not in state.systemd_enable:
state.systemd_enable.append(SCX_SERVICE)
elif token not in state.install_pkgs:
state.install_pkgs.append(token)
return True
if re.match(r"dnf5? remove -y\b", cmd):
for token in cmd.split():
if self._is_pkg_token(token) and token not in state.remove_pkgs:
state.remove_pkgs.append(token)
return True
if re.match(r"dnf5? copr enable\b", cmd):
repo = cmd.split()[-1]
if repo == self.PERF_COPR:
return True
if repo not in state.copr_repos:
state.copr_repos.append(repo)
return True
if "dnf5-command(copr)" in cmd or "dnf-command(copr)" in cmd:
return True
if re.match(r"systemctl enable\b", cmd):
svc = cmd.split()[-1]
if svc not in state.systemd_enable:
state.systemd_enable.append(svc)
return True
if re.match(r"systemctl disable\b", cmd):
svc = cmd.split()[-1]
if svc not in state.systemd_disable:
state.systemd_disable.append(svc)
return True
if (cmd.startswith("curl") or
cmd.startswith("rpm --import") or
cmd.startswith("rpm -i") or
cmd.startswith("dnf config-manager")):
if cmd not in state.custom_repos:
state.custom_repos.append(cmd)
return True
if cmd.startswith(("mkdir", "printf", "rm ")):
return True
return False
# =============================================================================
# Wizard state
# =============================================================================
class WizardState:
def __init__(self):
self.base_image = BASE_PRESETS[0]
self.repos = set()
self.custom_repos = []
self.copr_repos = []
self.install_pkgs = []
self.remove_pkgs = []
self.systemd_enable = []
self.systemd_disable = []
self.image_tag = self.derive_image_tag(BASE_PRESETS[0])
self.perf_cachyos_settings = False
self.perf_ksm_settings = False
self.perf_scx_scheds = False
@staticmethod
def derive_image_tag(base_image: str) -> str:
"""
Derive a localhost image tag from the base image reference.
Strips the registry and org prefix, then combines the image name and
upstream tag into the local name, with ':custom' as a fixed qualifier.
Examples:
ghcr.io/ublue-os/bazzite-nvidia-open:stable -> localhost/bazzite-nvidia-open-stable:custom
quay.io/fedora-ostree-desktops/cosmic-atomic:44 -> localhost/cosmic-atomic-44:custom
quay.io/fedora/fedora-bootc:latest -> localhost/fedora-bootc-latest:custom
"""
# Strip registry + org: take only the final path component
name_and_tag = base_image.rsplit("/", 1)[-1]
# Split on ':' — if no tag present fall back to 'unknown'
if ":" in name_and_tag:
name, tag = name_and_tag.rsplit(":", 1)
else:
name, tag = name_and_tag, "unknown"
return f"localhost/{name}-{tag}:custom"
def _fedora_ver(self) -> str:
m = re.search(r":(\d+)$", self.base_image)
if m:
return m.group(1)
# Non-numeric tags (rawhide, latest, stable) — fall back to current stable
# for RPM Fusion URL construction. Update when Fedora stable advances.
return "43"
def generate_containerfile(self) -> str:
DIVIDER = "# " + "\u2500" * 62
def section(n, title):
return [DIVIDER, f"# {n}. {title}", DIVIDER]
ver = self._fedora_ver()
out = [f"FROM {self.base_image}"]
PERF_PKGS = {"cachyos-settings", "cachyos-ksm-settings", "scx-scheds", "scx-tools"}
repo_parts = []
copr_repos = [r for r in self.copr_repos if r != "bieszczaders/kernel-cachyos-addons"]
if copr_repos:
repo_parts.append("dnf5 install -y --skip-unavailable 'dnf5-command(copr)'")
for repo in copr_repos:
repo_parts.append(f"dnf5 copr enable -y {repo}")
for cmd in self.custom_repos:
repo_parts.append(cmd)
if "RPM Fusion Free" in self.repos or "RPM Fusion Non-Free" in self.repos:
rpms = []
if "RPM Fusion Free" in self.repos:
rpms.append(RPM_FUSION_FREE_URL.format(ver=ver))
if "RPM Fusion Non-Free" in self.repos:
rpms.append(RPM_FUSION_NONFREE_URL.format(ver=ver))
rpm_lines = " \\\n ".join(rpms)
repo_parts.append("dnf5 install -y --skip-unavailable \\\n " + rpm_lines)
if repo_parts:
repo_parts.append("dnf5 clean all")
out.append("")
out += section(1, "Add external repositories")
out.append("RUN " + " \\\n && ".join(repo_parts))
install_list = [
p for p in self.install_pkgs
if "dnf-command" not in p and p not in PERF_PKGS
]
has_remove = bool(self.remove_pkgs)
has_install = bool(install_list)
if has_remove or has_install:
out.append("")
if has_remove and has_install:
out += section(2, "Remove unwanted defaults + install desired packages in one layer")
elif has_remove:
out += section(2, "Remove unwanted defaults")
else:
out += section(2, "Install desired packages")
run_parts = []
if has_remove:
pkgs = " \\\n ".join(sorted(self.remove_pkgs))
run_parts.append("dnf5 remove -y \\\n " + pkgs)
if has_install:
pkgs = " \\\n ".join(sorted(install_list))
run_parts.append("dnf5 install -y --skip-unavailable \\\n " + pkgs)
run_parts.append("dnf5 clean all")
out.append("RUN " + " \\\n && ".join(run_parts))
perf_pkgs = []
if self.perf_cachyos_settings:
perf_pkgs.append("cachyos-settings")
if self.perf_ksm_settings:
perf_pkgs.append("cachyos-ksm-settings")
if self.perf_scx_scheds:
perf_pkgs.extend(["scx-scheds", "scx-tools"])
if perf_pkgs:
out.append("")
out += section(3, "Performance tweaks (CachyOS addons \u2014 requires kernel 6.12+)")
perf_parts = [
"dnf5 install -y --skip-unavailable 'dnf5-command(copr)'",
"dnf5 copr enable -y bieszczaders/kernel-cachyos-addons",
"dnf5 install -y --allowerasing " + " \\\n ".join(perf_pkgs),
"dnf5 clean all",
]
if self.perf_scx_scheds:
cfg = 'default_sched = "scx_bpfland"\\ndefault_mode = "Auto"\\n'
perf_parts.append(
"mkdir -p /etc/scx_loader"
" && printf '" + cfg + "' > /etc/scx_loader/config.toml"
)
out.append("RUN " + " \\\n && ".join(perf_parts))
if _load_prefs().get("security_updates_enabled", False):
out.append("")
out += section(3 if not perf_pkgs else 4, "Security updates")
out.append("RUN dnf5 update --security -y \\\n && dnf5 clean all")
enable = [s for s in self.systemd_enable if s != SCX_SERVICE]
disable = list(self.systemd_disable)
if self.perf_scx_scheds:
enable.append(SCX_SERVICE)
cleanup = []
if not self.perf_scx_scheds:
cleanup.append("rm -rf /etc/scx_loader")
if enable or disable or cleanup:
out.append("")
out += section(4, "Enable / disable services")
parts = [f"systemctl enable {s}" for s in enable]
parts += [f"systemctl disable {s}" for s in disable]
parts += cleanup
out.append("RUN " + " \\\n && ".join(parts))
out.append("")
return "\n".join(out)
def validate_for_build(self) -> list[str]:
issues = []
if not self.base_image.strip():
issues.append("No base image specified (Step 1).")
if not self.image_tag.strip():
issues.append("No image tag specified (Review page).")
if self.perf_scx_scheds and SCX_SERVICE not in self.systemd_enable:
issues.append(
"SCX scheduler is enabled but scx_loader.service is not in the enable list."
)
return issues
# =============================================================================
# PAGE 0 - Landing
# =============================================================================
class PageLanding(Gtk.Box):
def __init__(self, state: WizardState, cf_path: str):
super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=0)
self.state = state
self.cf_path = cf_path
set_margins(self, top=0, bottom=0, start=0, end=0)
parser = ContainerfileParser(cf_path)
self._base = parser.parse_from()
outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
outer.set_vexpand(True)
outer.set_hexpand(True)
inner = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=28)
inner.set_halign(Gtk.Align.CENTER)
inner.set_valign(Gtk.Align.START)
set_margins(inner, top=48, bottom=32, start=60, end=60)
title = Gtk.Label()
title.set_markup("<b><big>Atomic Image Wizard</big></b>")
title.set_halign(Gtk.Align.CENTER)
inner.append(title)
found_lbl = Gtk.Label()
found_lbl.set_markup(
"An existing build was found.\n"
f"Base image: <tt>{GLib.markup_escape_text(self._base or '(unknown)')}</tt>"
)
found_lbl.set_halign(Gtk.Align.CENTER)
found_lbl.add_css_class("dim-label")
found_lbl.set_wrap(True)
inner.append(found_lbl)
btn_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
btn_box.set_halign(Gtk.Align.CENTER)
def make_option(title_text, subtitle_text, primary=False, destructive=False):
frame = Gtk.Frame()
frame.set_size_request(460, -1)
frame.add_css_class("card")
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=3)
set_margins(vbox, top=14, bottom=14, start=20, end=20)
t = Gtk.Label()
t.set_markup(f"<b>{GLib.markup_escape_text(title_text)}</b>")
t.set_xalign(0)
if primary:
t.add_css_class("accent")
elif destructive:
t.add_css_class("error")
s = Gtk.Label(label=subtitle_text)
s.set_xalign(0)
s.add_css_class("dim-label")
s.set_wrap(True)
vbox.append(t)
vbox.append(s)
btn = Gtk.Button()
btn.set_child(frame)
btn.set_has_frame(False)
frame.set_child(vbox)
return btn
upgrade_btn = make_option(
"Update Image",
"Rebuild the existing image as-is using the current Containerfile.",
primary=True
)
upgrade_btn.connect("clicked", self._do_upgrade)
btn_box.append(upgrade_btn)
switch_btn = make_option(
"Switch Image",
"Change the base image — upgrade to a new Fedora release or try a different spin."
)
switch_btn.connect("clicked", self._do_switch_image)
btn_box.append(switch_btn)
add_btn = make_option(
"Add Software",
"Load the existing build and jump to Repositories to add or change software."
)
add_btn.connect("clicked", self._do_add_software)
btn_box.append(add_btn)
new_btn = make_option(
"New Build",
"Start completely fresh with a new base image and clean settings.",
destructive=True
)
new_btn.connect("clicked", self._do_new_build)
btn_box.append(new_btn)
inner.append(btn_box)
cleanup_sep = Gtk.Separator()
cleanup_sep.set_margin_top(8)
cleanup_sep.set_margin_bottom(4)
inner.append(cleanup_sep)
cleanup_label = Gtk.Label()
cleanup_label.set_markup("<b>Disk Cleanup Utilities</b>")
cleanup_label.set_halign(Gtk.Align.CENTER)
cleanup_label.set_hexpand(True)
inner.append(cleanup_label)
cleanup_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
cleanup_box.set_halign(Gtk.Align.CENTER)
prune_cache_btn = Gtk.Button(label="\U0001f5d1 Clean build cache")
prune_cache_btn.connect("clicked", self._run_cleanup,
"podman builder prune -f",
"Clean Build Cache",
"Removes dangling intermediate layers left over from repeated builds.\n"
"Your named images (e.g. localhost/atomic-custom:latest) are NOT affected."
)
cleanup_box.append(prune_cache_btn)
prune_images_btn = Gtk.Button(label="\U0001f5d1 Clean unused images")