14360: Fix tests.
[arvados.git] / services / crunch-run / background.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "encoding/json"
9         "fmt"
10         "io"
11         "io/ioutil"
12         "os"
13         "os/exec"
14         "path/filepath"
15         "strings"
16         "syscall"
17         "time"
18 )
19
20 var (
21         lockdir    = "/var/run"
22         lockprefix = "crunch-run-"
23         locksuffix = ".lock"
24 )
25
26 // procinfo is saved in each process's lockfile.
27 type procinfo struct {
28         UUID   string
29         PID    int
30         Stdout string
31         Stderr string
32 }
33
34 // Detach acquires a lock for the given uuid, and starts the current
35 // program as a child process (with -nodetach prepended to the given
36 // arguments so the child knows not to detach again). The lock is
37 // passed along to the child process.
38 func Detach(uuid string, args []string, stdout, stderr io.Writer) int {
39         return exitcode(stderr, detach(uuid, args, stdout, stderr))
40 }
41 func detach(uuid string, args []string, stdout, stderr io.Writer) error {
42         lockfile, err := os.OpenFile(filepath.Join(lockdir, lockprefix+uuid+locksuffix), os.O_CREATE|os.O_RDWR, 0700)
43         if err != nil {
44                 return err
45         }
46         defer lockfile.Close()
47         err = syscall.Flock(int(lockfile.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
48         if err != nil {
49                 return err
50         }
51         lockfile.Truncate(0)
52
53         outfile, err := ioutil.TempFile("", "crunch-run-"+uuid+"-stdout-")
54         if err != nil {
55                 return err
56         }
57         defer outfile.Close()
58         errfile, err := ioutil.TempFile("", "crunch-run-"+uuid+"-stderr-")
59         if err != nil {
60                 os.Remove(outfile.Name())
61                 return err
62         }
63         defer errfile.Close()
64
65         cmd := exec.Command(args[0], append([]string{"-nodetach"}, args[1:]...)...)
66         cmd.Stdout = outfile
67         cmd.Stderr = errfile
68         cmd.ExtraFiles = []*os.File{lockfile}
69         err = cmd.Start()
70         if err != nil {
71                 os.Remove(outfile.Name())
72                 os.Remove(errfile.Name())
73                 return err
74         }
75
76         w := io.MultiWriter(stdout, lockfile)
77         err = json.NewEncoder(w).Encode(procinfo{
78                 PID:    cmd.Process.Pid,
79                 Stdout: outfile.Name(),
80                 Stderr: errfile.Name(),
81         })
82         if err != nil {
83                 os.Remove(outfile.Name())
84                 os.Remove(errfile.Name())
85                 return err
86         }
87         return nil
88 }
89
90 // KillProcess finds the crunch-run process corresponding to the given
91 // uuid, and sends the given signal to it. It then waits up to 1
92 // second for the process to die. It returns 0 if the process is
93 // successfully killed or didn't exist in the first place.
94 func KillProcess(uuid string, signal syscall.Signal, stdout, stderr io.Writer) int {
95         return exitcode(stderr, kill(uuid, signal, stdout, stderr))
96 }
97
98 func kill(uuid string, signal syscall.Signal, stdout, stderr io.Writer) error {
99         path := filepath.Join(lockdir, lockprefix+uuid+locksuffix)
100         f, err := os.Open(path)
101         if os.IsNotExist(err) {
102                 return nil
103         } else if err != nil {
104                 return err
105         }
106         defer f.Close()
107
108         var pi procinfo
109         err = json.NewDecoder(f).Decode(&pi)
110         if err != nil {
111                 return fmt.Errorf("%s: %s\n", path, err)
112         }
113
114         if pi.UUID != uuid || pi.PID == 0 {
115                 return fmt.Errorf("%s: bogus procinfo: %+v", path, pi)
116         }
117
118         proc, err := os.FindProcess(pi.PID)
119         if err != nil {
120                 return err
121         }
122
123         err = proc.Signal(signal)
124         for deadline := time.Now().Add(time.Second); err == nil && time.Now().Before(deadline); time.Sleep(time.Second / 100) {
125                 err = proc.Signal(syscall.Signal(0))
126         }
127         if err == nil {
128                 return fmt.Errorf("pid %d: sent signal %d (%s) but process is still alive", pi.PID, signal, signal)
129         }
130         fmt.Fprintf(stderr, "pid %d: %s\n", pi.PID, err)
131         return nil
132 }
133
134 // List UUIDs of active crunch-run processes.
135 func ListProcesses(stdout, stderr io.Writer) int {
136         return exitcode(stderr, filepath.Walk(lockdir, func(path string, info os.FileInfo, err error) error {
137                 if info.IsDir() {
138                         return filepath.SkipDir
139                 }
140                 if name := info.Name(); !strings.HasPrefix(name, lockprefix) || !strings.HasSuffix(name, locksuffix) {
141                         return nil
142                 }
143                 if info.Size() == 0 {
144                         // race: process has opened/locked but hasn't yet written pid/uuid
145                         return nil
146                 }
147
148                 f, err := os.Open(path)
149                 if err != nil {
150                         return nil
151                 }
152                 defer f.Close()
153
154                 // TODO: Do this check without risk of disrupting lock
155                 // acquisition during races, e.g., by connecting to a
156                 // unix socket or checking /proc/$pid/fd/$n ->
157                 // lockfile.
158                 err = syscall.Flock(int(f.Fd()), syscall.LOCK_SH)
159                 if err == nil {
160                         // lockfile is stale
161                         err := os.Remove(path)
162                         if err != nil {
163                                 fmt.Fprintln(stderr, err)
164                         }
165                         return nil
166                 }
167
168                 var pi procinfo
169                 err = json.NewDecoder(f).Decode(&pi)
170                 if err != nil {
171                         fmt.Fprintf(stderr, "%s: %s\n", path, err)
172                         return nil
173                 }
174                 if pi.UUID == "" || pi.PID == 0 {
175                         fmt.Fprintf(stderr, "%s: bogus procinfo: %+v", path, pi)
176                         return nil
177                 }
178
179                 fmt.Fprintln(stdout, pi.UUID)
180                 return nil
181         }))
182 }
183
184 // If err is nil, return 0 ("success"); otherwise, print err to stderr
185 // and return 1.
186 func exitcode(stderr io.Writer, err error) int {
187         if err != nil {
188                 fmt.Fprintln(stderr, err)
189                 return 1
190         }
191         return 0
192 }