Skip to main content

isothrum_machine/install/linux/scripts/
dnf.rs

1//! The root scripts behind the installs on Fedora and the distributions built on it: dnf, the
2//! vendors' rpm repositories (their keys pinned) and RPM Fusion's VirtualBox.
3
4#[cfg(test)]
5use super::{NEED_CURL, NEED_UNZIP};
6use super::{NEED_GPG, RootScript, check_keys, dnf_install_with_helpers, fetch_prelude, then_kvm_group, then_libvirt_groups, valid_user};
7use crate::providers::Provider;
8
9/// A vendor's rpm repository, set up the same way for every vendor ([`rpm_repo_setup`]): its
10/// signing key downloaded and checked against the pinned fingerprint, kept under
11/// `/etc/pki/rpm-gpg` and imported, then a repo file under `/etc/yum.repos.d` that trusts that
12/// key alone (`gpgcheck=1`). `RELEASE` in the base URL is the Fedora release the repository is
13/// read for: this one, else the newest earlier one it serves (HashiCorp serves a new Fedora
14/// release weeks after it ships), else the refusal, as the apt repositories' `release_served`.
15struct RpmRepo {
16    vendor: &'static str,
17    fingerprint: &'static str,
18    key_url: &'static str,
19    /// The base URL with `RELEASE` for the Fedora release and `$basearch` for dnf's architecture.
20    baseurl: &'static str,
21    /// The key file's and the repo file's name.
22    name: &'static str,
23    /// Where to install from instead when the repository serves no release near this one.
24    by_hand: &'static str,
25}
26
27/// `rpm_served <base url>`: whether an rpm repository at that URL answers (its `repodata/repomd.xml`):
28/// a 2xx is yes and a 404 no; anything else stops the script (an unreachable server is never "no
29/// packages"), as [`RELEASE_SERVED`](super::RELEASE_SERVED) does for apt.
30const RPM_SERVED: &str = r#"rpm_served() { served=$(curl -s -o /dev/null -w '%{http_code}' "$1/repodata/repomd.xml" || true); case "$served" in 2??) return 0 ;; 404) return 1 ;; *) echo "Couldn't reach $1 (HTTP $served). Check this machine's internet access or proxy, then try again." >&2; exit 1 ;; esac; }"#;
31
32/// The script that sets `r` up for dnf, after [`fetch_prelude`] in a [`RootScript`]: the
33/// release the repository serves found (`$rel`, this Fedora's or the newest earlier one of the
34/// three), the key checked and imported, the repo file written.
35fn rpm_repo_setup(r: &RpmRepo) -> String {
36    let RpmRepo {
37        vendor,
38        fingerprint,
39        key_url,
40        baseurl,
41        name,
42        by_hand,
43    } = r;
44    let probe = baseurl.replace("$basearch", "$(uname -m)");
45    format!(
46        r#"{RPM_SERVED}; this=$(rpm -E %fedora); rel=""; for r in "$this" $((this - 1)) $((this - 2)); do if rpm_served "{probe_r}"; then rel=$r; break; fi; done; [ -n "$rel" ] || {{ echo "{vendor} has no packages for Fedora $this yet. Install it from {by_hand}" >&2; exit 1; }}; [ "$rel" = "$this" ] || echo "{vendor} has no packages for Fedora $this: installing its Fedora $rel ones."; {NEED_GPG}; curl -fsSL "{key_url}" -o "$d/key"; {check}; install -m 0644 "$d/key" /etc/pki/rpm-gpg/RPM-GPG-KEY-{name}; rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-{name}; printf '[{name}]\nname={vendor}\nbaseurl=%s\nenabled=1\ngpgcheck=1\ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-{name}\n' "{base_rel}" >/etc/yum.repos.d/{name}.repo"#,
47        probe_r = probe.replace("RELEASE", "$r"),
48        // The release found expands; dnf's own `$basearch` stays for dnf.
49        base_rel = baseurl.replace("$basearch", "\\$basearch").replace("RELEASE", "$rel"),
50        check = check_keys(&[fingerprint], vendor),
51    )
52}
53
54/// Docker's rpm repository for Fedora, its key pinned (`docker@docker.com`, the key
55/// download.docker.com/linux/fedora/gpg serves; not the apt one).
56const DOCKER_RPM: RpmRepo = RpmRepo {
57    vendor: "Docker",
58    fingerprint: "060A61C51B558A7F742B77AAC52FEB6B621E9F35",
59    key_url: "https://download.docker.com/linux/fedora/gpg",
60    baseurl: "https://download.docker.com/linux/fedora/RELEASE/$basearch/stable",
61    name: "docker-ce",
62    by_hand: "https://docs.docker.com/engine/install/fedora/",
63};
64
65/// HashiCorp's rpm repository (Vagrant, Terraform), signed by the same key as its apt one.
66const HASHICORP_RPM: RpmRepo = RpmRepo {
67    vendor: "HashiCorp",
68    fingerprint: "D55C0D1AC78A8D8126CB631CFC9CA96ACA026560",
69    key_url: "https://rpm.releases.hashicorp.com/gpg",
70    baseurl: "https://rpm.releases.hashicorp.com/fedora/RELEASE/$basearch/stable",
71    name: "hashicorp",
72    by_hand: "https://developer.hashicorp.com/vagrant/install",
73};
74
75/// Docker Engine on Fedora from Docker's own repository, its key pinned, then its service on;
76/// the user joins the `docker` group as on Debian.
77#[must_use]
78pub fn docker_dnf_script(user: Option<&str>) -> RootScript {
79    let mut s = format!(
80        "{}; {}; dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin; systemctl enable --now docker",
81        fetch_prelude(),
82        rpm_repo_setup(&DOCKER_RPM)
83    );
84    if let Some(u) = user.filter(|u| valid_user(u)) {
85        s = format!("{s}; usermod -aG docker {u}; echo 'Added {u} to the docker group: log out and back in (or restart) for it to apply.'");
86    }
87    RootScript::new(s)
88}
89
90/// Vagrant on Fedora from HashiCorp's rpm repository (the distribution has none).
91#[must_use]
92pub fn vagrant_dnf_script() -> RootScript {
93    RootScript::new(format!("{}; {}; dnf install -y vagrant", fetch_prelude(), rpm_repo_setup(&HASHICORP_RPM)))
94}
95
96/// Terraform on Fedora from the same repository.
97#[must_use]
98pub fn terraform_dnf_script() -> RootScript {
99    RootScript::new(format!("{}; {}; dnf install -y terraform", fetch_prelude(), rpm_repo_setup(&HASHICORP_RPM)))
100}
101
102/// VirtualBox on Fedora from RPM Fusion (Oracle's own repository lags the Fedora releases by
103/// months), its kernel module built here for the running kernel (akmods),
104/// then the user into `vboxusers`. RPM Fusion's release package carries its signing key, which
105/// dnf imports as it installs it.
106#[must_use]
107pub fn virtualbox_dnf_script(user: Option<&str>) -> RootScript {
108    let mut s = r#"dnf install -y "https://mirrors.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm"; dnf install -y VirtualBox akmod-VirtualBox "kernel-devel-$(uname -r)" kernel-headers; akmods --force --kernels "$(uname -r)"; modprobe vboxdrv || echo "VirtualBox's driver isn't loaded yet: restart the computer to start it, and VirtualBox's driver is built then.""#.to_owned();
109    if let Some(u) = user.filter(|u| valid_user(u)) {
110        s = format!("{s}; usermod -aG vboxusers {u}");
111    }
112    RootScript::new(s)
113}
114
115/// libvirt on Fedora with what vagrant-libvirt builds against (libvirt's headers, a C compiler,
116/// pkg-config, Ruby's headers) and the programs its VMs need beside it (virtiofsd, for the shared
117/// folders), its service on, then the user into the `libvirt` group (and the KVM device's).
118#[must_use]
119pub fn libvirt_dnf_script(user: Option<&str>) -> RootScript {
120    let install = dnf_install_with_helpers(
121        Provider::Libvirt,
122        "libvirt libvirt-daemon-kvm qemu-kvm virt-install virt-manager libvirt-devel gcc make pkgconf-pkg-config ruby-devel",
123    );
124    then_libvirt_groups(&format!("{install}; systemctl enable --now libvirtd"), user)
125}
126
127/// QEMU and its disk tools on Fedora, with the programs its VMs need beside it (`genisoimage` for
128/// vagrant-qemu's cloud-init seeds, `virtiofsd` for its shared folders), then the user into the
129/// KVM device's group.
130#[must_use]
131pub fn qemu_dnf_script(user: Option<&str>) -> RootScript {
132    then_kvm_group(&dnf_install_with_helpers(Provider::Qemu, "qemu-kvm qemu-img"), user)
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn every_dnf_script_is_valid_sh_and_installs_through_dnf_alone() {
141        for (name, s) in [
142            ("docker", docker_dnf_script(Some("alice"))),
143            ("vagrant", vagrant_dnf_script()),
144            ("terraform", terraform_dnf_script()),
145            ("virtualbox", virtualbox_dnf_script(Some("alice"))),
146            ("libvirt", libvirt_dnf_script(Some("alice"))),
147            ("qemu", qemu_dnf_script(Some("alice"))),
148        ] {
149            assert!(crate::testing::sh_parses(&s), "{name}: not valid sh: {s}");
150            // The preludes install curl and gpg through whichever manager is there; the rest is dnf's.
151            let own = s.replace(NEED_CURL, "").replace(NEED_GPG, "").replace(NEED_UNZIP, "");
152            assert!(!own.contains("apt-get"), "{name} installs through apt: {s}");
153            assert!(s.contains("dnf install -y"), "{name}: {s}");
154        }
155    }
156
157    #[test]
158    fn a_vendors_rpm_repository_is_pinned_by_key_and_read_for_a_release_it_serves() {
159        let s = rpm_repo_setup(&HASHICORP_RPM);
160        assert!(s.contains(r#"[ "$k" = "D55C0D1AC78A8D8126CB631CFC9CA96ACA026560" ]"#), "the key pinned: {s}");
161        assert!(
162            s.contains("rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-hashicorp")
163                && s.contains("gpgcheck=1")
164                && s.contains("gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-hashicorp"),
165            "{s}"
166        );
167        assert!(
168            s.contains(r#"for r in "$this" $((this - 1)) $((this - 2))"#)
169                && s.contains(r#"rpm_served "https://rpm.releases.hashicorp.com/fedora/$r/$(uname -m)/stable""#),
170            "this release, else the two before: {s}"
171        );
172        assert!(
173            s.contains(r#""https://rpm.releases.hashicorp.com/fedora/$rel/\$basearch/stable""#),
174            "the release found, dnf's own $basearch: {s}"
175        );
176        assert!(
177            s.contains("HashiCorp has no packages for Fedora $this yet. Install it from https://developer.hashicorp.com/vagrant/install"),
178            "{s}"
179        );
180        let docker = rpm_repo_setup(&DOCKER_RPM);
181        assert!(
182            docker.contains("060A61C51B558A7F742B77AAC52FEB6B621E9F35") && docker.contains("/etc/yum.repos.d/docker-ce.repo"),
183            "{docker}"
184        );
185    }
186
187    #[cfg(unix)]
188    #[test]
189    fn a_release_the_repository_doesnt_serve_falls_back_to_the_newest_earlier_one() {
190        // HashiCorp serving Fedora 44 and not yet 45.
191        let s = rpm_repo_setup(&HASHICORP_RPM);
192        let head = s.get(..s.find("; command -v gpg").unwrap()).unwrap();
193        let bin = crate::testing::fresh_dir("rpm-probe");
194        std::fs::create_dir_all(&bin).unwrap();
195        crate::testing::write_executable(
196            bin.join("curl"),
197            "#!/bin/sh\ncase \"$*\" in */fedora/44/*) printf 200 ;; *) printf 404 ;; esac\n",
198        );
199        crate::testing::write_executable(bin.join("rpm"), "#!/bin/sh\necho 45\n");
200        let out = crate::testing::sh(
201            &format!("set -e; {head}; echo \"rel=$rel\""),
202            &[("PATH", &format!("{}:/usr/bin:/bin", bin.display()))],
203        );
204        std::fs::remove_dir_all(&bin).unwrap();
205        let stdout = String::from_utf8_lossy(&out.stdout);
206        assert!(
207            stdout.contains("HashiCorp has no packages for Fedora 45: installing its Fedora 44 ones.") && stdout.trim_end().ends_with("rel=44"),
208            "{stdout}"
209        );
210    }
211
212    #[test]
213    fn virtualbox_on_fedora_comes_from_rpm_fusion_with_its_module_built_here() {
214        let s = virtualbox_dnf_script(Some("alice"));
215        assert!(
216            s.contains("rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm")
217                && s.contains("akmod-VirtualBox")
218                && s.contains("akmods --force")
219                && s.contains("usermod -aG vboxusers alice"),
220            "{s}"
221        );
222    }
223}