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.

187 lines
6.0 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
  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 content = format!("[Service]
  59. ExecStartPre=/bin/rm -f /var/tmp/{1}-{2}.socket
  60. # This only works if the path is a directory
  61. WorkingDirectory={0}
  62. ExecStart=/usr/bin/nodejs {0}
  63. Restart=always
  64. Environment=NODE_ENV=production
  65. Environment=PORT=/var/tmp/{1}-{2}.socket
  66. #RuntimeDirectory=service
  67. #RuntimeDirectoryMode=766
  68. [Install]
  69. WantedBy=default.target
  70. ", path, user_name, name);
  71. NodeJsSystemdUserService {
  72. service_name: name,
  73. user_name: user_name,
  74. command_runner: SetuidCommandRunner::new(user_name, command_runner),
  75. file: FileSymbol::new(file_path, content)
  76. }
  77. }
  78. }
  79. impl<'a, C, R> NodeJsSystemdUserService<'a, C, R> where C: Deref<Target=str>, R: CommandRunner {
  80. fn systemctl_wait_for_dbus(&self, args: &[&str]) -> Result<String, Box<Error>> {
  81. let mut tries = 5;
  82. loop {
  83. let result = try!(self.command_runner.run_with_args("systemctl", args));
  84. if !result.status.success() {
  85. let raw_stderr = try!(String::from_utf8(result.stderr));
  86. let stderr = raw_stderr.trim_right();
  87. if stderr != "Failed to connect to bus: No such file or directory" {
  88. return Err(stderr.into());
  89. }
  90. } else {
  91. return Ok(try!(String::from_utf8(result.stdout)).trim_right().to_string());
  92. }
  93. tries -= 1;
  94. if tries == 0 {
  95. return Err("Gave up waiting for dbus to appear".to_string().into());
  96. }
  97. sleep(Duration::from_millis(500));
  98. }
  99. }
  100. fn check_if_service(&self) -> Result<bool, Box<Error>> {
  101. loop {
  102. let active_state = try!(self.systemctl_wait_for_dbus(&["--user", "show", "--property", "ActiveState", self.service_name]));
  103. match active_state.as_ref() {
  104. "ActiveState=activating" => sleep(Duration::from_millis(500)),
  105. "ActiveState=active" => return Ok(true),
  106. "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>)),
  107. _ => return Ok(false)
  108. }
  109. }
  110. }
  111. }
  112. fn wait_for_metadata(file_name: &str) -> Result<Metadata, Box<Error>> {
  113. let result;
  114. let mut tries = 5;
  115. loop {
  116. let metadata = fs::metadata(file_name.clone());
  117. match metadata {
  118. Ok(metadata) => {
  119. result = metadata;
  120. break;
  121. },
  122. Err(e) => {
  123. if e.kind() != io::ErrorKind::NotFound {
  124. return Err(Box::new(e));
  125. }
  126. }
  127. }
  128. tries -= 1;
  129. if tries == 0 {
  130. return Err("Gave up waiting for socket to appear".to_string().into());
  131. }
  132. sleep(Duration::from_millis(500));
  133. }
  134. Ok(result)
  135. }
  136. impl<'a, C, R> Symbol for NodeJsSystemdUserService<'a, C, R> where C: Deref<Target=str>, R: CommandRunner {
  137. fn target_reached(&self) -> Result<bool, Box<Error>> {
  138. if !(try!(self.file.target_reached())) {
  139. return Ok(false);
  140. }
  141. self.check_if_service()
  142. }
  143. fn execute(&self) -> Result<(), Box<Error>> {
  144. try!(self.file.execute());
  145. try!(self.systemctl_wait_for_dbus(&["--user", "enable", self.service_name]));
  146. try!(self.systemctl_wait_for_dbus(&["--user", "restart", self.service_name]));
  147. if !(try!(self.check_if_service())) {
  148. return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>));
  149. }
  150. let file_name = format!("/var/tmp/{}-{}.socket", self.user_name, self.service_name);
  151. let metadata = try!(wait_for_metadata(&file_name));
  152. let mut perms = metadata.permissions();
  153. perms.set_mode(0o666);
  154. try!(fs::set_permissions(file_name, perms));
  155. Ok(())
  156. }
  157. fn get_prerequisites(&self) -> Vec<Resource> {
  158. let mut r = vec![ Resource::new("file", format!("/var/lib/systemd/linger/{}", self.user_name)) ];
  159. r.extend(self.file.get_prerequisites().into_iter());
  160. r
  161. }
  162. }
  163. impl<'a, C, R> fmt::Display for NodeJsSystemdUserService<'a, C, R> where C: Deref<Target=str>, R: CommandRunner {
  164. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error>{
  165. write!(f, "Systemd Node.js user service unit for {}", self.service_name)
  166. }
  167. }