-
Notifications
You must be signed in to change notification settings - Fork 61
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make our Nix installation immune to macOS upgrades (#672)
* Add cargo-watch * clippy: the borrowed expression implements the required traits * clippy: expression creates a reference which is immediately dereferenced by the compiler * clippy: redundant closure * clippy: this if-then-else expression returns a bool literal * clippy: explicit call to .into_iter() in function argument accepting IntoIterator * Clippy: an implementation of From is preferred since it gives you Into<_> for free where the reverse isn't true * Support cargo building on a mac * Create a nix-hook service on macos to inject the shell at startup * Introduce nix-installe restore-shell to fix the init scripts, called by the nix-hook plist on every login * Wait for /nix to be there, and restart the hook until it works * Back to run-at-load hoping that works * Revert "Back to run-at-load hoping that works" This reverts commit cccb8bc. It starts too early, fails, and then aborts. When it fails, launchd says the service failed to initialize and that the system is read-only. * nits * rename to repair * Handle --no-modify-profile * fmt --------- Co-authored-by: Ana Hobden <[email protected]>
- Loading branch information
Showing
8 changed files
with
320 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,226 @@ | ||
use serde::{Deserialize, Serialize}; | ||
use tracing::{span, Span}; | ||
|
||
use std::path::PathBuf; | ||
use tokio::{ | ||
fs::{remove_file, OpenOptions}, | ||
io::AsyncWriteExt, | ||
process::Command, | ||
}; | ||
|
||
use crate::{ | ||
action::{Action, ActionDescription, ActionError, ActionErrorKind, ActionTag, StatefulAction}, | ||
execute_command, | ||
}; | ||
|
||
/** Create a plist for a `launchctl` service to re-add Nix to the zshrc after upgrades. | ||
*/ | ||
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] | ||
pub struct CreateNixHookService { | ||
path: PathBuf, | ||
service_label: String, | ||
needs_bootout: bool, | ||
} | ||
|
||
impl CreateNixHookService { | ||
#[tracing::instrument(level = "debug", skip_all)] | ||
pub async fn plan() -> Result<StatefulAction<Self>, ActionError> { | ||
let mut this = Self { | ||
path: PathBuf::from( | ||
"/Library/LaunchDaemons/systems.determinate.nix-installer.nix-hook.plist", | ||
), | ||
service_label: "systems.determinate.nix-installer.nix-hook".into(), | ||
needs_bootout: false, | ||
}; | ||
|
||
// If the service is currently loaded or running, we need to unload it during execute (since we will then recreate it and reload it) | ||
// This `launchctl` command may fail if the service isn't loaded | ||
let mut check_loaded_command = Command::new("launchctl"); | ||
check_loaded_command.process_group(0); | ||
check_loaded_command.arg("print"); | ||
check_loaded_command.arg(format!("system/{}", this.service_label)); | ||
tracing::trace!( | ||
command = format!("{:?}", check_loaded_command.as_std()), | ||
"Executing" | ||
); | ||
let check_loaded_output = check_loaded_command | ||
.output() | ||
.await | ||
.map_err(|e| ActionErrorKind::command(&check_loaded_command, e)) | ||
.map_err(Self::error)?; | ||
this.needs_bootout = check_loaded_output.status.success(); | ||
if this.needs_bootout { | ||
tracing::debug!( | ||
"Detected loaded service `{}` which needs unload before replacing `{}`", | ||
this.service_label, | ||
this.path.display(), | ||
); | ||
} | ||
|
||
if this.path.exists() { | ||
let discovered_plist: LaunchctlHookPlist = | ||
plist::from_file(&this.path).map_err(Self::error)?; | ||
let expected_plist = generate_plist(&this.service_label) | ||
.await | ||
.map_err(Self::error)?; | ||
if discovered_plist != expected_plist { | ||
tracing::trace!( | ||
?discovered_plist, | ||
?expected_plist, | ||
"Parsed plists not equal" | ||
); | ||
return Err(Self::error(CreateNixHookServiceError::DifferentPlist { | ||
expected: expected_plist, | ||
discovered: discovered_plist, | ||
path: this.path.clone(), | ||
})); | ||
} | ||
|
||
tracing::debug!("Creating file `{}` already complete", this.path.display()); | ||
return Ok(StatefulAction::completed(this)); | ||
} | ||
|
||
Ok(StatefulAction::uncompleted(this)) | ||
} | ||
} | ||
|
||
#[async_trait::async_trait] | ||
#[typetag::serde(name = "create_nix_hook_service")] | ||
impl Action for CreateNixHookService { | ||
fn action_tag() -> ActionTag { | ||
ActionTag("create_nix_hook_service") | ||
} | ||
fn tracing_synopsis(&self) -> String { | ||
format!( | ||
"{maybe_unload} a `launchctl` plist to put Nix into your PATH", | ||
maybe_unload = if self.needs_bootout { | ||
"Unload, then recreate" | ||
} else { | ||
"Create" | ||
} | ||
) | ||
} | ||
|
||
fn tracing_span(&self) -> Span { | ||
let span = span!( | ||
tracing::Level::DEBUG, | ||
"create_nix_hook_service", | ||
path = tracing::field::display(self.path.display()), | ||
buf = tracing::field::Empty, | ||
); | ||
|
||
span | ||
} | ||
|
||
fn execute_description(&self) -> Vec<ActionDescription> { | ||
vec![ActionDescription::new(self.tracing_synopsis(), vec![])] | ||
} | ||
|
||
#[tracing::instrument(level = "debug", skip_all)] | ||
async fn execute(&mut self) -> Result<(), ActionError> { | ||
let Self { | ||
path, | ||
service_label, | ||
needs_bootout, | ||
} = self; | ||
|
||
if *needs_bootout { | ||
execute_command( | ||
Command::new("launchctl") | ||
.process_group(0) | ||
.arg("bootout") | ||
.arg(format!("system/{service_label}")), | ||
) | ||
.await | ||
.map_err(Self::error)?; | ||
} | ||
|
||
let generated_plist = generate_plist(service_label).await.map_err(Self::error)?; | ||
|
||
let mut options = OpenOptions::new(); | ||
options.create(true).write(true).read(true); | ||
|
||
let mut file = options | ||
.open(&path) | ||
.await | ||
.map_err(|e| Self::error(ActionErrorKind::Open(path.to_owned(), e)))?; | ||
|
||
let mut buf = Vec::new(); | ||
plist::to_writer_xml(&mut buf, &generated_plist).map_err(Self::error)?; | ||
file.write_all(&buf) | ||
.await | ||
.map_err(|e| Self::error(ActionErrorKind::Write(path.to_owned(), e)))?; | ||
|
||
Ok(()) | ||
} | ||
|
||
fn revert_description(&self) -> Vec<ActionDescription> { | ||
vec![ActionDescription::new( | ||
format!("Delete file `{}`", self.path.display()), | ||
vec![format!("Delete file `{}`", self.path.display())], | ||
)] | ||
} | ||
|
||
#[tracing::instrument(level = "debug", skip_all)] | ||
async fn revert(&mut self) -> Result<(), ActionError> { | ||
remove_file(&self.path) | ||
.await | ||
.map_err(|e| Self::error(ActionErrorKind::Remove(self.path.to_owned(), e)))?; | ||
|
||
Ok(()) | ||
} | ||
} | ||
|
||
/// This function must be able to operate at both plan and execute time. | ||
async fn generate_plist(service_label: &str) -> Result<LaunchctlHookPlist, ActionErrorKind> { | ||
let plist = LaunchctlHookPlist { | ||
keep_alive: KeepAliveOpts { | ||
successful_exit: false, | ||
}, | ||
label: service_label.into(), | ||
program_arguments: vec![ | ||
"/bin/sh".into(), | ||
"-c".into(), | ||
"/bin/wait4path /nix/nix-installer && /nix/nix-installer repair".into(), | ||
], | ||
standard_error_path: "/nix/.nix-installer-hook.err.log".into(), | ||
standard_out_path: "/nix/.nix-installer-hook.out.log".into(), | ||
}; | ||
|
||
Ok(plist) | ||
} | ||
|
||
#[derive(Deserialize, Clone, Debug, Serialize, PartialEq)] | ||
#[serde(rename_all = "PascalCase")] | ||
pub struct LaunchctlHookPlist { | ||
label: String, | ||
program_arguments: Vec<String>, | ||
keep_alive: KeepAliveOpts, | ||
standard_error_path: String, | ||
standard_out_path: String, | ||
} | ||
|
||
#[derive(Deserialize, Clone, Debug, Serialize, PartialEq)] | ||
#[serde(rename_all = "PascalCase")] | ||
pub struct KeepAliveOpts { | ||
successful_exit: bool, | ||
} | ||
|
||
#[non_exhaustive] | ||
#[derive(Debug, thiserror::Error)] | ||
pub enum CreateNixHookServiceError { | ||
#[error( | ||
"`{path}` exists and contains content different than expected. Consider removing the file." | ||
)] | ||
DifferentPlist { | ||
expected: LaunchctlHookPlist, | ||
discovered: LaunchctlHookPlist, | ||
path: PathBuf, | ||
}, | ||
} | ||
|
||
impl From<CreateNixHookServiceError> for ActionErrorKind { | ||
fn from(val: CreateNixHookServiceError) -> Self { | ||
ActionErrorKind::Custom(Box::new(val)) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
use std::process::ExitCode; | ||
|
||
use crate::{ | ||
action::common::ConfigureShellProfile, | ||
cli::{ensure_root, CommandExecute}, | ||
planner::{PlannerError, ShellProfileLocations}, | ||
}; | ||
use clap::{ArgAction, Parser}; | ||
|
||
/** | ||
Update the shell profiles to make Nix usable after system upgrades. | ||
*/ | ||
#[derive(Debug, Parser)] | ||
#[command(args_conflicts_with_subcommands = true)] | ||
pub struct Repair { | ||
#[clap( | ||
long, | ||
env = "NIX_INSTALLER_NO_CONFIRM", | ||
action(ArgAction::SetTrue), | ||
default_value = "false", | ||
global = true | ||
)] | ||
pub no_confirm: bool, | ||
} | ||
|
||
#[async_trait::async_trait] | ||
impl CommandExecute for Repair { | ||
#[tracing::instrument(level = "trace", skip_all)] | ||
async fn execute(self) -> eyre::Result<ExitCode> { | ||
let Self { no_confirm: _ } = self; | ||
|
||
ensure_root()?; | ||
|
||
let mut reconfigure = ConfigureShellProfile::plan(ShellProfileLocations::default()) | ||
.await | ||
.map_err(PlannerError::Action)? | ||
.boxed(); | ||
|
||
if let Err(err) = reconfigure.try_execute().await { | ||
println!("{:#?}", err); | ||
Ok(ExitCode::FAILURE) | ||
} else { | ||
Ok(ExitCode::SUCCESS) | ||
} | ||
} | ||
} |
Oops, something went wrong.