2 * Utility functions for tests that use subprocesses.
4 * Provides utility functions for subprocess manipulation. Specifically,
5 * provides a function, run_setup, which runs a command and bails if it fails,
6 * using its error message as the bail output, and is_function_output, which
7 * runs a function in a subprocess and checks its output and exit status
8 * against expected values.
10 * Requires an Autoconf probe for sys/select.h and a replacement for a missing
13 * The canonical version of this file is maintained in the rra-c-util package,
14 * which can be found at <https://www.eyrie.org/~eagle/software/rra-c-util/>.
16 * Written by Russ Allbery <eagle@eyrie.org>
17 * Copyright 2002, 2004-2005, 2013, 2016-2017 Russ Allbery <eagle@eyrie.org>
18 * Copyright 2009-2011, 2013-2014
19 * The Board of Trustees of the Leland Stanford Junior University
21 * Permission is hereby granted, free of charge, to any person obtaining a
22 * copy of this software and associated documentation files (the "Software"),
23 * to deal in the Software without restriction, including without limitation
24 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
25 * and/or sell copies of the Software, and to permit persons to whom the
26 * Software is furnished to do so, subject to the following conditions:
28 * The above copyright notice and this permission notice shall be included in
29 * all copies or substantial portions of the Software.
31 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
32 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
33 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
34 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
35 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
36 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
37 * DEALINGS IN THE SOFTWARE.
39 * SPDX-License-Identifier: MIT
43 #include <portable/system.h>
48 #ifdef HAVE_SYS_SELECT_H
49 # include <sys/select.h>
52 #ifdef HAVE_SYS_TIME_H
53 # include <sys/time.h>
58 #include <tests/tap/basic.h>
59 #include <tests/tap/process.h>
60 #include <tests/tap/string.h>
62 /* May be defined by the build system. */
64 # define PATH_FAKEROOT ""
67 /* How long to wait for the process to start in seconds. */
68 #define PROCESS_WAIT 10
71 * Used to store information about a background process. This contains
72 * everything required to stop the process and clean up after it.
75 pid_t pid; /* PID of child process */
76 char *pidfile; /* PID file to delete on process stop */
77 char *tmpdir; /* Temporary directory for log file */
78 char *logfile; /* Log file of process output */
79 bool is_child; /* Whether we can waitpid for process */
80 struct process *next; /* Next process in global list */
84 * Global list of started processes, which will be cleaned up automatically on
85 * program exit if they haven't been explicitly stopped with process_stop
86 * prior to that point.
88 static struct process *processes = NULL;
92 * Given a function, an expected exit status, and expected output, runs that
93 * function in a subprocess, capturing stdout and stderr via a pipe, and
94 * returns the function output in newly allocated memory. Also captures the
95 * process exit status.
98 run_child_function(test_function_type function, void *data, int *status,
104 ssize_t count, ret, buflen;
107 /* Flush stdout before we start to avoid odd forking issues. */
110 /* Set up the pipe and call the function, collecting its output. */
112 sysbail("can't create pipe");
114 if (child == (pid_t) -1) {
115 sysbail("can't fork");
116 } else if (child == 0) {
117 /* In child. Set up our stdout and stderr. */
119 if (dup2(fds[1], 1) == -1)
121 if (dup2(fds[1], 2) == -1)
124 /* Now, run the function and exit successfully if it returns. */
130 * In the parent; close the extra file descriptor, read the output if
131 * any, and then collect the exit status.
135 buf = bmalloc(buflen);
138 ret = read(fds[0], buf + count, buflen - count - 1);
139 if (SSIZE_MAX - count <= ret)
140 bail("maximum output size exceeded in run_child_function");
143 if (count >= buflen - 1) {
145 buf = brealloc(buf, buflen);
149 if (waitpid(child, &rval, 0) == (pid_t) -1)
150 sysbail("waitpid failed");
154 /* Store the output and return. */
161 * Given a function, data to pass to that function, an expected exit status,
162 * and expected output, runs that function in a subprocess, capturing stdout
163 * and stderr via a pipe, and compare the combination of stdout and stderr
164 * with the expected output and the exit status with the expected status.
165 * Expects the function to always exit (not die from a signal).
168 is_function_output(test_function_type function, void *data, int status,
169 const char *output, const char *format, ...)
175 run_child_function(function, data, &rval, &buf);
177 /* Now, check the results against what we expected. */
178 va_start(args, format);
179 bvasprintf(&msg, format, args);
181 ok(WIFEXITED(rval), "%s (exited)", msg);
182 is_int(status, WEXITSTATUS(rval), "%s (status)", msg);
183 is_string(output, buf, "%s (output)", msg);
190 * A helper function for run_setup. This is a function to run an external
191 * command, suitable for passing into run_child_function. The expected
192 * argument must be an argv array, with argv[0] being the command to run.
195 exec_command(void *data)
197 char *const *argv = data;
199 execvp(argv[0], argv);
204 * Given a command expressed as an argv struct, with argv[0] the name or path
205 * to the command, run that command. If it exits with a non-zero status, use
206 * the part of its output up to the first newline as the error message when
210 run_setup(const char *const argv[])
215 run_child_function(exec_command, (void *) argv, &status, &output);
216 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
217 p = strchr(output, '\n');
220 if (output[0] != '\0')
223 bail("setup command failed with no output");
230 * Free the resources associated with tracking a process, without doing
231 * anything to the process. This is kept separate so that we can free
232 * resources during shutdown in a non-primary process.
235 process_free(struct process *process)
237 struct process **prev;
239 /* Do nothing if called with a NULL argument. */
243 /* Remove the process from the global list. */
245 while (*prev != NULL && *prev != process)
246 prev = &(*prev)->next;
247 if (*prev == process)
248 *prev = process->next;
250 /* Free resources. */
251 free(process->pidfile);
252 free(process->logfile);
253 test_tmpdir_free(process->tmpdir);
259 * Kill a process and wait for it to exit. Returns the status of the process.
260 * Calls bail on a system failure or a failure of the process to exit.
262 * We are quite aggressive with error reporting here because child processes
263 * that don't exit or that don't exist often indicate some form of test
267 process_kill(struct process *process)
272 unsigned long pid = process->pid;
274 /* If the process is not a child, just kill it and hope. */
275 if (!process->is_child) {
276 if (kill(process->pid, SIGTERM) < 0 && errno != ESRCH)
277 sysbail("cannot send SIGTERM to process %lu", pid);
281 /* Check if the process has already exited. */
282 result = waitpid(process->pid, &status, WNOHANG);
284 sysbail("cannot wait for child process %lu", pid);
289 * Kill the process and wait for it to exit. I don't want to go to the
290 * work of setting up a SIGCHLD handler or a full event loop here, so we
291 * effectively poll every tenth of a second for process exit (and
292 * hopefully faster when it does since the SIGCHLD may interrupt our
293 * select, although we're racing with it.
295 if (kill(process->pid, SIGTERM) < 0 && errno != ESRCH)
296 sysbail("cannot send SIGTERM to child process %lu", pid);
297 for (i = 0; i < PROCESS_WAIT * 10; i++) {
300 select(0, NULL, NULL, NULL, &tv);
301 result = waitpid(process->pid, &status, WNOHANG);
303 sysbail("cannot wait for child process %lu", pid);
308 /* The process still hasn't exited. Bail. */
309 bail("child process %lu did not exit on SIGTERM", pid);
311 /* Not reached, but some compilers may get confused. */
317 * Stop a particular process given its process struct. This kills the
318 * process, waits for it to exit if possible (giving it at most five seconds),
319 * and then removes it from the global processes struct so that it isn't
320 * stopped again during global shutdown.
323 process_stop(struct process *process)
326 unsigned long pid = process->pid;
328 /* Stop the process. */
329 status = process_kill(process);
331 /* Call diag to flush logs as well as provide exit status. */
332 if (process->is_child)
333 diag("stopped process %lu (exit status %d)", pid, status);
335 diag("stopped process %lu", pid);
337 /* Remove the log and PID file. */
338 diag_file_remove(process->logfile);
339 unlink(process->pidfile);
340 unlink(process->logfile);
342 /* Free resources. */
343 process_free(process);
348 * Stop all running processes. This is called as a cleanup handler during
349 * process shutdown. The first argument, which says whether the test was
350 * successful, is ignored, since the same actions should be performed
351 * regardless. The second argument says whether this is the primary process,
352 * in which case we do the full shutdown. Otherwise, we only free resources
353 * but don't stop the process.
356 process_stop_all(int success UNUSED, int primary)
358 while (processes != NULL) {
360 process_stop(processes);
362 process_free(processes);
368 * Read the PID of a process from a file. This is necessary when running
369 * under fakeroot to get the actual PID of the remctld process.
372 read_pidfile(const char *path)
378 file = fopen(path, "r");
380 sysbail("cannot open %s", path);
381 if (fgets(buffer, sizeof(buffer), file) == NULL)
382 sysbail("cannot read from %s", path);
384 pid = strtol(buffer, NULL, 10);
386 bail("cannot read PID from %s", path);
392 * Start a process and return its status information. The status information
393 * is also stored in the global processes linked list so that it can be
394 * stopped automatically on program exit.
396 * The boolean argument says whether to start the process under fakeroot. If
397 * true, PATH_FAKEROOT must be defined, generally by Autoconf. If it's not
398 * found, call skip_all.
400 * This is a helper function for process_start and process_start_fakeroot.
402 static struct process *
403 process_start_internal(const char *const argv[], const char *pidfile,
410 struct process *process;
411 const char **fakeroot_argv = NULL;
412 const char *path_fakeroot = PATH_FAKEROOT;
414 /* Check prerequisites. */
415 if (fakeroot && path_fakeroot[0] == '\0')
416 skip_all("fakeroot not found");
418 /* Create the process struct and log file. */
419 process = bcalloc(1, sizeof(struct process));
420 process->pidfile = bstrdup(pidfile);
421 process->tmpdir = test_tmpdir();
422 name = strrchr(argv[0], '/');
427 basprintf(&process->logfile, "%s/%s.log.XXXXXX", process->tmpdir, name);
428 log_fd = mkstemp(process->logfile);
430 sysbail("cannot create log file for %s", argv[0]);
432 /* If using fakeroot, rewrite argv accordingly. */
434 for (i = 0; argv[i] != NULL; i++)
436 fakeroot_argv = bcalloc(2 + i + 1, sizeof(const char *));
437 fakeroot_argv[0] = path_fakeroot;
438 fakeroot_argv[1] = "--";
439 for (i = 0; argv[i] != NULL; i++)
440 fakeroot_argv[i + 2] = argv[i];
441 fakeroot_argv[i + 2] = NULL;
442 argv = fakeroot_argv;
446 * Fork off the child process, redirect its standard output and standard
447 * error to the log file, and then exec the program.
449 process->pid = fork();
450 if (process->pid < 0)
451 sysbail("fork failed");
452 else if (process->pid == 0) {
453 if (dup2(log_fd, STDOUT_FILENO) < 0)
454 sysbail("cannot redirect standard output");
455 if (dup2(log_fd, STDERR_FILENO) < 0)
456 sysbail("cannot redirect standard error");
458 if (execv(argv[0], (char *const *) argv) < 0)
459 sysbail("exec of %s failed", argv[0]);
465 * In the parent. Wait for the child to start by watching for the PID
466 * file to appear in 100ms intervals.
468 for (i = 0; i < PROCESS_WAIT * 10 && access(pidfile, F_OK) != 0; i++) {
471 select(0, NULL, NULL, NULL, &tv);
475 * If the PID file still hasn't appeared after ten seconds, attempt to
476 * kill the process and then bail.
478 if (access(pidfile, F_OK) != 0) {
479 kill(process->pid, SIGTERM);
481 waitpid(process->pid, NULL, 0);
483 bail("cannot start %s", argv[0]);
487 * Read the PID back from the PID file. This usually isn't necessary for
488 * non-forking daemons, but always doing this makes this function general,
489 * and it's required when running under fakeroot.
492 process->pid = read_pidfile(pidfile);
493 process->is_child = !fakeroot;
495 /* Register the log file as a source of diag messages. */
496 diag_file_add(process->logfile);
499 * Add the process to our global list and set our cleanup handler if this
500 * is the first process we started.
502 if (processes == NULL)
503 test_cleanup_register(process_stop_all);
504 process->next = processes;
513 * Start a process and return the opaque process struct. The process must
514 * create pidfile with its PID when startup is complete.
517 process_start(const char *const argv[], const char *pidfile)
519 return process_start_internal(argv, pidfile, false);
524 * Start a process under fakeroot and return the opaque process struct. If
525 * fakeroot is not available, calls skip_all. The process must create pidfile
526 * with its PID when startup is complete.
529 process_start_fakeroot(const char *const argv[], const char *pidfile)
531 return process_start_internal(argv, pidfile, true);