PoC daemon edition
This commit is contained in:
parent
16f2649334
commit
ac53850fd1
2 changed files with 104 additions and 18 deletions
102
src/daemon.rs
102
src/daemon.rs
|
|
@ -1,9 +1,9 @@
|
|||
use std::{
|
||||
env, io,
|
||||
env, io, mem,
|
||||
ops::Deref,
|
||||
os::fd::{AsFd, BorrowedFd, IntoRawFd, OwnedFd, RawFd},
|
||||
sync::{
|
||||
LazyLock,
|
||||
Arc, LazyLock,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
|
|
@ -19,6 +19,7 @@ use serde::{Deserialize, Serialize};
|
|||
use serde_json::StreamDeserializer;
|
||||
|
||||
use crate::{
|
||||
SourceFile, SourceLine,
|
||||
daemon_tokfd::{FdInfo, FdKind},
|
||||
prelude::*,
|
||||
};
|
||||
|
|
@ -66,6 +67,17 @@ impl ConvenientAttrPath {
|
|||
let boxed = iter.map(|s| Box::from(s));
|
||||
Self::Split(Box::from_iter(boxed))
|
||||
}
|
||||
|
||||
pub fn to_nix_decl(&self) -> Box<str> {
|
||||
use ConvenientAttrPath::*;
|
||||
match self {
|
||||
Dotted(s) => s.clone(),
|
||||
Split(path) => {
|
||||
// FIXME: quote if necessary
|
||||
path.join(".").into_boxed_str()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'i> FromIterator<&'i str> for ConvenientAttrPath {
|
||||
|
|
@ -89,6 +101,7 @@ impl FromIterator<Box<str>> for ConvenientAttrPath {
|
|||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(serde::Deserialize, serde::Serialize)]
|
||||
#[serde(tag = "action", content = "args", rename_all = "snake_case")]
|
||||
// FIXME: rename to not confuse with the clap argument type.
|
||||
pub enum DaemonCmd {
|
||||
Append {
|
||||
name: ConvenientAttrPath,
|
||||
|
|
@ -112,6 +125,7 @@ fn next_token() -> Token {
|
|||
|
||||
#[derive(Debug)]
|
||||
pub struct Daemon {
|
||||
config_path: Arc<Path>,
|
||||
fd: OwnedFdWithFlags,
|
||||
path: Option<Box<Path>>,
|
||||
|
||||
|
|
@ -197,6 +211,8 @@ impl Daemon {
|
|||
IoError::last_os_error().raw_os_error(),
|
||||
Some(Errno::BADF.raw_os_error()),
|
||||
);
|
||||
|
||||
self.tokfd.remove2(&fd).unwrap_or_else(|| todo!());
|
||||
}
|
||||
|
||||
fn fd_for_token(&self, token: Token) -> Option<RawFd> {
|
||||
|
|
@ -215,7 +231,12 @@ impl Daemon {
|
|||
}
|
||||
|
||||
impl Daemon {
|
||||
pub fn new(fd: OwnedFd, kind: FdKind, name: Option<Box<OsStr>>) -> Self {
|
||||
pub fn new(
|
||||
config_path: Arc<Path>,
|
||||
fd: OwnedFd,
|
||||
kind: FdKind,
|
||||
name: Option<Box<OsStr>>,
|
||||
) -> Self {
|
||||
let mut fd_info: IdOrdMap<FdInfo> = Default::default();
|
||||
|
||||
// Supposedly, the only possible ways this can fail are EMFILE, ENFILE, and ENOMEM.
|
||||
|
|
@ -240,6 +261,7 @@ impl Daemon {
|
|||
};
|
||||
|
||||
Self {
|
||||
config_path,
|
||||
fd,
|
||||
path,
|
||||
poller,
|
||||
|
|
@ -250,7 +272,7 @@ impl Daemon {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn from_unix_socket_path(path: &Path) -> Result<Self, IoError> {
|
||||
pub fn from_unix_socket_path(config_path: Arc<Path>, path: &Path) -> Result<Self, IoError> {
|
||||
// We unconditionally unlink() `path` before binding, but completely ignore the result.
|
||||
let _ = rustix::fs::unlink(path);
|
||||
let listener = UnixListener::bind(path)
|
||||
|
|
@ -260,13 +282,18 @@ impl Daemon {
|
|||
rustix::net::sockopt::set_socket_keepalive(&listener_owned_fd, true).unwrap();
|
||||
let path: Box<OsStr> = path.to_path_buf().into_boxed_path().into_boxed_os_str();
|
||||
|
||||
Ok(Self::new(listener_owned_fd, FdKind::Socket, Some(path)))
|
||||
Ok(Self::new(
|
||||
config_path,
|
||||
listener_owned_fd,
|
||||
FdKind::Socket,
|
||||
Some(path),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn open_default_socket() -> Result<Self, IoError> {
|
||||
pub fn open_default_socket(config_path: Arc<Path>) -> Result<Self, IoError> {
|
||||
use IoErrorKind::*;
|
||||
let preferred = USER_SOCKET_DIR.join("dynix.sock").into_boxed_path();
|
||||
let constructed = match Self::from_unix_socket_path(&preferred) {
|
||||
let constructed = match Self::from_unix_socket_path(config_path.clone(), &preferred) {
|
||||
Ok(v) => v,
|
||||
Err(e) if e.kind() == Unsupported => {
|
||||
//
|
||||
|
|
@ -279,7 +306,7 @@ impl Daemon {
|
|||
);
|
||||
|
||||
let fallback = TMPDIR.join("dynix.sock").into_boxed_path();
|
||||
Self::from_unix_socket_path(&fallback).tap_err(|e| {
|
||||
Self::from_unix_socket_path(config_path, &fallback).tap_err(|e| {
|
||||
error!(
|
||||
"failed binding AF_UNIX socket at {}: {e}",
|
||||
fallback.display(),
|
||||
|
|
@ -294,14 +321,14 @@ impl Daemon {
|
|||
/// This panics if stdin cannot be opened.
|
||||
///
|
||||
/// If you want to handle that error, use [`Daemon::from_raw_parts()`].
|
||||
pub fn from_stdin() -> Self {
|
||||
pub fn from_stdin(config_path: Arc<Path>) -> Self {
|
||||
let stdin = io::stdin();
|
||||
let fd = stdin
|
||||
.as_fd()
|
||||
.try_clone_to_owned()
|
||||
.expect("dynix daemon could not open stdin; try a Unix socket?");
|
||||
|
||||
Self::new(fd, FdKind::File, None)
|
||||
Self::new(config_path, fd, FdKind::File, None)
|
||||
}
|
||||
|
||||
//pub unsafe fn from_raw_parts(fd: OwnedFd) -> Self {
|
||||
|
|
@ -325,8 +352,11 @@ impl Daemon {
|
|||
let _count = rustix::io::read(fd, spare_capacity(&mut self.cmd_buffer))
|
||||
.tap_err(|e| error!("read() on daemon fd {fd:?} failed: {e}"))?;
|
||||
|
||||
// So that the loop doesn't borrow from `self`.
|
||||
let mut cmd_buffer = mem::take(&mut self.cmd_buffer);
|
||||
|
||||
// The buffer might have existing data from the last read.
|
||||
let deserializer = serde_json::Deserializer::from_slice(&self.cmd_buffer);
|
||||
let deserializer = serde_json::Deserializer::from_slice(&cmd_buffer);
|
||||
let stream: StreamDeserializer<_, DaemonCmd> = deserializer.into_iter();
|
||||
for cmd in stream {
|
||||
let cmd = match cmd {
|
||||
|
|
@ -334,12 +364,14 @@ impl Daemon {
|
|||
Err(e) if e.is_eof() => {
|
||||
self.next_timeout = Some(Duration::from_secs(4));
|
||||
warn!("Didn't get a valid daemon command; giving the other side 4 seconds...");
|
||||
let _ = mem::replace(&mut self.cmd_buffer, cmd_buffer);
|
||||
return Ok(());
|
||||
},
|
||||
Err(e) => {
|
||||
warn!("error deserializing command: {e}");
|
||||
debug!("command buffer was: {:?}", self.cmd_buffer.as_bstr());
|
||||
self.cmd_buffer.clear();
|
||||
debug!("command buffer was: {:?}", cmd_buffer.as_bstr());
|
||||
cmd_buffer.clear();
|
||||
let _ = mem::replace(&mut self.cmd_buffer, cmd_buffer);
|
||||
// Don't propagate the error unless we have too many.
|
||||
self.fd_error_push(fd.as_raw_fd(), e.into()).tap_err(|e| {
|
||||
error!("Accumulated too many errors for daemon fd {fd:?}: {e}")
|
||||
|
|
@ -350,9 +382,51 @@ impl Daemon {
|
|||
debug!("got cmd: {cmd:?}");
|
||||
let _ = rustix::io::write(fd, b"");
|
||||
info!("dispatching command");
|
||||
self.dispatch_cmd(cmd).unwrap_or_else(|e| todo!("{e}"));
|
||||
}
|
||||
|
||||
self.cmd_buffer.clear();
|
||||
cmd_buffer.clear();
|
||||
let _ = mem::replace(&mut self.cmd_buffer, cmd_buffer);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn dispatch_cmd(&mut self, cmd: DaemonCmd) -> Result<(), IoError> {
|
||||
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 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);
|
||||
|
||||
crate::write_next_prio(source_file, new_line).unwrap_or_else(|e| todo!("{e}"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue