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.

192 lines
6.1 KiB

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