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
use dialoguer::theme::ColorfulTheme;
use dialoguer::Select;
use dialoguer::{console::Term, Confirm};
use indicatif::ProgressBar;
use serde::Deserialize;
use std::io::{BufRead, BufReader};
use std::num::NonZeroUsize;
use std::{
os::unix,
path::{Path, PathBuf},
process::{Command, Stdio},
time::Duration,
};
mod error;
pub use error::BuilderErr;
#[derive(Debug, Deserialize)]
pub struct KBConfig {
#[serde(rename = "kernel")]
pub kernel_file_path: PathBuf,
#[serde(rename = "initramfs")]
pub initramfs_file_path: Option<PathBuf>,
#[serde(rename = "kernel-config")]
pub kernel_config_file_path: PathBuf,
#[serde(rename = "kernel-src")]
pub kernel_src: PathBuf,
}
#[derive(Clone, Debug)]
struct VersionEntry {
path: PathBuf,
version_string: String,
}
#[derive(Debug)]
pub struct KernelBuilder {
config: KBConfig,
versions: Vec<VersionEntry>,
}
impl KernelBuilder {
pub const LINUX_PATH: &str = "/usr/src";
#[must_use]
pub fn new(config: KBConfig) -> Self {
let mut builder = Self {
config,
versions: vec![],
};
builder.get_available_version();
builder
}
fn get_available_version(&mut self) {
if self.versions.is_empty() {
if let Ok(directories) = std::fs::read_dir(&self.config.kernel_src) {
self.versions = directories
.filter_map(Result::ok)
.map(|dir| dir.path())
.filter(|path| path.starts_with(&self.config.kernel_src) && !path.is_symlink())
.filter_map(|path| {
path.strip_prefix(&self.config.kernel_src)
.ok()
.and_then(|p| {
let tmp = p.to_owned();
let version_string = tmp.to_string_lossy();
version_string
.starts_with("linux-")
.then_some(VersionEntry {
path: path.clone(),
version_string: version_string.to_string(),
})
})
})
.collect::<Vec<_>>();
}
}
}
pub fn build(&self) -> Result<(), BuilderErr> {
let version_entry = self.prompt_for_kernel_version();
let VersionEntry {
path,
version_string,
} = &version_entry;
let link = path.join(".config");
if !link.exists() {
let dot_config = &self.config.kernel_config_file_path;
if !dot_config.exists() || !dot_config.is_file() {
return Err(BuilderErr::KernelConfigMissing);
}
unix::fs::symlink(dot_config, link).map_err(|err| BuilderErr::LinkingFileError(err))?;
}
let linux = PathBuf::from(&self.config.kernel_src).join("linux");
let linux_target = linux
.read_link()
.map_err(|err| BuilderErr::LinkingFileError(err))?;
if linux_target.to_string_lossy() != *version_string {
std::fs::remove_file(&linux).map_err(|err| BuilderErr::LinkingFileError(err))?;
unix::fs::symlink(path, linux).map_err(|err| BuilderErr::LinkingFileError(err))?;
}
self.build_kernel(path)?;
if self.confirm_prompt("Do you want to install kernel modules?")? {
self.install_kernel_modules(path)?;
}
#[cfg(feature = "dracut")]
if self.confirm_prompt("Do you want to generate initramfs with dracut?")? {
self.generate_initramfs(&version_entry)?;
}
Ok(())
}
fn build_kernel(&self, path: &Path) -> Result<(), BuilderErr> {
let threads: NonZeroUsize =
std::thread::available_parallelism().unwrap_or(NonZeroUsize::new(1).unwrap());
let pb = ProgressBar::new_spinner();
pb.enable_steady_tick(Duration::from_millis(120));
let mut cmd = Command::new("make")
.current_dir(path)
.args(["-j", &threads.to_string()])
.stdout(Stdio::piped())
.spawn()
.map_err(|err| BuilderErr::KernelBuildFail(err))?;
{
let stdout = cmd.stdout.as_mut().unwrap();
let stdout_reader = BufReader::new(stdout);
let stdout_lines = stdout_reader.lines();
for line in stdout_lines {
pb.set_message(format!(
"Compiling kernel: {}",
line.map_err(|err| BuilderErr::KernelBuildFail(err))?
));
}
}
cmd.wait().map_err(|err| BuilderErr::KernelBuildFail(err))?;
pb.finish_with_message("Finished compiling Kernel");
std::fs::copy(
path.join("arch/x86/boot/bzImage"),
self.config.kernel_file_path.clone(),
)
.map_err(|err| BuilderErr::KernelBuildFail(err))?;
Ok(())
}
fn install_kernel_modules(&self, path: &Path) -> Result<(), BuilderErr> {
let pb = ProgressBar::new_spinner();
pb.enable_steady_tick(Duration::from_millis(120));
pb.set_message("Install kernel modules");
Command::new("make")
.current_dir(path)
.arg("modules_install")
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.map_err(|err| BuilderErr::KernelBuildFail(err))?
.wait()
.map_err(|err| BuilderErr::KernelBuildFail(err))?;
pb.finish_with_message("Finished installing modules");
Ok(())
}
#[cfg(feature = "dracut")]
fn generate_initramfs(
&self,
VersionEntry {
path,
version_string,
}: &VersionEntry,
) -> Result<(), BuilderErr> {
let pb = ProgressBar::new_spinner();
pb.enable_steady_tick(Duration::from_millis(120));
let initramfs_file_path = &self
.config
.initramfs_file_path.clone()
.ok_or(BuilderErr::KernelConfigMissingOption("initramfs".into()))?;
let mut cmd = Command::new("dracut")
.current_dir(path)
.args([
"--hostonly",
"--kver",
version_string.strip_prefix("linux-").unwrap(),
"--force",
initramfs_file_path.to_string_lossy().as_ref(),
])
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|err| BuilderErr::KernelBuildFail(err))?;
{
let stdout = cmd.stdout.as_mut().unwrap();
let stdout_reader = BufReader::new(stdout);
let stdout_lines = stdout_reader.lines();
for line in stdout_lines {
pb.set_message(format!(
"Generating initramfs: {}",
line.map_err(|err| BuilderErr::KernelBuildFail(err))?
));
}
}
cmd.wait().map_err(|err| BuilderErr::KernelBuildFail(err))?;
pb.finish_with_message("Finished initramfs");
Ok(())
}
fn prompt_for_kernel_version(&self) -> VersionEntry {
let versions = self
.versions
.clone()
.into_iter()
.map(|v| v.version_string)
.collect::<Vec<_>>();
let selection = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Pick version to build and install")
.items(versions.as_slice())
.default(0)
.interact_on_opt(&Term::stderr())
.unwrap()
.unwrap();
self.versions[selection].clone()
}
fn confirm_prompt(&self, message: &str) -> Result<bool, BuilderErr> {
Confirm::new()
.with_prompt(message)
.interact()
.map_err(|err| BuilderErr::PromptError(err))
}
}