forked from nix-community/nh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnixos.rs
More file actions
803 lines (702 loc) · 22.8 KB
/
nixos.rs
File metadata and controls
803 lines (702 loc) · 22.8 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
use std::{
env,
fs,
path::{Path, PathBuf},
};
use color_eyre::eyre::{Context, Result, bail, eyre};
use tracing::{debug, info, warn};
use crate::{
commands,
commands::{Command, ElevationStrategy},
generations,
installable::Installable,
interface::{
self,
DiffType,
OsBuildVmArgs,
OsGenerationsArgs,
OsRebuildArgs,
OsReplArgs,
OsRollbackArgs,
OsSubcommand::{self},
},
update::update,
util::{ensure_ssh_key_login, get_hostname, print_dix_diff},
};
const SYSTEM_PROFILE: &str = "/nix/var/nix/profiles/system";
const CURRENT_PROFILE: &str = "/run/current-system";
const SPEC_LOCATION: &str = "/etc/specialisation";
impl interface::OsArgs {
pub fn run(self, elevation: ElevationStrategy) -> Result<()> {
use OsRebuildVariant::{Boot, Build, Switch, Test};
match self.subcommand {
OsSubcommand::Boot(args) => args.rebuild(&Boot, None, elevation),
OsSubcommand::Test(args) => args.rebuild(&Test, None, elevation),
OsSubcommand::Switch(args) => args.rebuild(&Switch, None, elevation),
OsSubcommand::Build(args) => {
if args.common.ask || args.common.dry {
warn!("`--ask` and `--dry` have no effect for `nh os build`");
}
args.rebuild(&Build, None, elevation)
},
OsSubcommand::BuildVm(args) => args.build_vm(elevation),
OsSubcommand::Repl(args) => args.run(),
OsSubcommand::Info(args) => args.info(),
OsSubcommand::Rollback(args) => args.rollback(elevation),
}
}
}
#[derive(Debug)]
enum OsRebuildVariant {
Build,
Switch,
Boot,
Test,
BuildVm,
}
impl OsBuildVmArgs {
fn build_vm(self, elevation: ElevationStrategy) -> Result<()> {
let final_attr = get_final_attr(true, self.with_bootloader);
debug!("Building VM with attribute: {}", final_attr);
self
.common
.rebuild(&OsRebuildVariant::BuildVm, Some(final_attr), elevation)
}
}
impl OsRebuildArgs {
// final_attr is the attribute of config.system.build.X to evaluate.
#[expect(clippy::cognitive_complexity, clippy::too_many_lines)]
fn rebuild(
self,
variant: &OsRebuildVariant,
final_attr: Option<String>,
elevation: ElevationStrategy,
) -> Result<()> {
use OsRebuildVariant::{Boot, Build, BuildVm, Switch, Test};
if self.build_host.is_some() || self.target_host.is_some() {
// if it fails its okay
let _ = ensure_ssh_key_login();
}
let elevate = if self.bypass_root_check {
warn!("Bypassing root check, now running nix as root");
false
} else {
if nix::unistd::Uid::effective().is_root() {
bail!("Don't run nh os as root. I will call sudo internally as needed");
}
true
};
if self.update_args.update_all || self.update_args.update_input.is_some() {
update(&self.common.installable, self.update_args.update_input)?;
}
let system_hostname = match get_hostname() {
Ok(hostname) => Some(hostname),
Err(err) => {
tracing::warn!("{}", err.to_string());
None
},
};
let target_hostname = match &self.hostname {
Some(h) => h.to_owned(),
None => {
match &system_hostname {
Some(hostname) => {
// Only show the warning if we're explicitly building a VM
// by directly calling build_vm(), not when the BuildVm variant
// is used internally via other code paths
if matches!(variant, OsRebuildVariant::BuildVm)
&& final_attr
.as_deref()
.is_some_and(|attr| attr == "vm" || attr == "vmWithBootLoader")
{
tracing::warn!(
"Guessing system is {hostname} for a VM image. If this isn't \
intended, use --hostname to change."
);
}
hostname.clone()
},
None => {
return Err(eyre!(
"Unable to fetch hostname, and no hostname supplied."
));
},
}
},
};
let (out_path, _tempdir_guard): (PathBuf, Option<tempfile::TempDir>) =
match self.common.out_link {
Some(ref p) => (p.clone(), None),
None => {
match variant {
BuildVm | Build => (PathBuf::from("result"), None),
_ => {
let dir = tempfile::Builder::new().prefix("nh-os").tempdir()?;
(dir.as_ref().join("result"), Some(dir))
},
}
},
};
debug!("Output path: {out_path:?}");
// Use NH_OS_FLAKE if available, otherwise use the provided installable
let installable = if let Ok(os_flake) = env::var("NH_OS_FLAKE") {
debug!("Using NH_OS_FLAKE: {}", os_flake);
let mut elems = os_flake.splitn(2, '#');
let reference = elems
.next()
.ok_or_else(|| eyre!("NH_OS_FLAKE missing reference part"))?
.to_owned();
let attribute = elems
.next()
.map(crate::installable::parse_attribute)
.unwrap_or_default();
Installable::Flake {
reference,
attribute,
}
} else {
self.common.installable.clone()
};
let toplevel = toplevel_for(
&target_hostname,
installable,
final_attr.unwrap_or(String::from("toplevel")).as_str(),
);
let message = match variant {
BuildVm => "Building NixOS VM image",
_ => "Building NixOS configuration",
};
commands::Build::new(toplevel)
.extra_arg("--out-link")
.extra_arg(&out_path)
.extra_args(&self.extra_args)
.passthrough(&self.common.passthrough)
.builder(self.build_host.clone())
.message(message)
.nom(!self.common.no_nom)
.run()
.wrap_err("Failed to build configuration")?;
let current_specialisation = std::fs::read_to_string(SPEC_LOCATION).ok();
let target_specialisation = if self.no_specialisation {
None
} else {
current_specialisation.or_else(|| self.specialisation.clone())
};
debug!("Target specialisation: {target_specialisation:?}");
let target_profile = match &target_specialisation {
None => out_path.clone(),
Some(spec) => out_path.join("specialisation").join(spec),
};
debug!("Output path: {out_path:?}");
debug!("Target profile path: {}", target_profile.display());
debug!("Target profile exists: {}", target_profile.exists());
if !target_profile
.try_exists()
.context("Failed to check if target profile exists")?
{
return Err(eyre!(
"Target profile path does not exist: {}",
target_profile.display()
));
}
match self.common.diff {
DiffType::Always => {
let _ =
print_dix_diff(&PathBuf::from(CURRENT_PROFILE), &target_profile);
},
DiffType::Never => {
debug!("Not running dix as the --diff flag is set to never.");
},
DiffType::Auto => {
if system_hostname.is_none_or(|h| h == target_hostname)
&& self.target_host.is_none()
&& self.build_host.is_none()
{
debug!(
"Comparing with target profile: {}",
target_profile.display()
);
let _ =
print_dix_diff(&PathBuf::from(CURRENT_PROFILE), &target_profile);
} else {
debug!(
"Not running dix as the target hostname is different from the \
system hostname."
);
}
},
}
if self.common.dry || matches!(variant, Build | BuildVm) {
if self.common.ask {
warn!("--ask has no effect as dry run was requested");
}
return Ok(());
}
if self.common.ask {
let confirmation = inquire::Confirm::new("Apply the config?")
.with_default(false)
.prompt()?;
if !confirmation {
bail!("User rejected the new config");
}
}
if let Some(target_host) = &self.target_host {
Command::new("nix")
.args([
"copy",
"--to",
format!("ssh://{target_host}").as_str(),
match target_profile.to_str() {
Some(s) => s,
None => {
return Err(eyre!("target_profile path is not valid UTF-8"));
},
},
])
.message("Copying configuration to target")
.with_required_env()
.run()?;
}
if let Test | Switch = variant {
let switch_to_configuration =
target_profile.join("bin").join("switch-to-configuration");
if !switch_to_configuration.exists() {
return Err(eyre!(
"The 'switch-to-configuration' binary is missing from the built \
configuration.\n\nThis typically happens when \
'system.switch.enable' is set to false in your\nNixOS \
configuration. To fix this, please either:\n1. Remove \
'system.switch.enable = false' from your configuration, or\n2. Set \
'system.switch.enable = true' explicitly\n\nIf the problem \
persists, please open an issue on our issue tracker!"
));
}
let switch_to_configuration = switch_to_configuration
.canonicalize()
.context("Failed to resolve switch-to-configuration path")?;
let switch_to_configuration =
switch_to_configuration.to_str().ok_or_else(|| {
eyre!("switch-to-configuration path contains invalid UTF-8")
})?;
Command::new(switch_to_configuration)
.arg("test")
.ssh(self.target_host.clone())
.message("Activating configuration")
.elevate(elevate.then_some(elevation.clone()))
.preserve_envs(["NIXOS_INSTALL_BOOTLOADER"])
.with_required_env()
.run()
.wrap_err("Activation (test) failed")?;
}
if let Boot | Switch = variant {
let canonical_out_path = out_path
.canonicalize()
.context("Failed to resolve output path")?;
Command::new("nix")
.elevate(elevate.then_some(elevation.clone()))
.args(["build", "--no-link", "--profile", SYSTEM_PROFILE])
.arg(&canonical_out_path)
.ssh(self.target_host.clone())
.with_required_env()
.run()
.wrap_err("Failed to set system profile")?;
let switch_to_configuration =
out_path.join("bin").join("switch-to-configuration");
if !switch_to_configuration.exists() {
return Err(eyre!(
"The 'switch-to-configuration' binary is missing from the built \
configuration.\n\nThis typically happens when \
'system.switch.enable' is set to false in your\nNixOS \
configuration. To fix this, please either:\n1. Remove \
'system.switch.enable = false' from your configuration, or\n2. Set \
'system.switch.enable = true' explicitly\n\nIf the problem \
persists, please open an issue on our issue tracker!"
));
}
let switch_to_configuration = switch_to_configuration
.canonicalize()
.context("Failed to resolve switch-to-configuration path")?;
let switch_to_configuration =
switch_to_configuration.to_str().ok_or_else(|| {
eyre!("switch-to-configuration path contains invalid UTF-8")
})?;
Command::new(switch_to_configuration)
.arg("boot")
.ssh(self.target_host)
.elevate(elevate.then_some(elevation))
.message("Adding configuration to bootloader")
.preserve_envs(["NIXOS_INSTALL_BOOTLOADER"])
.with_required_env()
.run()
.wrap_err("Bootloader activation failed")?;
}
debug!("Completed operation with output path: {out_path:?}");
Ok(())
}
}
impl OsRollbackArgs {
fn rollback(&self, elevation: ElevationStrategy) -> Result<()> {
let elevate = if self.bypass_root_check {
warn!("Bypassing root check, now running nix as root");
false
} else {
if nix::unistd::Uid::effective().is_root() {
bail!("Don't run nh os as root. I will call sudo internally as needed");
}
true
};
// Find previous generation or specific generation
let target_generation = if let Some(gen_number) = self.to {
find_generation_by_number(gen_number)?
} else {
find_previous_generation()?
};
info!("Rolling back to generation {}", target_generation.number);
// Construct path to the generation
let profile_dir = Path::new(SYSTEM_PROFILE).parent().unwrap_or_else(|| {
tracing::warn!(
"SYSTEM_PROFILE has no parent, defaulting to /nix/var/nix/profiles"
);
Path::new("/nix/var/nix/profiles")
});
let generation_link =
profile_dir.join(format!("system-{}-link", target_generation.number));
// Handle specialisations
let current_specialisation = fs::read_to_string(SPEC_LOCATION).ok();
let target_specialisation = if self.no_specialisation {
None
} else {
self.specialisation.clone().or(current_specialisation)
};
debug!("target_specialisation: {target_specialisation:?}");
// Compare changes between current and target generation
if matches!(self.diff, DiffType::Never) {
debug!(
"Not running dix as the target hostname is different from the system \
hostname."
);
} else {
debug!(
"Comparing with target profile: {}",
generation_link.display()
);
let _ = print_dix_diff(&PathBuf::from(CURRENT_PROFILE), &generation_link);
}
if self.dry {
info!(
"Dry run: would roll back to generation {}",
target_generation.number
);
return Ok(());
}
if self.ask {
let confirmation = inquire::Confirm::new(&format!(
"Roll back to generation {}?",
target_generation.number
))
.with_default(false)
.prompt()?;
if !confirmation {
bail!("User rejected the rollback");
}
}
// Get current generation number for potential rollback
let current_gen_number = match get_current_generation_number() {
Ok(num) => num,
Err(e) => {
warn!("Failed to get current generation number: {}", e);
0
},
};
// Set the system profile
info!("Setting system profile...");
// Instead of direct symlink operations, use a command with proper elevation
Command::new("ln")
.arg("-sfn") // force, symbolic link
.arg(&generation_link)
.arg(SYSTEM_PROFILE)
.elevate(elevate.then_some(elevation.clone()))
.message("Setting system profile")
.with_required_env()
.run()
.wrap_err("Failed to set system profile during rollback")?;
// Determine the correct profile to use with specialisations
let final_profile = match &target_specialisation {
None => generation_link,
Some(spec) => {
let spec_path = generation_link.join("specialisation").join(spec);
if spec_path.exists() {
spec_path
} else {
warn!(
"Specialisation '{}' does not exist in generation {}",
spec, target_generation.number
);
warn!("Using base configuration without specialisations");
generation_link
}
},
};
// Activate the configuration
info!("Activating...");
let switch_to_configuration =
final_profile.join("bin").join("switch-to-configuration");
if !switch_to_configuration.exists() {
return Err(eyre!(
"The 'switch-to-configuration' binary is missing from the built \
configuration.\n\nThis typically happens when 'system.switch.enable' \
is set to false in your\nNixOS configuration. To fix this, please \
either:\n1. Remove 'system.switch.enable = false' from your \
configuration, or\n2. Set 'system.switch.enable = true' \
explicitly\n\nIf the problem persists, please open an issue on our \
issue tracker!"
));
}
match Command::new(&switch_to_configuration)
.arg("switch")
.elevate(elevate.then_some(elevation.clone()))
.preserve_envs(["NIXOS_INSTALL_BOOTLOADER"])
.with_required_env()
.run()
{
Ok(()) => {
info!(
"Successfully rolled back to generation {}",
target_generation.number
);
},
Err(e) => {
// If activation fails, rollback the profile
if current_gen_number > 0 {
let current_gen_link =
profile_dir.join(format!("system-{current_gen_number}-link"));
Command::new("ln")
.arg("-sfn") // Force, symbolic link
.arg(¤t_gen_link)
.arg(SYSTEM_PROFILE)
.elevate(elevate.then_some(elevation))
.message("Rolling back system profile")
.with_required_env()
.run()
.wrap_err("NixOS: Failed to restore previous system profile after failed activation")?;
}
return Err(eyre!("Activation (switch) failed: {}", e))
.context("Failed to activate configuration");
},
}
Ok(())
}
}
fn find_previous_generation() -> Result<generations::GenerationInfo> {
let profile_path = PathBuf::from(SYSTEM_PROFILE);
let mut generations: Vec<generations::GenerationInfo> = fs::read_dir(
profile_path
.parent()
.unwrap_or(Path::new("/nix/var/nix/profiles")),
)?
.filter_map(|entry| {
entry.ok().and_then(|e| {
let path = e.path();
if let Some(filename) = path.file_name() {
if let Some(name) = filename.to_str() {
if name.starts_with("system-") && name.ends_with("-link") {
return generations::describe(&path);
}
}
}
None
})
})
.collect();
if generations.is_empty() {
bail!("No generations found");
}
generations.sort_by(|a, b| {
a.number
.parse::<u64>()
.unwrap_or(0)
.cmp(&b.number.parse::<u64>().unwrap_or(0))
});
let current_idx = generations
.iter()
.position(|g| g.current)
.ok_or_else(|| eyre!("Current generation not found"))?;
if current_idx == 0 {
bail!("No generation older than the current one exists");
}
Ok(generations[current_idx - 1].clone())
}
fn find_generation_by_number(
number: u64,
) -> Result<generations::GenerationInfo> {
let profile_path = PathBuf::from(SYSTEM_PROFILE);
let generations: Vec<generations::GenerationInfo> = fs::read_dir(
profile_path
.parent()
.unwrap_or(Path::new("/nix/var/nix/profiles")),
)?
.filter_map(|entry| {
entry.ok().and_then(|e| {
let path = e.path();
if let Some(filename) = path.file_name() {
if let Some(name) = filename.to_str() {
if name.starts_with("system-") && name.ends_with("-link") {
return generations::describe(&path);
}
}
}
None
})
})
.filter(|generation| generation.number == number.to_string())
.collect();
if generations.is_empty() {
bail!("Generation {} not found", number);
}
Ok(generations[0].clone())
}
fn get_current_generation_number() -> Result<u64> {
let profile_path = PathBuf::from(SYSTEM_PROFILE);
let generations: Vec<generations::GenerationInfo> = fs::read_dir(
profile_path
.parent()
.unwrap_or(Path::new("/nix/var/nix/profiles")),
)?
.filter_map(|entry| entry.ok().and_then(|e| generations::describe(&e.path())))
.collect();
let current_gen = generations
.iter()
.find(|g| g.current)
.ok_or_else(|| eyre!("Current generation not found"))?;
current_gen
.number
.parse::<u64>()
.wrap_err("Invalid generation number")
}
#[must_use]
pub fn get_final_attr(build_vm: bool, with_bootloader: bool) -> String {
let attr = if build_vm && with_bootloader {
"vmWithBootLoader"
} else if build_vm {
"vm"
} else {
"toplevel"
};
String::from(attr)
}
pub fn toplevel_for<S: AsRef<str>>(
hostname: S,
installable: Installable,
final_attr: &str,
) -> Installable {
let mut res = installable;
let hostname = hostname.as_ref().to_owned();
let toplevel = ["config", "system", "build", final_attr]
.into_iter()
.map(String::from);
match res {
Installable::Flake {
ref mut attribute, ..
} => {
// If user explicitly selects some other attribute, don't push
// nixosConfigurations
if attribute.is_empty() {
attribute.push(String::from("nixosConfigurations"));
attribute.push(hostname);
}
attribute.extend(toplevel);
},
Installable::File {
ref mut attribute, ..
} => {
attribute.extend(toplevel);
},
Installable::Expression {
ref mut attribute, ..
} => {
attribute.extend(toplevel);
},
Installable::Store { .. } => {},
}
res
}
impl OsReplArgs {
fn run(self) -> Result<()> {
// Use NH_OS_FLAKE if available, otherwise use the provided installable
let mut target_installable = if let Ok(os_flake) = env::var("NH_OS_FLAKE") {
debug!("Using NH_OS_FLAKE: {}", os_flake);
let mut elems = os_flake.splitn(2, '#');
let reference = match elems.next() {
Some(r) => r.to_owned(),
None => return Err(eyre!("NH_OS_FLAKE missing reference part")),
};
let attribute = elems
.next()
.map(crate::installable::parse_attribute)
.unwrap_or_default();
Installable::Flake {
reference,
attribute,
}
} else {
self.installable
};
if matches!(target_installable, Installable::Store { .. }) {
bail!("Nix doesn't support nix store installables.");
}
let hostname = self.hostname.ok_or(()).or_else(|()| get_hostname())?;
if let Installable::Flake {
ref mut attribute, ..
} = target_installable
{
if attribute.is_empty() {
attribute.push(String::from("nixosConfigurations"));
attribute.push(hostname);
}
}
Command::new("nix")
.arg("repl")
.args(target_installable.to_args())
.with_required_env()
.show_output(true)
.run()?;
Ok(())
}
}
impl OsGenerationsArgs {
fn info(&self) -> Result<()> {
let profile = match self.profile {
Some(ref p) => PathBuf::from(p),
None => bail!("Profile path is required"),
};
if !profile.is_symlink() {
return Err(eyre!(
"No profile `{:?}` found",
profile.file_name().unwrap_or_default()
));
}
let profile_dir = profile.parent().unwrap_or_else(|| Path::new("."));
let generations: Vec<_> = fs::read_dir(profile_dir)?
.filter_map(|entry| {
entry.ok().and_then(|e| {
let path = e.path();
if path
.file_name()?
.to_str()?
.starts_with(profile.file_name()?.to_str()?)
{
Some(path)
} else {
None
}
})
})
.collect();
let descriptions: Vec<generations::GenerationInfo> = generations
.iter()
.filter_map(|gen_dir| generations::describe(gen_dir))
.collect();
generations::print_info(descriptions, &self.fields)?;
Ok(())
}
}