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.

235 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
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
7 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
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
5 years ago
5 years ago
7 years ago
7 years ago
5 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
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. try!(write!(f, "{}", self.description()));
  42. if let UserServiceError::ActivationFailed(Ok(ref log)) = self {
  43. try!(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 = try!(self.command_runner.run_with_args("systemctl", args));
  118. if !result.status.success() {
  119. let raw_stderr = try!(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(
  126. try!(String::from_utf8(result.stdout))
  127. .trim_end()
  128. .to_string(),
  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 = try!(self.systemctl_wait_for_dbus(&[
  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. &["--user", &format!("--user-unit={}", self.service_name)],
  155. )) as UserServiceError<io::Error>,
  156. ))
  157. }
  158. _ => return Ok(false),
  159. }
  160. }
  161. }
  162. }
  163. impl<'a, C, R> Symbol for UserService<'a, C, R>
  164. where
  165. C: Deref<Target = str>,
  166. R: CommandRunner,
  167. {
  168. fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
  169. if !(try!(self.file.target_reached())) {
  170. return Ok(false);
  171. }
  172. self.check_if_service()
  173. }
  174. fn execute(&self) -> Result<(), Box<dyn Error>> {
  175. try!(self.file.execute());
  176. try!(self.systemctl_wait_for_dbus(&["--user", "enable", self.service_name]));
  177. try!(self.systemctl_wait_for_dbus(&["--user", "restart", self.service_name]));
  178. if !(try!(self.check_if_service())) {
  179. return Err(Box::new(
  180. UserServiceError::GenericError as UserServiceError<io::Error>,
  181. ));
  182. }
  183. let file_name = format!("/var/tmp/{}-{}.socket", self.user_name, self.service_name);
  184. fs::metadata(&file_name)
  185. .map(|_| ())
  186. .map_err(|e| Box::new(e) as Box<dyn Error>)
  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),
  192. )];
  193. r.extend(self.file.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<'a, C, R> fmt::Display for UserService<'a, C, R>
  207. where
  208. C: Deref<Target = str>,
  209. R: CommandRunner,
  210. {
  211. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  212. write!(f, "Systemd user service unit for {}", self.service_name)
  213. }
  214. }