-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathconfigure_init_service.rs
More file actions
757 lines (689 loc) · 28.2 KB
/
configure_init_service.rs
File metadata and controls
757 lines (689 loc) · 28.2 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
use std::path::Path;
use std::path::PathBuf;
use tokio::process::Command;
use tracing::{span, Span};
use crate::action::macos::DARWIN_LAUNCHD_DOMAIN;
use crate::action::{ActionError, ActionErrorKind, ActionTag, StatefulAction};
use crate::execute_command;
use crate::action::{Action, ActionDescription};
use crate::settings::InitSystem;
use crate::util::OnMissing;
const TMPFILES_SRC: &str = "/nix/var/nix/profiles/default/lib/tmpfiles.d/nix-daemon.conf";
const TMPFILES_DEST: &str = "/etc/tmpfiles.d/nix-daemon.conf";
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct SocketFile {
pub name: String,
pub src: UnitSrc,
pub dest: PathBuf,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub enum UnitSrc {
Path(PathBuf),
Literal(String),
}
/**
Configure the init to run the Nix daemon
*/
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
#[serde(tag = "action_name", rename = "configure_init_service")]
pub struct ConfigureInitService {
init: InitSystem,
start_daemon: bool,
// TODO(cole-h): make an enum so we can distinguish between "written out by another step" vs "actually there isn't one"
service_src: Option<PathBuf>,
service_name: Option<String>,
service_dest: Option<PathBuf>,
socket_files: Vec<SocketFile>,
}
impl ConfigureInitService {
pub(crate) async fn check_if_systemd_unit_exists(
src: &UnitSrc,
dest: &Path,
) -> Result<(), ActionErrorKind> {
// TODO: once we have a way to communicate interaction between the library and the cli,
// interactively ask for permission to remove the file
// NOTE: Check if the unit file already exists...
let unit_dest = PathBuf::from(dest);
if unit_dest.exists() {
match src {
UnitSrc::Path(unit_src) => {
if unit_dest.is_symlink() {
let link_dest = tokio::fs::read_link(&unit_dest)
.await
.map_err(|e| ActionErrorKind::ReadSymlink(unit_dest.clone(), e))?;
if link_dest != *unit_src {
return Err(ActionErrorKind::SymlinkExists(unit_dest));
}
} else {
return Err(ActionErrorKind::FileExists(unit_dest));
}
},
UnitSrc::Literal(content) => {
if unit_dest.is_symlink() {
return Err(ActionErrorKind::FileExists(unit_dest));
} else {
let actual_content = tokio::fs::read_to_string(&unit_dest)
.await
.map_err(|e| ActionErrorKind::Read(unit_dest.clone(), e))?;
if *content != actual_content {
return Err(ActionErrorKind::DifferentContent(unit_dest));
}
}
},
}
}
// NOTE: ...and if there are any overrides in the most well-known places for systemd
let dest_d = format!("{dest}.d", dest = dest.display());
if Path::new(&dest_d).exists() {
return Err(ActionErrorKind::DirExists(PathBuf::from(dest_d)));
}
Ok(())
}
#[tracing::instrument(level = "debug", skip_all)]
pub async fn plan(
init: InitSystem,
start_daemon: bool,
service_src: Option<PathBuf>,
service_dest: Option<PathBuf>,
service_name: Option<String>,
socket_files: Vec<SocketFile>,
) -> Result<StatefulAction<Self>, ActionError> {
match init {
InitSystem::Launchd => {
// No plan checks, yet
},
InitSystem::Systemd => {
// If `no_start_daemon` is set, then we don't require a running systemd,
// so we don't need to check if `/run/systemd/system` exists.
if start_daemon {
// If /run/systemd/system exists, we can be reasonably sure the machine is booted
// with systemd: https://www.freedesktop.org/software/systemd/man/sd_booted.html
if !Path::new("/run/systemd/system").exists() {
return Err(Self::error(ActionErrorKind::SystemdMissing));
}
}
if which::which("systemctl").is_err() {
return Err(Self::error(ActionErrorKind::SystemdMissing));
}
},
InitSystem::None => {
// Nothing here, no init system
},
};
Ok(Self {
init,
start_daemon,
service_src,
service_dest,
service_name,
socket_files,
}
.into())
}
}
#[async_trait::async_trait]
#[typetag::serde(name = "configure_init_service")]
impl Action for ConfigureInitService {
fn action_tag() -> ActionTag {
ActionTag("configure_init_service")
}
fn tracing_synopsis(&self) -> String {
match self.init {
InitSystem::Systemd => "Configure Nix daemon related settings with systemd".to_string(),
InitSystem::Launchd => {
"Configure Nix daemon related settings with launchctl".to_string()
},
InitSystem::None => "Leave the Nix daemon unconfigured".to_string(),
}
}
fn tracing_span(&self) -> Span {
span!(tracing::Level::DEBUG, "configure_init_service")
}
fn execute_description(&self) -> Vec<ActionDescription> {
let mut vec = Vec::new();
match self.init {
InitSystem::Systemd => {
let mut explanation = vec![
"Run `systemd-tmpfiles --create --prefix=/nix/var/nix`".to_string(),
format!(
"Symlink `{0}` to `{1}`",
self.service_src
.as_ref()
.expect("service_src should be defined for systemd")
.display(),
self.service_dest
.as_ref()
.expect("service_src should be defined for systemd")
.display()
),
];
for SocketFile { src, dest, .. } in self.socket_files.iter() {
match src {
UnitSrc::Path(src) => {
explanation.push(format!(
"Symlink `{}` to `{}`",
src.display(),
dest.display()
));
},
UnitSrc::Literal(_) => {
explanation.push(format!("Create `{}`", dest.display()));
},
}
}
explanation.push("Run `systemctl daemon-reload`".to_string());
if self.start_daemon {
for SocketFile { name, .. } in self.socket_files.iter() {
explanation.push(format!("Run `systemctl enable --now {}`", name));
}
}
vec.push(ActionDescription::new(self.tracing_synopsis(), explanation))
},
InitSystem::Launchd => {
let mut explanation = vec![];
if let Some(service_src) = self.service_src.as_ref() {
explanation.push(format!(
"Copy `{0}` to `{1}`",
service_src.display(),
self.service_dest
.as_ref()
.expect("service_dest should be defined for launchd")
.display(),
));
}
if self.start_daemon {
explanation.push(format!(
"Run `launchctl bootstrap {0}`",
self.service_dest
.as_ref()
.expect("service_dest should be defined for launchd")
.display(),
));
}
vec.push(ActionDescription::new(self.tracing_synopsis(), explanation))
},
InitSystem::None => (),
}
vec
}
#[tracing::instrument(level = "debug", skip_all)]
async fn execute(&mut self) -> Result<(), ActionError> {
let Self {
init,
start_daemon,
service_src,
service_dest,
service_name,
socket_files,
} = self;
match init {
InitSystem::Launchd => {
let service_dest = service_dest
.as_ref()
.expect("service_dest should be set for Launchd");
let service_name = service_name
.as_ref()
.expect("service_name should be set for Launchd");
let domain = DARWIN_LAUNCHD_DOMAIN;
if let Some(service_src) = service_src {
tokio::fs::copy(&service_src, service_dest)
.await
.map_err(|e| {
Self::error(ActionErrorKind::Copy(
service_src.clone(),
PathBuf::from(service_dest),
e,
))
})?;
}
crate::action::macos::retry_bootstrap(domain, service_name, service_dest)
.await
.map_err(Self::error)?;
let is_disabled = crate::action::macos::service_is_disabled(domain, service_name)
.await
.map_err(Self::error)?;
if is_disabled {
execute_command(
Command::new("launchctl")
.process_group(0)
.arg("enable")
.arg(format!("{domain}/{service_name}"))
.stdin(std::process::Stdio::null()),
)
.await
.map_err(Self::error)?;
}
if *start_daemon {
crate::action::macos::retry_kickstart(domain, service_name)
.await
.map_err(Self::error)?;
}
},
InitSystem::Systemd => {
let service_dest = service_dest
.as_ref()
.expect("service_dest should be defined for systemd");
// The goal state is the `socket` enabled and active, the service not enabled and stopped (it activates via socket activation)
let mut any_socket_was_active = false;
for SocketFile { name, .. } in socket_files.iter() {
let is_active = is_active(name).await.map_err(Self::error)?;
if is_enabled(name).await.map_err(Self::error)? {
disable(name, is_active).await.map_err(Self::error)?;
} else if is_active {
stop(name).await.map_err(Self::error)?;
};
if is_active {
any_socket_was_active = true;
}
}
{
let is_active = is_active("nix-daemon.service").await.map_err(Self::error)?;
if is_enabled("nix-daemon.service")
.await
.map_err(Self::error)?
{
disable("nix-daemon.service", is_active)
.await
.map_err(Self::error)?;
} else if is_active {
stop("nix-daemon.service").await.map_err(Self::error)?;
};
}
if !Path::new(TMPFILES_DEST).exists() {
tracing::trace!(src = TMPFILES_SRC, dest = TMPFILES_DEST, "Symlinking");
tokio::fs::symlink(TMPFILES_SRC, TMPFILES_DEST)
.await
.map_err(|e| {
ActionErrorKind::Symlink(
PathBuf::from(TMPFILES_SRC),
PathBuf::from(TMPFILES_DEST),
e,
)
})
.map_err(Self::error)?;
}
execute_command(
Command::new("systemd-tmpfiles")
.process_group(0)
.arg("--create")
.arg("--prefix=/nix/var/nix")
.stdin(std::process::Stdio::null()),
)
.await
.map_err(Self::error)?;
// TODO: once we have a way to communicate interaction between the library and the
// cli, interactively ask for permission to remove the file
if let Some(service_src) = service_src.as_ref() {
Self::check_if_systemd_unit_exists(
&UnitSrc::Path(service_src.to_path_buf()),
service_dest,
)
.await
.map_err(Self::error)?;
crate::util::remove_file(service_dest, OnMissing::Ignore)
.await
.map_err(|e| ActionErrorKind::Remove(service_dest.into(), e))
.map_err(Self::error)?;
tracing::trace!(src = %service_src.display(), dest = %service_dest.display(), "Symlinking");
tokio::fs::symlink(service_src, service_dest)
.await
.map_err(|e| {
ActionErrorKind::Symlink(
service_src.clone(),
PathBuf::from(service_dest),
e,
)
})
.map_err(Self::error)?;
}
for SocketFile { src, dest, .. } in socket_files.iter() {
Self::check_if_systemd_unit_exists(src, dest)
.await
.map_err(Self::error)?;
crate::util::remove_file(dest, OnMissing::Ignore)
.await
.map_err(|e| ActionErrorKind::Remove(dest.into(), e))
.map_err(Self::error)?;
match src {
UnitSrc::Path(src) => {
tracing::trace!(src = %src.display(), dest = %dest.display(), "Symlinking");
tokio::fs::symlink(src, dest)
.await
.map_err(|e| {
ActionErrorKind::Symlink(
PathBuf::from(src),
PathBuf::from(dest),
e,
)
})
.map_err(Self::error)?;
},
UnitSrc::Literal(content) => {
tracing::trace!(src = %content, dest = %dest.display(), "Writing");
tokio::fs::write(&dest, content)
.await
.map_err(|e| ActionErrorKind::Write(dest.clone(), e))
.map_err(Self::error)?;
},
}
}
if *start_daemon {
execute_command(
Command::new("systemctl")
.process_group(0)
.arg("daemon-reload")
.stdin(std::process::Stdio::null()),
)
.await
.map_err(Self::error)?;
}
for SocketFile { name, src, .. } in socket_files.iter() {
let enable_now = *start_daemon || any_socket_was_active;
match src {
UnitSrc::Path(path) => {
// NOTE(cole-h): we have to enable by path here because older systemd's
// (e.g. on our Ubuntu 16.04 test VMs) had faulty (or too- strict)
// symlink detection, which causes the symlink chain of
// `/etc/systemd/system/nix-daemon.socket` ->
// `/nix/var/nix/profiles/default` -> `/nix/store/............/nix-
// daemon.socket` to fail with "Failed to execute operation: Too many
// levels of symbolic links"
enable(path.display().to_string().as_ref(), enable_now)
.await
.map_err(Self::error)?;
},
UnitSrc::Literal(_) => {
enable(name, enable_now).await.map_err(Self::error)?;
},
}
}
},
InitSystem::None => {
// Nothing here, no init system
},
};
Ok(())
}
fn revert_description(&self) -> Vec<ActionDescription> {
match self.init {
InitSystem::Systemd => {
let mut steps = vec![];
for SocketFile { name, .. } in self.socket_files.iter() {
steps.push(format!("Run `systemctl disable {}`", name));
}
steps.push(format!(
"Run `systemctl disable {0}`",
self.service_src
.as_ref()
.expect("service_src should be defined for systemd")
.display()
));
steps.push("Run `systemd-tempfiles --remove --prefix=/nix/var/nix`".to_string());
steps.push("Run `systemctl daemon-reload`".to_string());
vec![ActionDescription::new(
"Unconfigure Nix daemon related settings with systemd".to_string(),
steps,
)]
},
InitSystem::Launchd => {
vec![ActionDescription::new(
"Unconfigure Nix daemon related settings with launchctl".to_string(),
vec![format!(
"Run `launchctl bootout {DARWIN_LAUNCHD_DOMAIN}/{0}`",
self.service_name
.as_ref()
.expect("service_name should be defined for launchd"),
)],
)]
},
InitSystem::None => Vec::new(),
}
}
#[tracing::instrument(level = "debug", skip_all)]
async fn revert(&mut self) -> Result<(), ActionError> {
let mut errors = vec![];
match self.init {
InitSystem::Launchd => {
let service_name = self
.service_name
.as_ref()
.expect("service_name should be set for launchd");
if let Err(e) =
crate::action::macos::retry_bootout(DARWIN_LAUNCHD_DOMAIN, service_name).await
{
errors.push(e);
}
// check if the daemon is down up to 99 times, with 100ms of delay between each attempt
for attempt in 1..100 {
tracing::trace!(attempt, "Checking to see if the daemon is down yet");
if execute_command(
Command::new("launchctl")
.process_group(0)
.arg("print")
.arg([DARWIN_LAUNCHD_DOMAIN, service_name].join("/")),
)
.await
.is_err()
{
tracing::trace!(attempt, "Daemon is down");
break;
}
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
}
},
InitSystem::Systemd => {
// We separate stop and disable (instead of using `--now`) to avoid cases where the service isn't started, but is enabled.
// These have to fail fast.
for SocketFile { name, .. } in self.socket_files.iter() {
let socket_is_active = is_active(name).await.map_err(Self::error)?;
let socket_is_enabled = is_enabled(name).await.map_err(Self::error)?;
if socket_is_active {
if let Err(err) = execute_command(
Command::new("systemctl")
.process_group(0)
.args(["stop", name])
.stdin(std::process::Stdio::null()),
)
.await
{
errors.push(err);
}
}
if socket_is_enabled {
if let Err(err) = execute_command(
Command::new("systemctl")
.process_group(0)
.args(["disable", name])
.stdin(std::process::Stdio::null()),
)
.await
{
errors.push(err);
}
}
}
let service_is_active =
is_active("nix-daemon.service").await.map_err(Self::error)?;
let service_is_enabled = is_enabled("nix-daemon.service")
.await
.map_err(Self::error)?;
if service_is_active {
if let Err(err) = execute_command(
Command::new("systemctl")
.process_group(0)
.args(["stop", "nix-daemon.service"])
.stdin(std::process::Stdio::null()),
)
.await
{
errors.push(err);
}
}
if service_is_enabled {
if let Err(err) = execute_command(
Command::new("systemctl")
.process_group(0)
.args(["disable", "nix-daemon.service"])
.stdin(std::process::Stdio::null()),
)
.await
{
errors.push(err);
}
}
if let Err(err) = execute_command(
Command::new("systemd-tmpfiles")
.process_group(0)
.arg("--remove")
.arg("--prefix=/nix/var/nix")
.stdin(std::process::Stdio::null()),
)
.await
{
errors.push(err);
}
if let Err(err) =
crate::util::remove_file(Path::new(TMPFILES_DEST), OnMissing::Ignore)
.await
.map_err(|e| ActionErrorKind::Remove(PathBuf::from(TMPFILES_DEST), e))
{
errors.push(err);
}
if let Err(err) = execute_command(
Command::new("systemctl")
.process_group(0)
.arg("daemon-reload")
.stdin(std::process::Stdio::null()),
)
.await
{
errors.push(err);
}
},
InitSystem::None => {
// Nothing here, no init
},
};
if let Some(dest) = &self.service_dest {
if let Err(err) = crate::util::remove_file(dest, OnMissing::Ignore)
.await
.map_err(|e| ActionErrorKind::Remove(PathBuf::from(dest), e))
{
errors.push(err);
}
}
for socket in self.socket_files.iter() {
if let Err(err) = crate::util::remove_file(&socket.dest, OnMissing::Ignore)
.await
.map_err(|e| ActionErrorKind::Remove(socket.dest.to_path_buf(), e))
{
errors.push(err);
}
}
if errors.is_empty() {
Ok(())
} else if errors.len() == 1 {
Err(Self::error(
errors
.into_iter()
.next()
.expect("Expected 1 len Vec to have at least 1 item"),
))
} else {
Err(Self::error(ActionErrorKind::Multiple(errors)))
}
}
}
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ConfigureNixDaemonServiceError {
#[error("No supported init system found")]
InitNotSupported,
}
async fn stop(unit: &str) -> Result<(), ActionErrorKind> {
let mut command = Command::new("systemctl");
command.arg("stop");
command.arg(unit);
let output = command
.output()
.await
.map_err(|e| ActionErrorKind::command(&command, e))?;
match output.status.success() {
true => {
tracing::trace!(%unit, "Stopped");
Ok(())
},
false => Err(ActionErrorKind::command_output(&command, output)),
}
}
async fn enable(unit: &str, now: bool) -> Result<(), ActionErrorKind> {
let mut command = Command::new("systemctl");
command.arg("enable");
command.arg(unit);
if now {
command.arg("--now");
}
let output = command
.output()
.await
.map_err(|e| ActionErrorKind::command(&command, e))?;
match output.status.success() {
true => {
tracing::trace!(unit = %unit, %now, "Enabled unit");
Ok(())
},
false => Err(ActionErrorKind::command_output(&command, output)),
}
}
async fn disable(unit: &str, now: bool) -> Result<(), ActionErrorKind> {
let mut command = Command::new("systemctl");
command.arg("disable");
command.arg(unit);
if now {
command.arg("--now");
}
let output = command
.output()
.await
.map_err(|e| ActionErrorKind::command(&command, e))?;
match output.status.success() {
true => {
tracing::trace!(%unit, %now, "Disabled unit");
Ok(())
},
false => Err(ActionErrorKind::command_output(&command, output)),
}
}
async fn is_active(unit: &str) -> Result<bool, ActionErrorKind> {
let mut command = Command::new("systemctl");
command.arg("is-active");
command.arg(unit);
let output = command
.output()
.await
.map_err(|e| ActionErrorKind::command(&command, e))?;
if String::from_utf8(output.stdout)?.starts_with("active") {
tracing::trace!(%unit, "Is active");
Ok(true)
} else {
tracing::trace!(%unit, "Is not active");
Ok(false)
}
}
async fn is_enabled(unit: &str) -> Result<bool, ActionErrorKind> {
let mut command = Command::new("systemctl");
command.arg("is-enabled");
command.arg(unit);
let output = command
.output()
.await
.map_err(|e| ActionErrorKind::command(&command, e))?;
let stdout = String::from_utf8(output.stdout)?;
if stdout.starts_with("enabled") || stdout.starts_with("linked") {
tracing::trace!(%unit, "Is enabled");
Ok(true)
} else {
tracing::trace!(%unit, "Is not enabled");
Ok(false)
}
}