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.

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