New architecture

This commit is contained in:
Adrian Heine 2019-12-26 20:50:23 +01:00
parent e4b3424ba6
commit 907a4962c5
61 changed files with 2742 additions and 3100 deletions

View file

@ -1,3 +1,7 @@
pub mod reload;
pub mod user_service;
pub mod user_session;
mod reload;
mod user_service;
mod user_session;
pub use reload::ReloadService;
pub use user_service::UserService;
pub use user_session::UserSession;

View file

@ -1,49 +1,35 @@
use std::error::Error;
use std::fmt;
use crate::command_runner::CommandRunner;
use crate::symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
use crate::symbols::Symbol;
use std::borrow::Borrow;
use std::error::Error;
use std::marker::PhantomData;
pub struct ReloadService<'a, S, C: CommandRunner> {
#[derive(Debug)]
pub struct ReloadService<_C, C, S> {
service: S,
command_runner: &'a C,
command_runner: C,
phantom: PhantomData<_C>,
}
impl<'a, S, C: CommandRunner> ReloadService<'a, S, C> {
pub fn new(service: S, command_runner: &'a C) -> Self {
ReloadService {
impl<_C, C, S> ReloadService<_C, C, S> {
pub fn new(command_runner: C, service: S) -> Self {
Self {
service,
command_runner,
phantom: PhantomData::default(),
}
}
}
impl<S: AsRef<str>, C: CommandRunner> Symbol for ReloadService<'_, S, C> {
impl<S: AsRef<str>, _C: CommandRunner, C: Borrow<_C>> Symbol for ReloadService<_C, C, S> {
fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
Ok(true)
}
fn execute(&self) -> Result<(), Box<dyn Error>> {
self.command_runner.run_successfully(
self.command_runner.borrow().run_successfully(
"systemctl",
args!["reload-or-restart", self.service.as_ref()],
)
}
fn as_action<'b>(&'b self, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b> {
Box::new(SymbolAction::new(runner, self))
}
fn into_action<'b>(self: Box<Self>, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b>
where
Self: 'b,
{
Box::new(OwnedSymbolAction::new(runner, *self))
}
}
impl<S: AsRef<str>, C: CommandRunner> fmt::Display for ReloadService<'_, S, C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "Reload service {}", self.service.as_ref())
}
}

View file

@ -1,132 +1,34 @@
use crate::command_runner::{CommandRunner, SetuidCommandRunner};
use crate::symbols::Symbol;
use std::error::Error;
use std::ffi::OsStr;
use std::fmt;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::process::Output;
use std::thread::sleep;
use std::time::Duration;
use crate::command_runner::{CommandRunner, SetuidCommandRunner};
use crate::resources::Resource;
use crate::symbols::file::File as FileSymbol;
use crate::symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
#[derive(Debug)]
pub enum UserServiceError<E: Error> {
ActivationFailed(io::Result<Output>),
ExecError(E),
GenericError,
}
impl From<io::Error> for UserServiceError<io::Error> {
fn from(err: io::Error) -> Self {
Self::ExecError(err)
}
}
impl<E: Error> Error for UserServiceError<E> {
fn description(&self) -> &str {
match self {
Self::ExecError(ref e) => e.description(),
Self::GenericError => "Generic error",
Self::ActivationFailed(_) => "Activation of service failed",
}
}
fn cause(&self) -> Option<&dyn Error> {
match self {
Self::ExecError(ref e) => Some(e),
_ => None,
}
}
}
impl<E: Error> fmt::Display for UserServiceError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{}", self.description())?;
if let Self::ActivationFailed(Ok(ref log)) = self {
write!(f, ": {:?}", log)?;
};
Ok(())
}
}
pub struct UserService<'a, S: AsRef<Path>, U: AsRef<str>, C: AsRef<str>, R: CommandRunner> {
pub struct UserService<'a, S: AsRef<Path>, U: AsRef<str>, R: CommandRunner> {
socket_path: S,
service_name: &'a str,
user_name: U,
command_runner: R,
config: FileSymbol<C, PathBuf>,
command_runner: SetuidCommandRunner<'a, U, R>,
}
impl<'a, S: AsRef<Path>, U: AsRef<str> + Clone, R: CommandRunner>
UserService<'a, S, U, String, SetuidCommandRunner<'a, U, R>>
{
pub fn new_nodejs(
home: &'_ Path,
user_name: U,
service_name: &'a str,
path: &'_ Path,
command_runner: &'a R,
socket_path: S,
) -> Self {
let content = format!(
"[Service]
Environment=NODE_ENV=production
Environment=PORT={1}
ExecStartPre=/bin/rm -f {1}
ExecStart=/usr/bin/nodejs {0}
ExecStartPost=/bin/sh -c 'sleep 1 && chmod 666 {1}'
# FIXME: This only works if the nodejs path is a directory
WorkingDirectory={0}
#RuntimeDirectory=service
#RuntimeDirectoryMode=766
Restart=always
[Install]
WantedBy=default.target
",
path.to_str().unwrap(),
socket_path.as_ref().to_str().unwrap()
);
Self::new(
socket_path,
home,
user_name,
service_name,
command_runner,
content,
)
}
impl<S: AsRef<Path>, U: AsRef<str>, R: CommandRunner> UserService<'static, S, U, R> {
pub fn new(
socket_path: S,
home: &'_ Path,
user_name: U,
service_name: &'a str,
command_runner: &'a R,
content: String,
service_name: &'static str,
command_runner: &'static R,
) -> Self {
let config_path: PathBuf = [
home,
format!(".config/systemd/user/{}.service", service_name).as_ref(),
]
.iter()
.collect();
UserService {
Self {
socket_path,
service_name,
user_name: user_name.clone(),
command_runner: SetuidCommandRunner::new(user_name, command_runner),
config: FileSymbol::new(config_path, content),
}
}
}
impl<S: AsRef<Path>, U: AsRef<str>, C: AsRef<str>, R: CommandRunner> UserService<'_, S, U, C, R> {
impl<S: AsRef<Path>, U: AsRef<str>, R: CommandRunner> UserService<'_, S, U, R> {
fn systemctl_wait_for_dbus(&self, args: &[&OsStr]) -> Result<String, Box<dyn Error>> {
let mut tries = 5;
loop {
@ -161,12 +63,13 @@ impl<S: AsRef<Path>, U: AsRef<str>, C: AsRef<str>, R: CommandRunner> UserService
"ActiveState=activating" => sleep(Duration::from_millis(500)),
"ActiveState=active" => return Ok(true),
"ActiveState=failed" => {
return Err(Box::new(
UserServiceError::ActivationFailed(self.command_runner.run_with_args(
return Err(
String::from_utf8(self.command_runner.get_output(
"journalctl",
args!["--user", format!("--user-unit={}", self.service_name)],
)) as UserServiceError<io::Error>,
))
)?)?
.into(),
)
}
_ => return Ok(false),
}
@ -174,26 +77,18 @@ impl<S: AsRef<Path>, U: AsRef<str>, C: AsRef<str>, R: CommandRunner> UserService
}
}
impl<S: AsRef<Path>, U: AsRef<str>, C: AsRef<str>, R: CommandRunner> Symbol
for UserService<'_, S, U, C, R>
{
impl<S: AsRef<Path>, U: AsRef<str>, R: CommandRunner> Symbol for UserService<'_, S, U, R> {
fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
if !(self.config.target_reached()?) {
return Ok(false);
}
self.check_if_service()
}
fn execute(&self) -> Result<(), Box<dyn Error>> {
self.config.execute()?;
self.systemctl_wait_for_dbus(args!["--user", "enable", self.service_name])?;
self.systemctl_wait_for_dbus(args!["--user", "restart", self.service_name])?;
loop {
if !(self.check_if_service()?) {
return Err(Box::new(
UserServiceError::GenericError as UserServiceError<io::Error>,
));
return Err("Generic error".into());
}
if self.socket_path.as_ref().exists() {
@ -202,32 +97,4 @@ impl<S: AsRef<Path>, U: AsRef<str>, C: AsRef<str>, R: CommandRunner> Symbol
sleep(Duration::from_millis(500));
}
}
fn get_prerequisites(&self) -> Vec<Resource> {
let mut r = vec![Resource::new(
"file",
format!("/var/lib/systemd/linger/{}", self.user_name.as_ref()),
)];
r.extend(self.config.get_prerequisites().into_iter());
r
}
fn as_action<'b>(&'b self, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b> {
Box::new(SymbolAction::new(runner, self))
}
fn into_action<'b>(self: Box<Self>, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b>
where
Self: 'b,
{
Box::new(OwnedSymbolAction::new(runner, *self))
}
}
impl<S: AsRef<Path>, U: AsRef<str>, C: AsRef<str>, R: CommandRunner> fmt::Display
for UserService<'_, S, U, C, R>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "Systemd user service unit for {}", self.service_name)
}
}

View file

@ -1,55 +1,26 @@
use std::error::Error;
use std::fmt;
use std::path::PathBuf;
use crate::command_runner::CommandRunner;
use crate::symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
use crate::symbols::Symbol;
use std::error::Error;
use std::path::Path;
#[derive(Debug)]
pub enum SystemdUserSessionError<E: Error> {
ExecError(E),
GenericError,
}
impl<E: Error> Error for SystemdUserSessionError<E> {
fn description(&self) -> &str {
match self {
Self::ExecError(ref e) => e.description(),
Self::GenericError => "Generic error",
}
}
fn cause(&self) -> Option<&dyn Error> {
match self {
Self::ExecError(ref e) => Some(e),
_ => None,
}
}
}
impl<E: Error> fmt::Display for SystemdUserSessionError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{}", self.description())
}
}
pub struct SystemdUserSession<'a, U: AsRef<str>, C: CommandRunner> {
pub struct UserSession<'a, U, C> {
user_name: U,
command_runner: &'a C,
}
impl<'a, U: AsRef<str>, C: CommandRunner> SystemdUserSession<'a, U, C> {
impl<'a, U, C> UserSession<'a, U, C> {
pub fn new(user_name: U, command_runner: &'a C) -> Self {
SystemdUserSession {
Self {
user_name,
command_runner,
}
}
}
impl<U: AsRef<str>, C: CommandRunner> Symbol for SystemdUserSession<'_, U, C> {
impl<U: AsRef<str>, C: CommandRunner> Symbol for UserSession<'_, U, C> {
fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
let mut path = PathBuf::from("/var/lib/systemd/linger");
path.push(self.user_name.as_ref());
let path = Path::new("/var/lib/systemd/linger").join(self.user_name.as_ref());
Ok(path.exists())
// Could also do `loginctl show-user ${self.user_name} | grep -F 'Linger=yes`
}
@ -59,21 +30,4 @@ impl<U: AsRef<str>, C: CommandRunner> Symbol for SystemdUserSession<'_, U, C> {
.command_runner
.run_successfully("loginctl", args!["enable-linger", self.user_name.as_ref()])
}
fn as_action<'b>(&'b self, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b> {
Box::new(SymbolAction::new(runner, self))
}
fn into_action<'b>(self: Box<Self>, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b>
where
Self: 'b,
{
Box::new(OwnedSymbolAction::new(runner, *self))
}
}
impl<U: AsRef<str>, C: CommandRunner> fmt::Display for SystemdUserSession<'_, U, C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "Systemd user session for {}", self.user_name.as_ref())
}
}