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::{
|
use std::{
|
||||||
env, io,
|
env, io, mem,
|
||||||
ops::Deref,
|
ops::Deref,
|
||||||
os::fd::{AsFd, BorrowedFd, IntoRawFd, OwnedFd, RawFd},
|
os::fd::{AsFd, BorrowedFd, IntoRawFd, OwnedFd, RawFd},
|
||||||
sync::{
|
sync::{
|
||||||
LazyLock,
|
Arc, LazyLock,
|
||||||
atomic::{AtomicUsize, Ordering},
|
atomic::{AtomicUsize, Ordering},
|
||||||
},
|
},
|
||||||
time::Duration,
|
time::Duration,
|
||||||
|
|
@ -19,6 +19,7 @@ use serde::{Deserialize, Serialize};
|
||||||
use serde_json::StreamDeserializer;
|
use serde_json::StreamDeserializer;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
SourceFile, SourceLine,
|
||||||
daemon_tokfd::{FdInfo, FdKind},
|
daemon_tokfd::{FdInfo, FdKind},
|
||||||
prelude::*,
|
prelude::*,
|
||||||
};
|
};
|
||||||
|
|
@ -66,6 +67,17 @@ impl ConvenientAttrPath {
|
||||||
let boxed = iter.map(|s| Box::from(s));
|
let boxed = iter.map(|s| Box::from(s));
|
||||||
Self::Split(Box::from_iter(boxed))
|
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 {
|
impl<'i> FromIterator<&'i str> for ConvenientAttrPath {
|
||||||
|
|
@ -89,6 +101,7 @@ impl FromIterator<Box<str>> for ConvenientAttrPath {
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
#[derive(serde::Deserialize, serde::Serialize)]
|
#[derive(serde::Deserialize, serde::Serialize)]
|
||||||
#[serde(tag = "action", content = "args", rename_all = "snake_case")]
|
#[serde(tag = "action", content = "args", rename_all = "snake_case")]
|
||||||
|
// FIXME: rename to not confuse with the clap argument type.
|
||||||
pub enum DaemonCmd {
|
pub enum DaemonCmd {
|
||||||
Append {
|
Append {
|
||||||
name: ConvenientAttrPath,
|
name: ConvenientAttrPath,
|
||||||
|
|
@ -112,6 +125,7 @@ fn next_token() -> Token {
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Daemon {
|
pub struct Daemon {
|
||||||
|
config_path: Arc<Path>,
|
||||||
fd: OwnedFdWithFlags,
|
fd: OwnedFdWithFlags,
|
||||||
path: Option<Box<Path>>,
|
path: Option<Box<Path>>,
|
||||||
|
|
||||||
|
|
@ -197,6 +211,8 @@ impl Daemon {
|
||||||
IoError::last_os_error().raw_os_error(),
|
IoError::last_os_error().raw_os_error(),
|
||||||
Some(Errno::BADF.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> {
|
fn fd_for_token(&self, token: Token) -> Option<RawFd> {
|
||||||
|
|
@ -215,7 +231,12 @@ impl Daemon {
|
||||||
}
|
}
|
||||||
|
|
||||||
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();
|
let mut fd_info: IdOrdMap<FdInfo> = Default::default();
|
||||||
|
|
||||||
// Supposedly, the only possible ways this can fail are EMFILE, ENFILE, and ENOMEM.
|
// Supposedly, the only possible ways this can fail are EMFILE, ENFILE, and ENOMEM.
|
||||||
|
|
@ -240,6 +261,7 @@ impl Daemon {
|
||||||
};
|
};
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
|
config_path,
|
||||||
fd,
|
fd,
|
||||||
path,
|
path,
|
||||||
poller,
|
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.
|
// We unconditionally unlink() `path` before binding, but completely ignore the result.
|
||||||
let _ = rustix::fs::unlink(path);
|
let _ = rustix::fs::unlink(path);
|
||||||
let listener = UnixListener::bind(path)
|
let listener = UnixListener::bind(path)
|
||||||
|
|
@ -260,13 +282,18 @@ impl Daemon {
|
||||||
rustix::net::sockopt::set_socket_keepalive(&listener_owned_fd, true).unwrap();
|
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();
|
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::*;
|
use IoErrorKind::*;
|
||||||
let preferred = USER_SOCKET_DIR.join("dynix.sock").into_boxed_path();
|
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,
|
Ok(v) => v,
|
||||||
Err(e) if e.kind() == Unsupported => {
|
Err(e) if e.kind() == Unsupported => {
|
||||||
//
|
//
|
||||||
|
|
@ -279,7 +306,7 @@ impl Daemon {
|
||||||
);
|
);
|
||||||
|
|
||||||
let fallback = TMPDIR.join("dynix.sock").into_boxed_path();
|
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!(
|
error!(
|
||||||
"failed binding AF_UNIX socket at {}: {e}",
|
"failed binding AF_UNIX socket at {}: {e}",
|
||||||
fallback.display(),
|
fallback.display(),
|
||||||
|
|
@ -294,14 +321,14 @@ impl Daemon {
|
||||||
/// This panics if stdin cannot be opened.
|
/// This panics if stdin cannot be opened.
|
||||||
///
|
///
|
||||||
/// If you want to handle that error, use [`Daemon::from_raw_parts()`].
|
/// 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 stdin = io::stdin();
|
||||||
let fd = stdin
|
let fd = stdin
|
||||||
.as_fd()
|
.as_fd()
|
||||||
.try_clone_to_owned()
|
.try_clone_to_owned()
|
||||||
.expect("dynix daemon could not open stdin; try a Unix socket?");
|
.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 {
|
//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))
|
let _count = rustix::io::read(fd, spare_capacity(&mut self.cmd_buffer))
|
||||||
.tap_err(|e| error!("read() on daemon fd {fd:?} failed: {e}"))?;
|
.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.
|
// 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();
|
let stream: StreamDeserializer<_, DaemonCmd> = deserializer.into_iter();
|
||||||
for cmd in stream {
|
for cmd in stream {
|
||||||
let cmd = match cmd {
|
let cmd = match cmd {
|
||||||
|
|
@ -334,12 +364,14 @@ impl Daemon {
|
||||||
Err(e) if e.is_eof() => {
|
Err(e) if e.is_eof() => {
|
||||||
self.next_timeout = Some(Duration::from_secs(4));
|
self.next_timeout = Some(Duration::from_secs(4));
|
||||||
warn!("Didn't get a valid daemon command; giving the other side 4 seconds...");
|
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(());
|
return Ok(());
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!("error deserializing command: {e}");
|
warn!("error deserializing command: {e}");
|
||||||
debug!("command buffer was: {:?}", self.cmd_buffer.as_bstr());
|
debug!("command buffer was: {:?}", cmd_buffer.as_bstr());
|
||||||
self.cmd_buffer.clear();
|
cmd_buffer.clear();
|
||||||
|
let _ = mem::replace(&mut self.cmd_buffer, cmd_buffer);
|
||||||
// Don't propagate the error unless we have too many.
|
// Don't propagate the error unless we have too many.
|
||||||
self.fd_error_push(fd.as_raw_fd(), e.into()).tap_err(|e| {
|
self.fd_error_push(fd.as_raw_fd(), e.into()).tap_err(|e| {
|
||||||
error!("Accumulated too many errors for daemon fd {fd:?}: {e}")
|
error!("Accumulated too many errors for daemon fd {fd:?}: {e}")
|
||||||
|
|
@ -350,9 +382,51 @@ impl Daemon {
|
||||||
debug!("got cmd: {cmd:?}");
|
debug!("got cmd: {cmd:?}");
|
||||||
let _ = rustix::io::write(fd, b"");
|
let _ = rustix::io::write(fd, b"");
|
||||||
info!("dispatching command");
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
||||||
20
src/lib.rs
20
src/lib.rs
|
|
@ -35,6 +35,8 @@ pub(crate) mod prelude {
|
||||||
|
|
||||||
pub use bstr::ByteSlice;
|
pub use bstr::ByteSlice;
|
||||||
|
|
||||||
|
pub use itertools::Itertools;
|
||||||
|
|
||||||
pub use rustix::io::Errno;
|
pub use rustix::io::Errno;
|
||||||
|
|
||||||
pub use tap::{Pipe, Tap, TapFallible, TapOptional};
|
pub use tap::{Pipe, Tap, TapFallible, TapOptional};
|
||||||
|
|
@ -133,17 +135,27 @@ pub fn do_append(args: Arc<Args>, append_args: AppendCmd) -> Result<(), BoxDynEr
|
||||||
}
|
}
|
||||||
|
|
||||||
//#[tracing::instrument(level = "debug")]
|
//#[tracing::instrument(level = "debug")]
|
||||||
pub fn do_daemon(_args: Arc<Args>, daemon_args: DaemonCmd) -> Result<(), BoxDynError> {
|
pub fn do_daemon(args: Arc<Args>, daemon_args: DaemonCmd) -> Result<(), BoxDynError> {
|
||||||
|
let config_file = Path::new(&args.file);
|
||||||
|
let config_file: PathBuf = if config_file.is_relative() && !config_file.starts_with("./") {
|
||||||
|
iter::once(OsStr::new("./"))
|
||||||
|
.chain(config_file.iter())
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
config_file.to_path_buf()
|
||||||
|
};
|
||||||
|
let config_file: Arc<Path> = Arc::from(config_file);
|
||||||
|
|
||||||
// FIXME: make configurable?
|
// FIXME: make configurable?
|
||||||
let _ = rustix::process::umask(Mode::from_bits_retain(0o600).complement());
|
let _ = rustix::process::umask(Mode::from_bits_retain(0o600).complement());
|
||||||
|
|
||||||
let mut daemon = match daemon_args {
|
let mut daemon = match daemon_args {
|
||||||
DaemonCmd { stdin: true, .. } => Daemon::from_stdin(),
|
DaemonCmd { stdin: true, .. } => Daemon::from_stdin(config_file),
|
||||||
DaemonCmd { socket: None, .. } => Daemon::open_default_socket()?,
|
DaemonCmd { socket: None, .. } => Daemon::open_default_socket(config_file)?,
|
||||||
DaemonCmd {
|
DaemonCmd {
|
||||||
socket: Some(socket),
|
socket: Some(socket),
|
||||||
..
|
..
|
||||||
} => Daemon::from_unix_socket_path(&socket)?,
|
} => Daemon::from_unix_socket_path(config_file, &socket)?,
|
||||||
};
|
};
|
||||||
|
|
||||||
daemon.enter_loop().unwrap();
|
daemon.enter_loop().unwrap();
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue