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.

231 lines
6.0 KiB

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