]> git.ozlabs.org Git - petitboot/blob - lib/process/process.c
f7e5b8faa2d1af4595fb479fe3d39b429184ad90
[petitboot] / lib / process / process.c
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; version 2 of the License.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9  * GNU General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public License
12  * along with this program; if not, write to the Free Software
13  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
14  */
15
16 #include <assert.h>
17 #include <errno.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <sys/wait.h>
21
22 #include <process/process.h>
23 #include <talloc/talloc.h>
24 #include <waiter/waiter.h>
25 #include <log/log.h>
26
27 struct procset {
28         struct waitset          *waitset;
29         struct list             async_list;
30         int                     sigchld_pipe[2];
31         struct waiter           *sigchld_waiter;
32         bool                    dry_run;
33 };
34
35 /* Internal data type for process handling
36  *
37  * Allocation: these structures may have multiple references:
38  *  - from the original ctx pointer
39  *  - due to inclusion in async_list
40  *  - due to a currently-registered waiter
41  *
42  */
43 struct process_info {
44 #ifdef DEBUG
45         /* prevent talloc_free(process) from working */
46         int                     __pad;
47 #endif
48         struct process          process;
49         struct list_item        async_list;
50         int                     stdout_buf_len;
51         struct waiter           *stdout_waiter;
52         int                     stdout_pipe[2];
53         void                    *orig_ctx;
54 };
55
56 static struct procset *procset;
57
58 static struct process_info *get_info(struct process *process)
59 {
60         return container_of(process, struct process_info, process);
61 }
62
63 struct process *procinfo_get_process(struct process_info *procinfo)
64 {
65         return &procinfo->process;
66 }
67
68 /* Read as much as possible into the currently-allocated stdout buffer, and
69  * possibly realloc it for the next read
70  * If the line pointer is not NULL, it is set to the start of the latest
71  * output.
72  *
73  * Returns:
74  *  > 0 on success (even though no bytes may have been read)
75  *    0 on EOF (no error, but no more reads can be performed)
76  *  < 0 on error
77  **/
78 static int process_read_stdout_once(struct process_info *procinfo, char **line)
79 {
80         struct process *process = &procinfo->process;
81         int rc, fd, max_len;
82
83         assert(process->keep_stdout);
84
85         fd = procinfo->stdout_pipe[0];
86
87         max_len =  procinfo->stdout_buf_len - process->stdout_len - 1;
88
89         rc = read(fd, process->stdout_buf + process->stdout_len, max_len);
90         if (rc == 0)
91                 return 0;
92         if (rc < 0) {
93                 if (errno == EINTR)
94                         return 1;
95                 pb_log("%s: read failed: %s\n", __func__, strerror(errno));
96                 return rc;
97         }
98
99         if (line)
100                 *line = process->stdout_buf + process->stdout_len;
101
102         process->stdout_len += rc;
103         if (process->stdout_len == procinfo->stdout_buf_len - 1) {
104                 procinfo->stdout_buf_len *= 2;
105                 process->stdout_buf = talloc_realloc(procinfo,
106                                 process->stdout_buf, char,
107                                 procinfo->stdout_buf_len);
108         }
109
110         return 1;
111 }
112
113 static int process_setup_stdout_pipe(struct process_info *procinfo)
114 {
115         int rc;
116
117         if (!procinfo->process.keep_stdout)
118                 return 0;
119
120         procinfo->stdout_buf_len = 4096;
121         procinfo->process.stdout_len = 0;
122         procinfo->process.stdout_buf = talloc_array(procinfo, char,
123                         procinfo->stdout_buf_len);
124
125         rc = pipe(procinfo->stdout_pipe);
126         if (rc) {
127                 pb_log("pipe failed");
128                 return rc;
129         }
130         return 0;
131 }
132
133 static void process_setup_stdout_parent(struct process_info *procinfo)
134 {
135         if (!procinfo->process.keep_stdout)
136                 return;
137
138         close(procinfo->stdout_pipe[1]);
139 }
140
141 static void process_setup_stdout_child(struct process_info *procinfo)
142 {
143         int log = fileno(pb_log_get_stream());
144
145         if (procinfo->process.keep_stdout)
146                 dup2(procinfo->stdout_pipe[1], STDOUT_FILENO);
147         else
148                 dup2(log, STDOUT_FILENO);
149
150         if (procinfo->process.keep_stdout && procinfo->process.add_stderr)
151                 dup2(procinfo->stdout_pipe[1], STDERR_FILENO);
152         else
153                 dup2(log, STDERR_FILENO);
154 }
155
156 static void process_finish_stdout(struct process_info *procinfo)
157 {
158         close(procinfo->stdout_pipe[0]);
159         procinfo->process.stdout_buf[procinfo->process.stdout_len] = '\0';
160 }
161
162 static int process_read_stdout(struct process_info *procinfo)
163 {
164         int rc;
165
166         if (!procinfo->process.keep_stdout)
167                 return 0;
168
169         do {
170                 rc = process_read_stdout_once(procinfo, NULL);
171         } while (rc > 0);
172
173         process_finish_stdout(procinfo);
174
175         return rc < 0 ? rc : 0;
176 }
177
178 static int process_stdout_cb(void *arg)
179 {
180         struct process_info *procinfo = arg;
181         int rc;
182
183         rc = process_read_stdout_once(procinfo, NULL);
184
185         /* if we're going to signal to the waitset that we're done (ie, non-zero
186          * return value), then the waiters will remove us, so we drop the
187          * reference */
188         if (rc < 0) {
189                 talloc_unlink(procset, procinfo);
190                 procinfo->stdout_waiter = NULL;
191                 rc = -1;
192         } else {
193                 rc = 0;
194         }
195
196         return rc;
197 }
198
199 int process_stdout_custom(struct process_info *procinfo, char **line)
200 {
201         int rc;
202
203         rc = process_read_stdout_once(procinfo, line);
204
205         /* if we're going to signal to the waitset that we're done (ie, non-zero
206          * return value), then the waiters will remove us, so we drop the
207          * reference */
208         if (rc < 0) {
209                 talloc_unlink(procset, procinfo);
210                 procinfo->stdout_waiter = NULL;
211                 rc = -1;
212         } else {
213                 rc = 0;
214         }
215
216         return rc;
217 }
218
219 static void sigchld_sigaction(int signo, siginfo_t *info,
220                 void *arg __attribute__((unused)))
221 {
222         pid_t pid;
223         int rc;
224
225         if (signo != SIGCHLD)
226                 return;
227
228         pid = info->si_pid;
229
230         rc = write(procset->sigchld_pipe[1], &pid, sizeof(pid));
231         if (rc != sizeof(pid))
232                 pb_log("%s: write failed: %s\n", __func__, strerror(errno));
233 }
234
235 static int sigchld_pipe_event(void *arg)
236 {
237         struct process_info *procinfo;
238         struct procset *procset = arg;
239         struct process *process;
240         int pid, rc;
241
242         rc = read(procset->sigchld_pipe[0], &pid, sizeof(pid));
243         if (rc != sizeof(pid))
244                 return 0;
245
246         process = NULL;
247         list_for_each_entry(&procset->async_list, procinfo, async_list) {
248                 if (procinfo->process.pid == pid) {
249                         process = &procinfo->process;
250                         break;
251                 }
252         }
253
254         /* We'll receive SIGCHLD for synchronous processes too; just ignore */
255         if (!process)
256                 return 0;
257
258         rc = waitpid(process->pid, &process->exit_status, WNOHANG);
259
260         /* if the process is still running, ignore the event. We leave
261          * the process in async_list so we can manage the final signal */
262         if (rc == 0)
263                 return 0;
264
265         /* ensure we have all of the child's stdout */
266         process_read_stdout(procinfo);
267
268         if (process->exit_cb)
269                 process->exit_cb(process);
270
271         list_remove(&procinfo->async_list);
272         talloc_unlink(procset, procinfo);
273
274         return 0;
275 }
276
277 static int process_fini(void *p)
278 {
279         struct procset *procset = p;
280         struct sigaction sa;
281
282         memset(&sa, 0, sizeof(sa));
283         sa.sa_handler = SIG_DFL;
284
285         sigaction(SIGCHLD, &sa, NULL);
286
287         waiter_remove(procset->sigchld_waiter);
288
289         close(procset->sigchld_pipe[0]);
290         close(procset->sigchld_pipe[1]);
291         return 0;
292 }
293
294 struct procset *process_init(void *ctx, struct waitset *set, bool dry_run)
295 {
296         struct sigaction sa;
297         int rc;
298
299         procset = talloc(ctx, struct procset);
300         procset->waitset = set;
301         procset->dry_run = dry_run;
302         list_init(&procset->async_list);
303
304         rc = pipe(procset->sigchld_pipe);
305         if (rc) {
306                 pb_log("%s: pipe() failed: %s\n", __func__, strerror(errno));
307                 goto err_free;
308         }
309
310         procset->sigchld_waiter = waiter_register_io(set,
311                                         procset->sigchld_pipe[0], WAIT_IN,
312                                         sigchld_pipe_event, procset);
313         if (!procset->sigchld_waiter)
314                 goto err_close;
315
316         memset(&sa, 0, sizeof(sa));
317         sa.sa_sigaction = sigchld_sigaction;
318         sa.sa_flags = SA_SIGINFO | SA_NOCLDSTOP;
319
320         rc = sigaction(SIGCHLD, &sa, NULL);
321         if (rc) {
322                 pb_log("%s: sigaction() failed: %s\n", __func__,
323                                 strerror(errno));
324                 goto err_remove;
325         }
326
327         talloc_set_destructor(procset, process_fini);
328
329         return procset;
330
331 err_remove:
332         waiter_remove(procset->sigchld_waiter);
333 err_close:
334         close(procset->sigchld_pipe[0]);
335         close(procset->sigchld_pipe[1]);
336 err_free:
337         talloc_free(procset);
338         return NULL;
339 }
340
341 struct process *process_create(void *ctx)
342 {
343         struct process_info *info = talloc_zero(ctx, struct process_info);
344         info->orig_ctx = ctx;
345         return &info->process;
346 }
347
348 void process_release(struct process *process)
349 {
350         struct process_info *info = get_info(process);
351         talloc_unlink(info->orig_ctx, info);
352 }
353
354 static int process_run_common(struct process_info *procinfo)
355 {
356         struct process *process = &procinfo->process;
357         const char *arg;
358         char *logmsg;
359         pid_t pid;
360         int rc, i;
361
362         logmsg = talloc_asprintf(procinfo, " exe:  %s\n argv:", process->path);
363         for (i = 0, arg = process->argv[i]; arg; i++, arg = process->argv[i])
364                 logmsg = talloc_asprintf_append(logmsg, " '%s'", arg);
365
366         pb_log("Running command:\n%s\n", logmsg);
367
368         rc = process_setup_stdout_pipe(procinfo);
369         if (rc)
370                 return rc;
371
372         pid = fork();
373         if (pid < 0) {
374                 pb_log("%s: fork failed: %s\n", __func__, strerror(errno));
375                 return pid;
376         }
377
378         if (pid == 0) {
379                 process_setup_stdout_child(procinfo);
380                 if (procset->dry_run)
381                         exit(EXIT_SUCCESS);
382                 execvp(process->path, (char * const *)process->argv);
383                 exit(EXIT_FAILURE);
384         }
385
386         process_setup_stdout_parent(procinfo);
387         process->pid = pid;
388
389         return 0;
390 }
391
392 int process_run_sync(struct process *process)
393 {
394         struct process_info *procinfo = get_info(process);
395         int rc;
396
397         rc = process_run_common(procinfo);
398         if (rc)
399                 return rc;
400
401         process_read_stdout(procinfo);
402
403         for (;;) {
404                 rc = waitpid(process->pid, &process->exit_status, 0);
405                 if (rc >= 0)
406                         break;
407                 if (errno == EINTR)
408                         continue;
409
410                 pb_log("%s: waitpid failed: %s\n", __func__, strerror(errno));
411                 return rc;
412         }
413
414         return 0;
415 }
416
417 int process_run_async(struct process *process)
418 {
419         struct process_info *procinfo = get_info(process);
420         waiter_cb stdout_cb;
421         int rc;
422
423         rc = process_run_common(procinfo);
424         if (rc)
425                 return rc;
426
427         if (process->keep_stdout) {
428                 stdout_cb = process->stdout_cb ?: process_stdout_cb;
429                 procinfo->stdout_waiter = waiter_register_io(procset->waitset,
430                                                 procinfo->stdout_pipe[0],
431                                                 WAIT_IN, stdout_cb, procinfo);
432                 talloc_reference(procset, procinfo);
433         }
434
435         list_add(&procset->async_list, &procinfo->async_list);
436         talloc_reference(procset, procinfo);
437
438         return 0;
439 }
440
441 void process_stop_async(struct process *process)
442 {
443         /* Avoid signalling an old pid */
444         if (process->cancelled)
445                 return;
446
447         pb_debug("process: sending SIGTERM to pid %d\n", process->pid);
448         kill(process->pid, SIGTERM);
449         process->cancelled = true;
450 }
451
452 void process_stop_async_all(void)
453 {
454         struct process_info *procinfo;
455         struct process *process = NULL;
456
457         pb_debug("process: cancelling all async jobs\n");
458
459         list_for_each_entry(&procset->async_list, procinfo, async_list) {
460                 process = &procinfo->process;
461                 /* Ignore the process completion - callbacks may use stale data */
462                 process->exit_cb = NULL;
463                 process->stdout_cb = NULL;
464                 process_stop_async(process);
465         }
466 }
467
468 int process_run_simple_argv(void *ctx, const char *argv[])
469 {
470         struct process *process;
471         int rc;
472
473         process = process_create(ctx);
474
475         process->path = argv[0];
476         process->argv = argv;
477
478         rc = process_run_sync(process);
479
480         if (!rc)
481                 rc = process->exit_status;
482
483         process_release(process);
484
485         return rc;
486 }
487
488 int process_run_simple(void *ctx, const char *name, ...)
489 {
490         int rc, i, n_argv = 1;
491         const char **argv;
492         va_list ap;
493
494         va_start(ap, name);
495         while (va_arg(ap, char *))
496                 n_argv++;
497         va_end(ap);
498
499         argv = talloc_array(ctx, const char *, n_argv + 1);
500         argv[0] = name;
501
502         va_start(ap, name);
503         for (i = 1; i < n_argv; i++)
504                 argv[i] = va_arg(ap, const char *);
505         va_end(ap);
506
507         argv[i] = NULL;
508
509         rc = process_run_simple_argv(ctx, argv);
510
511         talloc_free(argv);
512
513         return rc;
514 }
515
516 bool process_exit_ok(struct process *process)
517 {
518         return WIFEXITED(process->exit_status) &&
519                 WEXITSTATUS(process->exit_status) == 0;
520 }