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.

170 lines
5.6 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
  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=rm /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 check_if_service(&self) -> Result<bool, Box<Error>> {
  81. loop {
  82. // Check if service is registered
  83. let active_state = try!(self.command_runner.run_with_args("systemctl", &["--user", "show", "--property", "ActiveState", self.service_name]));
  84. if !active_state.status.success() {
  85. return Err(String::from_utf8(active_state.stderr).unwrap().trim_right().into());
  86. }
  87. // Check if service is running
  88. match String::from_utf8(active_state.stdout).unwrap().trim_right() {
  89. "ActiveState=activating" => sleep(Duration::from_millis(500)),
  90. "ActiveState=active" => return Ok(true),
  91. "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>)),
  92. _ => return Ok(false)
  93. }
  94. }
  95. }
  96. }
  97. fn wait_for_metadata(file_name: &str) -> Result<Metadata, Box<Error>> {
  98. let result;
  99. let mut tries = 5;
  100. loop {
  101. let metadata = fs::metadata(file_name.clone());
  102. match metadata {
  103. Ok(metadata) => {
  104. result = metadata;
  105. break;
  106. },
  107. Err(e) => {
  108. if e.kind() != io::ErrorKind::NotFound {
  109. return Err(Box::new(e));
  110. }
  111. }
  112. }
  113. tries -= 1;
  114. if tries == 0 {
  115. return Err("Gave up waiting for socket to appear".to_string().into());
  116. }
  117. sleep(Duration::from_millis(500));
  118. }
  119. Ok(result)
  120. }
  121. impl<'a, C, R> Symbol for NodeJsSystemdUserService<'a, C, R> where C: Deref<Target=str>, R: CommandRunner {
  122. fn target_reached(&self) -> Result<bool, Box<Error>> {
  123. if !(try!(self.file.target_reached())) {
  124. return Ok(false);
  125. }
  126. self.check_if_service()
  127. }
  128. fn execute(&self) -> Result<(), Box<Error>> {
  129. try!(self.file.execute());
  130. try!(self.command_runner.run_with_args("systemctl", &["--user", "enable", self.service_name]));
  131. try!(self.command_runner.run_with_args("systemctl", &["--user", "start", self.service_name]));
  132. if !(try!(self.check_if_service())) {
  133. return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>));
  134. }
  135. let file_name = format!("/var/tmp/{}-{}.socket", self.user_name, self.service_name);
  136. let metadata = try!(wait_for_metadata(&file_name));
  137. let mut perms = metadata.permissions();
  138. perms.set_mode(0o666);
  139. try!(fs::set_permissions(file_name, perms));
  140. Ok(())
  141. }
  142. fn get_prerequisites(&self) -> Vec<Resource> {
  143. let mut r = vec![ Resource::new("file", format!("/var/lib/systemd/linger/{}", self.user_name)) ];
  144. r.extend(self.file.get_prerequisites().into_iter());
  145. r
  146. }
  147. }
  148. impl<'a, C, R> fmt::Display for NodeJsSystemdUserService<'a, C, R> where C: Deref<Target=str>, R: CommandRunner {
  149. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error>{
  150. write!(f, "Systemd Node.js user service unit for {}", self.service_name)
  151. }
  152. }