power outage stash
This commit is contained in:
parent
2ecd987be6
commit
a9b63f4d58
10 changed files with 332 additions and 62 deletions
254
src/daemon.rs
254
src/daemon.rs
|
|
@ -1,6 +1,7 @@
|
|||
use std::{
|
||||
env, io,
|
||||
os::fd::{AsFd, BorrowedFd, IntoRawFd, OwnedFd, RawFd},
|
||||
process::{Command, Stdio},
|
||||
sync::{
|
||||
Arc, LazyLock,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
|
|
@ -12,7 +13,20 @@ use iddqd::{BiHashMap, IdOrdMap};
|
|||
|
||||
use mio::{Events, Interest, Poll, Token, event::Event, net::UnixListener, unix::SourceFd};
|
||||
|
||||
use rustix::{buffer::spare_capacity, net::SocketFlags, process::Uid};
|
||||
use rustix::{
|
||||
buffer::spare_capacity,
|
||||
net::SocketFlags,
|
||||
process::{Pid, PidfdFlags, Uid, WaitId, WaitIdOptions},
|
||||
};
|
||||
|
||||
mod rustix {
|
||||
pub use rustix::process::{getuid, pidfd_open, waitid};
|
||||
pub use rustix::*;
|
||||
}
|
||||
|
||||
//mod rustix_prelude {
|
||||
// pub use rustix::process::{getuid, pidfd_open, waitid};
|
||||
//}
|
||||
|
||||
use serde_json::StreamDeserializer;
|
||||
|
||||
|
|
@ -21,10 +35,7 @@ use crate::prelude::*;
|
|||
pub mod api;
|
||||
use api::DaemonCmd;
|
||||
|
||||
use crate::{
|
||||
SourceFile, SourceLine,
|
||||
daemon_tokfd::{FdInfo, FdKind},
|
||||
};
|
||||
use crate::daemon_tokfd::{FdInfo, FdKind};
|
||||
|
||||
use crate::{OwnedFdWithFlags, TokenFd};
|
||||
|
||||
|
|
@ -45,6 +56,14 @@ pub static TMPDIR: LazyLock<&'static Path> = LazyLock::new(|| {
|
|||
Box::leak(dir)
|
||||
});
|
||||
|
||||
pub static NIXOS_REBUILD: LazyLock<&'static Path> = LazyLock::new(|| {
|
||||
which::which("nixos-rebuild")
|
||||
.inspect_err(|e| error!("couldn't find `nixos-rebuild` in PATH: {e}"))
|
||||
.map(PathBuf::into_boxed_path)
|
||||
.map(|boxed| &*Box::leak(boxed))
|
||||
.unwrap_or(Path::new("/run/current-system/sw/bin/nixos-rebuild"))
|
||||
});
|
||||
|
||||
const TIMEOUT_NEVER: Option<Duration> = None;
|
||||
|
||||
static NEXT_TOKEN_NUMBER: AtomicUsize = AtomicUsize::new(1);
|
||||
|
|
@ -60,6 +79,42 @@ fn next_token() -> Token {
|
|||
Token(tok)
|
||||
}
|
||||
|
||||
trait EventExt {
|
||||
type Display;
|
||||
|
||||
fn display(&self) -> Self::Display;
|
||||
}
|
||||
|
||||
#[derive(Copy)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
struct EventDisplay {
|
||||
token: Token,
|
||||
error: bool,
|
||||
writable: bool,
|
||||
write_closed: bool,
|
||||
readable: bool,
|
||||
read_closed: bool,
|
||||
}
|
||||
impl EventExt for Event {
|
||||
type Display = EventDisplay;
|
||||
|
||||
fn display(&self) -> Self::Display {
|
||||
EventDisplay {
|
||||
token: self.token(),
|
||||
error: self.is_error(),
|
||||
writable: self.is_writable(),
|
||||
write_closed: self.is_write_closed(),
|
||||
readable: self.is_readable(),
|
||||
read_closed: self.is_read_closed(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Display for EventDisplay {
|
||||
fn fmt(&self, f: &mut Formatter) -> FmtResult {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Daemon {
|
||||
config_path: Arc<Path>,
|
||||
|
|
@ -132,6 +187,32 @@ impl Daemon {
|
|||
token
|
||||
}
|
||||
|
||||
fn register_with_name<S>(&mut self, fd: RawFd, kind: FdKind, name: Box<OsStr>) -> Token {
|
||||
let token = next_token();
|
||||
|
||||
debug!(
|
||||
"Registering new {} FdInfo for {fd} ({}) with token {token:?}",
|
||||
name.to_string_lossy(),
|
||||
kind.name_str(),
|
||||
);
|
||||
|
||||
self.fd_info
|
||||
.insert_unique(FdInfo::new_with_name(fd, kind, name))
|
||||
.unwrap();
|
||||
|
||||
self.tokfd
|
||||
.insert_unique(TokenFd { token, fd })
|
||||
.unwrap_or_else(|e| todo!("{e}"));
|
||||
|
||||
let mut source = SourceFd(&fd);
|
||||
self.poller
|
||||
.registry()
|
||||
.register(&mut source, token, Interest::READABLE)
|
||||
.unwrap_or_else(|e| unreachable!("registering {fd:?} with poller failed: {e}"));
|
||||
|
||||
token
|
||||
}
|
||||
|
||||
fn deregister(&mut self, fd: RawFd) {
|
||||
let info = self
|
||||
.fd_info
|
||||
|
|
@ -279,6 +360,32 @@ const DAEMON: Token = Token(0);
|
|||
|
||||
/// Private helpers.
|
||||
impl Daemon {
|
||||
//fn proxy_stdio(&mut self, fd: &BorrowedFd) -> Result<(), IoError> {
|
||||
// let info = self.fd_info.get(&fd.as_raw_fd()).unwrap();
|
||||
// let label = match info.kind {
|
||||
// FdKind::ChildStdout => "stdout",
|
||||
// FdKind::ChildStderr => "stderr",
|
||||
// other => unreachable!("child stdio cannot have kind {other:?}"),
|
||||
// };
|
||||
// // FIXME: don't use a new allocation every time.
|
||||
// let mut buffer: Vec<u8> = Vec::with_capacity(1024);
|
||||
// // FIXME: handle line buffering correctly.
|
||||
// loop {
|
||||
// let count = rustix::io::read(fd, spare_capacity(&mut buffer))
|
||||
// .inspect_err(|e| error!("read() on child stdio fd {fd:?} failed: {e}"))?;
|
||||
//
|
||||
// if count == 0 {
|
||||
// break;
|
||||
// }
|
||||
//
|
||||
// for line in buffer.lines() {
|
||||
// debug!("[child {label}]: {}", line.as_bstr())
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// Ok(())
|
||||
//}
|
||||
|
||||
fn read_cmd(&mut self, fd: &BorrowedFd) -> Result<(), IoError> {
|
||||
// FIXME: don't use a new allocation every time.
|
||||
let mut cmd_buffer: Vec<u8> = Vec::with_capacity(1024);
|
||||
|
|
@ -317,42 +424,63 @@ impl Daemon {
|
|||
}
|
||||
|
||||
fn dispatch_cmd(&mut self, cmd: DaemonCmd) -> Result<(), IoError> {
|
||||
// Write the new file...
|
||||
let (name, value) = match cmd {
|
||||
DaemonCmd::Append { name, value } => (name, value),
|
||||
};
|
||||
let mut opts = File::options();
|
||||
opts.read(true)
|
||||
.write(true)
|
||||
.create(false)
|
||||
.custom_flags(libc::O_CLOEXEC);
|
||||
let source_file = SourceFile::open_from(self.config_path.clone(), opts)?;
|
||||
let source_file = crate::open_source_file(self.config_path.clone())?;
|
||||
let pri = crate::get_where(source_file.clone()).unwrap_or_else(|e| todo!("{e}"));
|
||||
let new_pri = pri - 1;
|
||||
//let new_pri_line =
|
||||
// crate::get_next_prio_line(source_file.clone(), Arc::from(name), Arc::from(value));
|
||||
// Get next priority line.
|
||||
let source_lines = source_file.lines()?;
|
||||
let penultimate = source_lines.get(source_lines.len() - 2);
|
||||
// FIXME: don't rely on whitespace lol
|
||||
debug_assert_eq!(penultimate.map(SourceLine::text).as_deref(), Some(" ];"));
|
||||
let penultimate = penultimate.unwrap();
|
||||
let new_generation = 0 - new_pri;
|
||||
let new_line = SourceLine {
|
||||
line: penultimate.line,
|
||||
path: source_file.path(),
|
||||
text: Arc::from(format!(
|
||||
" {} = lib.mkOverride ({}) ({}); # DYNIX GENERATION {}",
|
||||
name.to_nix_decl(),
|
||||
new_pri,
|
||||
value,
|
||||
new_generation,
|
||||
)),
|
||||
};
|
||||
|
||||
drop(source_lines);
|
||||
let opt_name = name.to_nix_decl();
|
||||
let new_line = crate::get_next_prio_line(source_file.clone(), &opt_name, new_pri, &value)
|
||||
.unwrap_or_else(|e| panic!("someone is holding a reference to source.lines(): {e}"));
|
||||
|
||||
crate::write_next_prio(source_file, new_line).unwrap_or_else(|e| todo!("{e}"));
|
||||
|
||||
// Rebuild and switch.
|
||||
// FIXME: allow passing additional args.
|
||||
let child = Command::new(*NIXOS_REBUILD)
|
||||
.arg("switch")
|
||||
.arg("--log-format")
|
||||
.arg("raw-with-logs")
|
||||
.arg("--no-reexec")
|
||||
.arg("-v")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.inspect_err(|e| {
|
||||
error!("failed to spawn `nixos-rebuild` command: {e}");
|
||||
})?;
|
||||
|
||||
debug!("Spanwed child process {}", child.id());
|
||||
|
||||
let pid = Pid::from_child(&child);
|
||||
|
||||
let stdout = child.stdout.unwrap_or_else(|| {
|
||||
unreachable!("`child` is given `.stdout(Stdio::piped())`");
|
||||
});
|
||||
let stderr = child.stderr.unwrap_or_else(|| {
|
||||
unreachable!("`child` is given `.stderr(Stdio::piped())`");
|
||||
});
|
||||
|
||||
let _token = self.register(stdout.into_raw_fd(), FdKind::ChildStdout);
|
||||
let _token = self.register(stderr.into_raw_fd(), FdKind::ChildStderr);
|
||||
|
||||
match rustix::process::pidfd_open(pid, PidfdFlags::NONBLOCK) {
|
||||
Ok(pidfd) => {
|
||||
debug!("Opened pidfd {pidfd:?}, for process {pid}");
|
||||
self.register(pidfd.into_raw_fd(), FdKind::Pid(pid));
|
||||
},
|
||||
Err(e) if e.kind() == IoErrorKind::NotFound => {
|
||||
warn!("child {pid} not found; died before we could open it?");
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Error opening pidfd for child {pid}: {e}");
|
||||
return Err(e)?;
|
||||
},
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -386,9 +514,9 @@ impl Daemon {
|
|||
|
||||
loop {
|
||||
if tracing::enabled!(tracing::Level::DEBUG) {
|
||||
trace!("Daemon loop iteration, with file descriptors: ");
|
||||
debug!("Daemon loop iteration, with file descriptors: ");
|
||||
for info in &self.fd_info {
|
||||
trace!("- {}", info.display());
|
||||
debug!("- {}", info.display());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -441,7 +569,7 @@ impl Daemon {
|
|||
}
|
||||
|
||||
fn handle_event(&mut self, event: &Event) -> Result<(), IoError> {
|
||||
trace!("Handling event {event:?}");
|
||||
trace!("Handling event {event:#?}");
|
||||
|
||||
match event.token() {
|
||||
DAEMON => {
|
||||
|
|
@ -487,17 +615,61 @@ impl Daemon {
|
|||
},
|
||||
other_token => {
|
||||
// This must be a stream fd.
|
||||
let stream_fd = self.fd_for_token(other_token).unwrap_or_else(|| {
|
||||
let fd = self.fd_for_token(other_token).unwrap_or_else(|| {
|
||||
unreachable!("tried to get fd for non-existent token? {other_token:?}")
|
||||
});
|
||||
let Some(info) = self.fd_info.get(&fd) else {
|
||||
panic!("Received an event on an unregistered fd {fd}; IO-safety violation?");
|
||||
};
|
||||
|
||||
if event.is_read_closed() {
|
||||
self.deregister(stream_fd);
|
||||
} else {
|
||||
// SAFETY: oh boy.
|
||||
let stream_fd = unsafe { BorrowedFd::borrow_raw(stream_fd) };
|
||||
self.read_cmd(&stream_fd).unwrap();
|
||||
self.deregister(fd);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
match info.kind {
|
||||
FdKind::Pid(pid) => {
|
||||
debug!("Reaping child process {pid}");
|
||||
// SAFETY: `fd` cannot have been closed yet, since that's what we do here.
|
||||
let pidfd = unsafe { BorrowedFd::borrow_raw(fd) };
|
||||
let status = rustix::waitid(WaitId::PidFd(pidfd), WaitIdOptions::EXITED)
|
||||
.unwrap_or_else(|e| {
|
||||
todo!("waitid() can fail? on pid {pid}: {e}");
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
todo!("waitid() returned None? for pid {pid}");
|
||||
});
|
||||
|
||||
debug!("waitid() for pid {pid} returned status: {status:?}");
|
||||
let is_dead = status.exited() || status.killed() || status.dumped();
|
||||
if !is_dead {
|
||||
todo!("Handle process {pid} events that aren't death: {status:?}");
|
||||
}
|
||||
let Some(exit_code) = status.exit_status() else {
|
||||
unreachable!("Process {pid} died with no exit code at all? {status:?}");
|
||||
};
|
||||
debug!("Child process {pid} exited with code {exit_code}");
|
||||
|
||||
// Close the pidfd.
|
||||
self.deregister(fd);
|
||||
},
|
||||
//FdKind::ChildStdout => {
|
||||
// warn!("got stdout");
|
||||
// todo!();
|
||||
//},
|
||||
//FdKind::ChildStderr => {
|
||||
// warn!("got stderr");
|
||||
// // SAFETY: oh boy.
|
||||
// let stderr = unsafe { BorrowedFd::borrow_raw(fd) };
|
||||
// self.proxy_stdio(&stderr).unwrap();
|
||||
//},
|
||||
FdKind::SockStream => {
|
||||
// SAFETY: oh boy.
|
||||
let stream_fd = unsafe { BorrowedFd::borrow_raw(fd) };
|
||||
self.read_cmd(&stream_fd).unwrap();
|
||||
},
|
||||
kind => todo!("{kind:?}"),
|
||||
};
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue