manager.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. package rintegration
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "sort"
  9. "strings"
  10. "sync"
  11. "syscall"
  12. "time"
  13. )
  14. var (
  15. // ErrNotRunning is returned by Stop when no process exists for the slug.
  16. ErrNotRunning = errors.New("integration process not running")
  17. // ErrAlreadyRunning is returned by Start when a process is already up.
  18. ErrAlreadyRunning = errors.New("integration process already running")
  19. )
  20. // Manager supervises pusher processes in memory (no systemd: the service runs
  21. // as an unprivileged user). It owns the on-disk directory that holds each
  22. // slug's environment file, log file and extracted binary.
  23. type Manager struct {
  24. dir string
  25. mu sync.Mutex
  26. procs map[string]*proc
  27. fetch *Fetcher
  28. onExit func(slug string, err error)
  29. }
  30. type proc struct {
  31. cmd *exec.Cmd
  32. done chan struct{}
  33. stopping bool // guarded by Manager.mu
  34. }
  35. // NewManager builds a Manager rooted at dir.
  36. func NewManager(dir string) *Manager {
  37. return &Manager{dir: dir, procs: map[string]*proc{}, fetch: NewFetcher()}
  38. }
  39. // Fetch returns the shared release fetcher.
  40. func (m *Manager) Fetch() *Fetcher { return m.fetch }
  41. // Dir returns the on-disk root for environments, logs and binaries.
  42. func (m *Manager) Dir() string { return m.dir }
  43. // Env returns the environment file of a slug as a map. The password and the
  44. // token live only in that file, so editing an integration reads it first and
  45. // rewrites it with the changed keys instead of rebuilding it from scratch.
  46. func (m *Manager) Env(slug string) (map[string]string, error) {
  47. return readEnvFile(filepath.Join(m.dir, slug+".env"))
  48. }
  49. // WriteEnv replaces the environment file of a slug, keeping mode 0600.
  50. func (m *Manager) WriteEnv(slug string, env map[string]string) error {
  51. if err := os.MkdirAll(m.dir, 0o755); err != nil {
  52. return err
  53. }
  54. return writeEnvFile(filepath.Join(m.dir, slug+".env"), env)
  55. }
  56. // SSHPasswordPath returns the companion SSH password file of a slug
  57. // (<dir>/<slug>.sshpass, #1708). Same discipline as the env file: 0600,
  58. // owned by the service user, never in the database and never in an API
  59. // response.
  60. func (m *Manager) SSHPasswordPath(slug string) string {
  61. return filepath.Join(m.dir, slug+".sshpass")
  62. }
  63. // ReadSSHPassword returns the SSH password stored for slug, or "" when the
  64. // companion file does not exist (the server key stays the auth method). A
  65. // trailing newline (hand-written files) is tolerated.
  66. func (m *Manager) ReadSSHPassword(slug string) (string, error) {
  67. data, err := os.ReadFile(m.SSHPasswordPath(slug))
  68. if os.IsNotExist(err) {
  69. return "", nil
  70. }
  71. if err != nil {
  72. return "", err
  73. }
  74. return strings.TrimRight(string(data), "\n"), nil
  75. }
  76. // WriteSSHPassword stores the SSH password of slug in the companion file
  77. // with mode 0600.
  78. func (m *Manager) WriteSSHPassword(slug, password string) error {
  79. if err := os.MkdirAll(m.dir, 0o755); err != nil {
  80. return err
  81. }
  82. return os.WriteFile(m.SSHPasswordPath(slug), []byte(password), 0o600)
  83. }
  84. // RemoveSSHPassword deletes the companion SSH password file. Removing a
  85. // missing file is a no-op.
  86. func (m *Manager) RemoveSSHPassword(slug string) error {
  87. if err := os.Remove(m.SSHPasswordPath(slug)); err != nil && !os.IsNotExist(err) {
  88. return err
  89. }
  90. return nil
  91. }
  92. // SetOnExit registers the callback invoked when a process exits unexpectedly
  93. // (a crash). Intentional stops do not fire it: the caller owns that state.
  94. func (m *Manager) SetOnExit(fn func(slug string, err error)) {
  95. m.mu.Lock()
  96. m.onExit = fn
  97. m.mu.Unlock()
  98. }
  99. // Start launches the pusher binary for slug. When env is non-empty it is
  100. // written to <dir>/<slug>.env (0600); otherwise the existing env file is
  101. // reused, which is how restarts recover the password/token that live only
  102. // there. The process gets the vars in its environment, runs in its own
  103. // process group, and logs stdout/stderr to <dir>/<slug>.log.
  104. func (m *Manager) Start(slug string, env map[string]string, binPath string) error {
  105. if m.Running(slug) {
  106. return ErrAlreadyRunning
  107. }
  108. if err := os.MkdirAll(m.dir, 0o755); err != nil {
  109. return err
  110. }
  111. envPath := filepath.Join(m.dir, slug+".env")
  112. if len(env) > 0 {
  113. if err := writeEnvFile(envPath, env); err != nil {
  114. return err
  115. }
  116. }
  117. processEnv, err := readEnvFile(envPath)
  118. if err != nil {
  119. return fmt.Errorf("integration %s: %w", slug, err)
  120. }
  121. logPath := filepath.Join(m.dir, slug+".log")
  122. logf, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
  123. if err != nil {
  124. return err
  125. }
  126. cmd := exec.Command(binPath)
  127. cmd.Dir = m.dir
  128. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
  129. cmd.Stdout = logf
  130. cmd.Stderr = logf
  131. cmd.Env = append(os.Environ(), envMapToList(processEnv)...)
  132. if err := cmd.Start(); err != nil {
  133. logf.Close()
  134. return err
  135. }
  136. p := &proc{cmd: cmd, done: make(chan struct{})}
  137. m.mu.Lock()
  138. m.procs[slug] = p
  139. m.mu.Unlock()
  140. go func() {
  141. err := cmd.Wait()
  142. logf.Close()
  143. m.mu.Lock()
  144. cur := m.procs[slug]
  145. stopping := cur != nil && cur.stopping
  146. delete(m.procs, slug)
  147. onExit := m.onExit
  148. m.mu.Unlock()
  149. close(p.done)
  150. if !stopping && onExit != nil {
  151. onExit(slug, err)
  152. }
  153. }()
  154. return nil
  155. }
  156. // Stop sends SIGTERM to the process group, waits up to 10s, then SIGKILL.
  157. func (m *Manager) Stop(slug string) error {
  158. m.mu.Lock()
  159. p, ok := m.procs[slug]
  160. if !ok {
  161. m.mu.Unlock()
  162. return ErrNotRunning
  163. }
  164. p.stopping = true
  165. m.mu.Unlock()
  166. _ = syscall.Kill(-p.cmd.Process.Pid, syscall.SIGTERM)
  167. select {
  168. case <-p.done:
  169. return nil
  170. case <-time.After(10 * time.Second):
  171. _ = syscall.Kill(-p.cmd.Process.Pid, syscall.SIGKILL)
  172. <-p.done
  173. return nil
  174. }
  175. }
  176. // Running reports whether a process is currently tracked for the slug.
  177. func (m *Manager) Running(slug string) bool {
  178. m.mu.Lock()
  179. _, ok := m.procs[slug]
  180. m.mu.Unlock()
  181. return ok
  182. }
  183. // StopAll stops every tracked process (used on graceful shutdown).
  184. func (m *Manager) StopAll() {
  185. m.mu.Lock()
  186. slugs := make([]string, 0, len(m.procs))
  187. for s := range m.procs {
  188. slugs = append(slugs, s)
  189. }
  190. m.mu.Unlock()
  191. sort.Strings(slugs)
  192. for _, s := range slugs {
  193. _ = m.Stop(s)
  194. }
  195. }
  196. // Cleanup removes the env file, log file and extracted directory for a slug.
  197. // Errors are collected and returned; it is safe to call when nothing exists.
  198. func (m *Manager) Cleanup(slug string) error {
  199. var errs []string
  200. for _, p := range []string{
  201. filepath.Join(m.dir, slug+".env"),
  202. filepath.Join(m.dir, slug+".log"),
  203. } {
  204. if err := os.Remove(p); err != nil && !os.IsNotExist(err) {
  205. errs = append(errs, err.Error())
  206. }
  207. }
  208. if err := os.RemoveAll(filepath.Join(m.dir, slug)); err != nil {
  209. errs = append(errs, err.Error())
  210. }
  211. if len(errs) > 0 {
  212. return errors.New(strings.Join(errs, "; "))
  213. }
  214. return nil
  215. }
  216. // EscapeEnvValue escapes a value so it stays on one line of a KEY=value env
  217. // file and can be read back losslessly by UnescapeEnvValue.
  218. func EscapeEnvValue(v string) string {
  219. var b strings.Builder
  220. for _, r := range v {
  221. switch r {
  222. case '\\':
  223. b.WriteString(`\\`)
  224. case '\n':
  225. b.WriteString(`\n`)
  226. case '\r':
  227. b.WriteString(`\r`)
  228. case '\t':
  229. b.WriteString(`\t`)
  230. default:
  231. b.WriteRune(r)
  232. }
  233. }
  234. return b.String()
  235. }
  236. // UnescapeEnvValue reverses EscapeEnvValue.
  237. func UnescapeEnvValue(v string) string {
  238. runes := []rune(v)
  239. var b strings.Builder
  240. for i := 0; i < len(runes); i++ {
  241. if runes[i] == '\\' && i+1 < len(runes) {
  242. switch runes[i+1] {
  243. case '\\':
  244. b.WriteRune('\\')
  245. case 'n':
  246. b.WriteRune('\n')
  247. case 'r':
  248. b.WriteRune('\r')
  249. case 't':
  250. b.WriteRune('\t')
  251. default:
  252. b.WriteRune('\\')
  253. b.WriteRune(runes[i+1])
  254. }
  255. i++
  256. continue
  257. }
  258. b.WriteRune(runes[i])
  259. }
  260. return b.String()
  261. }
  262. func envMapToList(env map[string]string) []string {
  263. keys := make([]string, 0, len(env))
  264. for k := range env {
  265. keys = append(keys, k)
  266. }
  267. sort.Strings(keys)
  268. out := make([]string, 0, len(env))
  269. for _, k := range keys {
  270. out = append(out, k+"="+env[k])
  271. }
  272. return out
  273. }
  274. func writeEnvFile(path string, env map[string]string) error {
  275. keys := make([]string, 0, len(env))
  276. for k := range env {
  277. keys = append(keys, k)
  278. }
  279. sort.Strings(keys)
  280. var b strings.Builder
  281. for _, k := range keys {
  282. b.WriteString(k)
  283. b.WriteByte('=')
  284. b.WriteString(EscapeEnvValue(env[k]))
  285. b.WriteByte('\n')
  286. }
  287. return os.WriteFile(path, []byte(b.String()), 0o600)
  288. }
  289. func readEnvFile(path string) (map[string]string, error) {
  290. data, err := os.ReadFile(path)
  291. if err != nil {
  292. return nil, err
  293. }
  294. return ParseEnv(string(data)), nil
  295. }
  296. // ParseEnv parses a KEY=value env file body into a map, unescaping the values
  297. // written by EscapeEnvValue. It is also used on the output of a remote read.
  298. func ParseEnv(body string) map[string]string {
  299. out := map[string]string{}
  300. for _, line := range strings.Split(body, "\n") {
  301. line = strings.TrimRight(line, "\r")
  302. if line == "" {
  303. continue
  304. }
  305. i := strings.IndexByte(line, '=')
  306. if i < 0 {
  307. continue
  308. }
  309. out[line[:i]] = UnescapeEnvValue(line[i+1:])
  310. }
  311. return out
  312. }