A library for writing host-specific, single-binary configuration management and deployment tools
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

233 lines
6.1 KiB

7 years ago
7 years ago
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
7 years ago
7 years ago
7 years ago
5 years ago
7 years ago
5 years ago
7 years ago
5 years ago
5 years ago
7 years ago
5 years ago
5 years ago
5 years ago
7 years ago
7 years ago
5 years ago
5 years ago
7 years ago
7 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
7 years ago
7 years ago
7 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
7 years ago
7 years ago
5 years ago
7 years ago
7 years ago
5 years ago
5 years ago
5 years ago
5 years ago
7 years ago
7 years ago
7 years ago
5 years ago
7 years ago
5 years ago
5 years ago
7 years ago
7 years ago
5 years ago
5 years ago
5 years ago
7 years ago
7 years ago
5 years ago
5 years ago
5 years ago
7 years ago
7 years ago
5 years ago
7 years ago
5 years ago
7 years ago
5 years ago
5 years ago
5 years ago
7 years ago
7 years ago
5 years ago
7 years ago
5 years ago
7 years ago
7 years ago
5 years ago
5 years ago
7 years ago
  1. use std::error::Error;
  2. use std::ffi::OsStr;
  3. use std::fmt;
  4. use std::io;
  5. use std::path::Path;
  6. use std::path::PathBuf;
  7. use std::process::Output;
  8. use std::thread::sleep;
  9. use std::time::Duration;
  10. use crate::command_runner::{CommandRunner, SetuidCommandRunner};
  11. use crate::resources::Resource;
  12. use crate::symbols::file::File as FileSymbol;
  13. use crate::symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
  14. #[derive(Debug)]
  15. pub enum UserServiceError<E: Error> {
  16. ActivationFailed(io::Result<Output>),
  17. ExecError(E),
  18. GenericError,
  19. }
  20. impl From<io::Error> for UserServiceError<io::Error> {
  21. fn from(err: io::Error) -> Self {
  22. Self::ExecError(err)
  23. }
  24. }
  25. impl<E: Error> Error for UserServiceError<E> {
  26. fn description(&self) -> &str {
  27. match self {
  28. Self::ExecError(ref e) => e.description(),
  29. Self::GenericError => "Generic error",
  30. Self::ActivationFailed(_) => "Activation of service failed",
  31. }
  32. }
  33. fn cause(&self) -> Option<&dyn Error> {
  34. match self {
  35. Self::ExecError(ref e) => Some(e),
  36. _ => None,
  37. }
  38. }
  39. }
  40. impl<E: Error> fmt::Display for UserServiceError<E> {
  41. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
  42. write!(f, "{}", self.description())?;
  43. if let Self::ActivationFailed(Ok(ref log)) = self {
  44. write!(f, ": {:?}", log)?;
  45. };
  46. Ok(())
  47. }
  48. }
  49. pub struct UserService<'a, S: AsRef<Path>, U: AsRef<str>, C: AsRef<str>, R: CommandRunner> {
  50. socket_path: S,
  51. service_name: &'a str,
  52. user_name: U,
  53. command_runner: R,
  54. config: FileSymbol<C, PathBuf>,
  55. }
  56. impl<'a, S: AsRef<Path>, U: AsRef<str> + Clone, R: CommandRunner>
  57. UserService<'a, S, U, String, SetuidCommandRunner<'a, U, R>>
  58. {
  59. pub fn new_nodejs(
  60. home: &'_ Path,
  61. user_name: U,
  62. service_name: &'a str,
  63. path: &'_ Path,
  64. command_runner: &'a R,
  65. socket_path: S,
  66. ) -> Self {
  67. let content = format!(
  68. "[Service]
  69. Environment=NODE_ENV=production
  70. Environment=PORT={1}
  71. ExecStartPre=/bin/rm -f {1}
  72. ExecStart=/usr/bin/nodejs {0}
  73. ExecStartPost=/bin/sh -c 'sleep 1 && chmod 666 {1}'
  74. # FIXME: This only works if the nodejs path is a directory
  75. WorkingDirectory={0}
  76. #RuntimeDirectory=service
  77. #RuntimeDirectoryMode=766
  78. Restart=always
  79. [Install]
  80. WantedBy=default.target
  81. ",
  82. path.to_str().unwrap(),
  83. socket_path.as_ref().to_str().unwrap()
  84. );
  85. Self::new(
  86. socket_path,
  87. home,
  88. user_name,
  89. service_name,
  90. command_runner,
  91. content,
  92. )
  93. }
  94. pub fn new(
  95. socket_path: S,
  96. home: &'_ Path,
  97. user_name: U,
  98. service_name: &'a str,
  99. command_runner: &'a R,
  100. content: String,
  101. ) -> Self {
  102. let config_path: PathBuf = [
  103. home,
  104. format!(".config/systemd/user/{}.service", service_name).as_ref(),
  105. ]
  106. .iter()
  107. .collect();
  108. UserService {
  109. socket_path,
  110. service_name,
  111. user_name: user_name.clone(),
  112. command_runner: SetuidCommandRunner::new(user_name, command_runner),
  113. config: FileSymbol::new(config_path, content),
  114. }
  115. }
  116. }
  117. impl<S: AsRef<Path>, U: AsRef<str>, C: AsRef<str>, R: CommandRunner> UserService<'_, S, U, C, R> {
  118. fn systemctl_wait_for_dbus(&self, args: &[&OsStr]) -> Result<String, Box<dyn Error>> {
  119. let mut tries = 5;
  120. loop {
  121. let result = self.command_runner.run_with_args("systemctl", args)?;
  122. if result.status.success() {
  123. return Ok(String::from_utf8(result.stdout)?.trim_end().to_string());
  124. } else {
  125. let raw_stderr = String::from_utf8(result.stderr)?;
  126. let stderr = raw_stderr.trim_end();
  127. if stderr != "Failed to connect to bus: No such file or directory" {
  128. return Err(stderr.into());
  129. }
  130. }
  131. tries -= 1;
  132. if tries == 0 {
  133. return Err("Gave up waiting for dbus to appear".to_string().into());
  134. }
  135. sleep(Duration::from_millis(500));
  136. }
  137. }
  138. fn check_if_service(&self) -> Result<bool, Box<dyn Error>> {
  139. loop {
  140. let active_state = self.systemctl_wait_for_dbus(args![
  141. "--user",
  142. "show",
  143. "--property",
  144. "ActiveState",
  145. self.service_name,
  146. ])?;
  147. match active_state.as_ref() {
  148. "ActiveState=activating" => sleep(Duration::from_millis(500)),
  149. "ActiveState=active" => return Ok(true),
  150. "ActiveState=failed" => {
  151. return Err(Box::new(
  152. UserServiceError::ActivationFailed(self.command_runner.run_with_args(
  153. "journalctl",
  154. args!["--user", format!("--user-unit={}", self.service_name)],
  155. )) as UserServiceError<io::Error>,
  156. ))
  157. }
  158. _ => return Ok(false),
  159. }
  160. }
  161. }
  162. }
  163. impl<S: AsRef<Path>, U: AsRef<str>, C: AsRef<str>, R: CommandRunner> Symbol
  164. for UserService<'_, S, U, C, R>
  165. {
  166. fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
  167. if !(self.config.target_reached()?) {
  168. return Ok(false);
  169. }
  170. self.check_if_service()
  171. }
  172. fn execute(&self) -> Result<(), Box<dyn Error>> {
  173. self.config.execute()?;
  174. self.systemctl_wait_for_dbus(args!["--user", "enable", self.service_name])?;
  175. self.systemctl_wait_for_dbus(args!["--user", "restart", self.service_name])?;
  176. loop {
  177. if !(self.check_if_service()?) {
  178. return Err(Box::new(
  179. UserServiceError::GenericError as UserServiceError<io::Error>,
  180. ));
  181. }
  182. if self.socket_path.as_ref().exists() {
  183. return Ok(());
  184. }
  185. sleep(Duration::from_millis(500));
  186. }
  187. }
  188. fn get_prerequisites(&self) -> Vec<Resource> {
  189. let mut r = vec![Resource::new(
  190. "file",
  191. format!("/var/lib/systemd/linger/{}", self.user_name.as_ref()),
  192. )];
  193. r.extend(self.config.get_prerequisites().into_iter());
  194. r
  195. }
  196. fn as_action<'b>(&'b self, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b> {
  197. Box::new(SymbolAction::new(runner, self))
  198. }
  199. fn into_action<'b>(self: Box<Self>, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b>
  200. where
  201. Self: 'b,
  202. {
  203. Box::new(OwnedSymbolAction::new(runner, *self))
  204. }
  205. }
  206. impl<S: AsRef<Path>, U: AsRef<str>, C: AsRef<str>, R: CommandRunner> fmt::Display
  207. for UserService<'_, S, U, C, R>
  208. {
  209. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
  210. write!(f, "Systemd user service unit for {}", self.service_name)
  211. }
  212. }