Debian Codegraph @

t/cmd/lfstest-count-tests.go

raw symbols SCIP
1 package main
2
3 import (
4 "context"
5 "fmt"
6 "io"
7 "net/http"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "runtime"
12 "strconv"
13 "strings"
14 "time"
15 )
16
17 var (
18 // countFile is the path to a file (relative to the $LFSTEST_DIR) who's
19 // contents is the number of actively-running integration tests.
20 countFile = "test_count"
21 // lockFile is the path to a file (relative to the $LFSTEST_DIR) who's
22 // presence indicates that another invocation of the lfstest-count-tests
23 // program is modifying the test_count.
24 lockFile = "test_count.lock"
25
26 // lockAcquireTimeout is the maximum amount of time that we will wait
27 // for lockFile to become available (and thus the amount of time that we
28 // will wait in order to acquire the lock).
29 lockAcquireTimeout = 5 * time.Second
30
31 // errCouldNotAcquire indicates that the program could not acquire the
32 // lock needed to modify the test_count. It is a fatal error.
33 errCouldNotAcquire = fmt.Errorf("could not acquire lock, dying")
34 // errNegativeCount indicates that the count in test_count was negative,
35 // which is unexpected and makes this script behave in an undefined
36 // fashion
37 errNegativeCount = fmt.Errorf("unexpected negative count")
38 )
39
40 // countFn is a type signature that all functions who wish to modify the
41 // test_count must inhabit.
42 //
43 // The first and only formal parameter is the current number of running tests
44 // found in test_count after acquiring the lock.
45 //
46 // The returned tuple indicates (1) the new number that should be written to
47 // test_count, and (2) if there was an error in computing that value. If err is
48 // non-nil, the program will exit and test_count will not be updated.
49 type countFn func(int) (int, error)
50
51 func main() {
52 if len(os.Args) > 2 {
53 fmt.Fprintf(os.Stderr,
54 "usage: %s [increment|decrement]\n", os.Args[0])
55 os.Exit(1)
56 }
57
58 ctx, cancel := context.WithTimeout(
59 context.Background(), lockAcquireTimeout)
60 defer cancel()
61
62 if err := acquire(ctx); err != nil {
63 fatal(err)
64 }
65 defer func() {
66 if err := release(); err != nil {
67 fmt.Fprintf(os.Stderr, "unable to release lock file: %s\n", err)
68 }
69 }()
70
71 if len(os.Args) == 1 {
72 // Calling with no arguments indicates that we simply want to
73 // read the contents of test_count.
74 callWithCount(func(n int) (int, error) {
75 fmt.Fprintf(os.Stdout, "%d\n", n)
76 return n, nil
77 })
78 return
79 }
80
81 var err error
82
83 switch strings.ToLower(os.Args[1]) {
84 case "increment":
85 err = callWithCount(func(n int) (int, error) {
86 if n > 0 {
87 // If n>1, it is therefore true that a
88 // lfstest-gitserver invocation is already
89 // running.
90 //
91 // Hence, let's do nothing here other than
92 // increase the count.
93 return n + 1, nil
94 }
95
96 // The lfstest-gitserver invocation (see: below) does
97 // not itself create a gitserver.log in the appropriate
98 // directory. Thus, let's create it ourselves instead.
99 log, err := os.Create(fmt.Sprintf(
100 "%s/gitserver.log", os.Getenv("LFSTEST_DIR")))
101 if err != nil {
102 return n, err
103 }
104
105 // The executable name depends on the X environment
106 // variable, which is set in script/cibuild.
107 var cmd *exec.Cmd
108 if runtime.GOOS == "windows" {
109 cmd = exec.Command("lfstest-gitserver.exe")
110 } else {
111 cmd = exec.Command("lfstest-gitserver")
112 }
113
114 // The following are ported from the old
115 // test/testhelpers.sh, and comprise the requisite
116 // environment variables needed to run
117 // lfstest-gitserver.
118 cmd.Env = append(os.Environ(),
119 fmt.Sprintf("LFSTEST_URL=%s", os.Getenv("LFSTEST_URL")),
120 fmt.Sprintf("LFSTEST_SSL_URL=%s", os.Getenv("LFSTEST_SSL_URL")),
121 fmt.Sprintf("LFSTEST_CLIENT_CERT_URL=%s", os.Getenv("LFSTEST_CLIENT_CERT_URL")),
122 fmt.Sprintf("LFSTEST_DIR=%s", os.Getenv("LFSTEST_DIR")),
123 fmt.Sprintf("LFSTEST_CERT=%s", os.Getenv("LFSTEST_CERT")),
124 fmt.Sprintf("LFSTEST_CLIENT_CERT=%s", os.Getenv("LFSTEST_CLIENT_CERT")),
125 fmt.Sprintf("LFSTEST_CLIENT_KEY=%s", os.Getenv("LFSTEST_CLIENT_KEY")),
126 )
127 cmd.Stdout = log
128 cmd.Stderr = log
129
130 // Start performs a fork/execve, hence we can abandon
131 // this process once it has started.
132 if err := cmd.Start(); err != nil {
133 return n, err
134 }
135 return 1, nil
136 })
137 case "decrement":
138 err = callWithCount(func(n int) (int, error) {
139 if n > 1 {
140 // If there is at least two tests running, we
141 // need not shutdown a lfstest-gitserver
142 // instance.
143 return n - 1, nil
144 }
145
146 // Otherwise, we need to POST to /shutdown, which will
147 // cause the lfstest-gitserver to abort itself.
148 url, err := os.ReadFile(os.Getenv("LFS_URL_FILE"))
149 if err == nil {
150 _, err = http.Post(string(url)+"/shutdown",
151 "application/text",
152 strings.NewReader(time.Now().String()))
153 }
154
155 return 0, nil
156 })
157 }
158
159 if err != nil {
160 fatal(err)
161 }
162 }
163
164 var (
165 // acquireTick is the constant time that one tick (i.e., one attempt at
166 // acquiring the lock) should last.
167 acquireTick = 10 * time.Millisecond
168 )
169
170 // acquire acquires the lock file necessary to perform updates to test_count,
171 // and returns an error if that lock cannot be acquired.
172 func acquire(ctx context.Context) error {
173 path, err := path(lockFile)
174 if err != nil {
175 return err
176 }
177
178 tick := time.NewTicker(acquireTick)
179 defer tick.Stop()
180
181 for {
182 select {
183 case <-tick.C:
184 // Try every tick of the above ticker before giving up
185 // and trying again.
186 f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
187 if err == nil || !os.IsExist(err) {
188 if err == nil {
189 f.Close()
190 }
191 return err
192 }
193 case <-ctx.Done():
194 // If the context.Context above has reached its
195 // deadline, we must give up.
196 return errCouldNotAcquire
197 }
198 }
199 }
200
201 // release releases the lock file so that another process can take over, or
202 // returns an error.
203 func release() error {
204 path, err := path(lockFile)
205 if err != nil {
206 return err
207 }
208 return os.Remove(path)
209 }
210
211 // callWithCount calls the given countFn with the current count in test_count,
212 // and updates it with what the function returns.
213 //
214 // If the function produced an error, that will be returned instead.
215 func callWithCount(fn countFn) error {
216 path, err := path(countFile)
217 if err != nil {
218 return err
219 }
220
221 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0666)
222 if err != nil {
223 return err
224 }
225
226 contents, err := io.ReadAll(f)
227 if err != nil {
228 return err
229 }
230
231 var n int = 0
232 if len(contents) != 0 {
233 n, err = strconv.Atoi(string(contents))
234 if err != nil {
235 return err
236 }
237
238 if n < 0 {
239 return errNegativeCount
240 }
241 }
242
243 after, err := fn(n)
244 if err != nil {
245 return err
246 }
247
248 // We want to write over the contents in the file, so "truncate" the
249 // file to a length of 0, and then seek to the beginning of the file to
250 // update the write head.
251 if err := f.Truncate(0); err != nil {
252 return err
253 }
254 if _, err := f.Seek(0, io.SeekStart); err != nil {
255 return err
256 }
257
258 if _, err := fmt.Fprintf(f, "%d", after); err != nil {
259 return err
260 }
261 return nil
262 }
263
264 // path returns an absolute path corresponding to any given path relative to the
265 // 't' directory of the current checkout of Git LFS.
266 func path(s string) (string, error) {
267 p := filepath.Join(filepath.Dir(os.Getenv("LFSTEST_DIR")), s)
268 if err := os.MkdirAll(filepath.Dir(p), 0777); err != nil {
269 return "", err
270 }
271 return p, nil
272 }
273
274 // fatal reports the given error (if non-nil), and then dies. If the error was
275 // nil, nothing happens.
276 func fatal(err error) {
277 if err == nil {
278 return
279 }
280 if err := release(); err != nil {
281 fmt.Fprintf(os.Stderr, "fatal: while dying, got: %s\n", err)
282 }
283 fmt.Fprintf(os.Stderr, "fatal: %s\n", err)
284 os.Exit(1)
285 }