5dd34b3a7c8c4ca9ed0b7e5243fb92745efce07f
[sliver-openvswitch.git] / lib / process.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "process.h"
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27 #include "coverage.h"
28 #include "dynamic-string.h"
29 #include "fatal-signal.h"
30 #include "list.h"
31 #include "ovs-thread.h"
32 #include "poll-loop.h"
33 #include "signals.h"
34 #include "socket-util.h"
35 #include "util.h"
36 #include "vlog.h"
37
38 VLOG_DEFINE_THIS_MODULE(process);
39
40 COVERAGE_DEFINE(process_start);
41
42 struct process {
43     struct list node;
44     char *name;
45     pid_t pid;
46
47     /* State. */
48     bool exited;
49     int status;
50 };
51
52 /* Pipe used to signal child termination. */
53 static int fds[2];
54
55 /* All processes. */
56 static struct list all_processes = LIST_INITIALIZER(&all_processes);
57
58 static void sigchld_handler(int signr OVS_UNUSED);
59
60 /* Initializes the process subsystem (if it is not already initialized).  Calls
61  * exit() if initialization fails.
62  *
63  * This function may not be called after creating any additional threads.
64  *
65  * Calling this function is optional; it will be called automatically by
66  * process_start() if necessary.  Calling it explicitly allows the client to
67  * prevent the process from exiting at an unexpected time. */
68 void
69 process_init(void)
70 {
71     static bool inited;
72     struct sigaction sa;
73
74     assert_single_threaded();
75     if (inited) {
76         return;
77     }
78     inited = true;
79
80     /* Create notification pipe. */
81     xpipe_nonblocking(fds);
82
83     /* Set up child termination signal handler. */
84     memset(&sa, 0, sizeof sa);
85     sa.sa_handler = sigchld_handler;
86     sigemptyset(&sa.sa_mask);
87     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
88     xsigaction(SIGCHLD, &sa, NULL);
89 }
90
91 char *
92 process_escape_args(char **argv)
93 {
94     struct ds ds = DS_EMPTY_INITIALIZER;
95     char **argp;
96     for (argp = argv; *argp; argp++) {
97         const char *arg = *argp;
98         const char *p;
99         if (argp != argv) {
100             ds_put_char(&ds, ' ');
101         }
102         if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
103             ds_put_char(&ds, '"');
104             for (p = arg; *p; p++) {
105                 if (*p == '\\' || *p == '\"') {
106                     ds_put_char(&ds, '\\');
107                 }
108                 ds_put_char(&ds, *p);
109             }
110             ds_put_char(&ds, '"');
111         } else {
112             ds_put_cstr(&ds, arg);
113         }
114     }
115     return ds_cstr(&ds);
116 }
117
118 /* Prepare to start a process whose command-line arguments are given by the
119  * null-terminated 'argv' array.  Returns 0 if successful, otherwise a
120  * positive errno value. */
121 static int
122 process_prestart(char **argv)
123 {
124     char *binary;
125
126     process_init();
127
128     /* Log the process to be started. */
129     if (VLOG_IS_DBG_ENABLED()) {
130         char *args = process_escape_args(argv);
131         VLOG_DBG("starting subprocess: %s", args);
132         free(args);
133     }
134
135     /* execvp() will search PATH too, but the error in that case is more
136      * obscure, since it is only reported post-fork. */
137     binary = process_search_path(argv[0]);
138     if (!binary) {
139         VLOG_ERR("%s not found in PATH", argv[0]);
140         return ENOENT;
141     }
142     free(binary);
143
144     return 0;
145 }
146
147 /* Creates and returns a new struct process with the specified 'name' and
148  * 'pid'. */
149 static struct process *
150 process_register(const char *name, pid_t pid)
151 {
152     struct process *p;
153     const char *slash;
154
155     p = xzalloc(sizeof *p);
156     p->pid = pid;
157     slash = strrchr(name, '/');
158     p->name = xstrdup(slash ? slash + 1 : name);
159     p->exited = false;
160
161     list_push_back(&all_processes, &p->node);
162
163     return p;
164 }
165
166 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
167  * argv[0] is used as the name of the process.  Searches the PATH environment
168  * variable to find the program to execute.
169  *
170  * This function may not be called after creating any additional threads.
171  *
172  * All file descriptors are closed before executing the subprocess, except for
173  * fds 0, 1, and 2.
174  *
175  * Returns 0 if successful, otherwise a positive errno value indicating the
176  * error.  If successful, '*pp' is assigned a new struct process that may be
177  * used to query the process's status.  On failure, '*pp' is set to NULL. */
178 int
179 process_start(char **argv, struct process **pp)
180 {
181     pid_t pid;
182     int error;
183
184     assert_single_threaded();
185
186     *pp = NULL;
187     COVERAGE_INC(process_start);
188     error = process_prestart(argv);
189     if (error) {
190         return error;
191     }
192
193     pid = fork();
194     if (pid < 0) {
195         VLOG_WARN("fork failed: %s", ovs_strerror(errno));
196         return errno;
197     } else if (pid) {
198         /* Running in parent process. */
199         *pp = process_register(argv[0], pid);
200         return 0;
201     } else {
202         /* Running in child process. */
203         int fd_max = get_max_fds();
204         int fd;
205
206         fatal_signal_fork();
207         for (fd = 3; fd < fd_max; fd++) {
208             close(fd);
209         }
210         execvp(argv[0], argv);
211         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
212                 argv[0], ovs_strerror(errno));
213         _exit(1);
214     }
215 }
216
217 /* Destroys process 'p'. */
218 void
219 process_destroy(struct process *p)
220 {
221     if (p) {
222         list_remove(&p->node);
223         free(p->name);
224         free(p);
225     }
226 }
227
228 /* Sends signal 'signr' to process 'p'.  Returns 0 if successful, otherwise a
229  * positive errno value. */
230 int
231 process_kill(const struct process *p, int signr)
232 {
233     return (p->exited ? ESRCH
234             : !kill(p->pid, signr) ? 0
235             : errno);
236 }
237
238 /* Returns the pid of process 'p'. */
239 pid_t
240 process_pid(const struct process *p)
241 {
242     return p->pid;
243 }
244
245 /* Returns the name of process 'p' (the name passed to process_start() with any
246  * leading directories stripped). */
247 const char *
248 process_name(const struct process *p)
249 {
250     return p->name;
251 }
252
253 /* Returns true if process 'p' has exited, false otherwise. */
254 bool
255 process_exited(struct process *p)
256 {
257     return p->exited;
258 }
259
260 /* Returns process 'p''s exit status, as reported by waitpid(2).
261  * process_status(p) may be called only after process_exited(p) has returned
262  * true. */
263 int
264 process_status(const struct process *p)
265 {
266     ovs_assert(p->exited);
267     return p->status;
268 }
269
270 /* Given 'status', which is a process status in the form reported by waitpid(2)
271  * and returned by process_status(), returns a string describing how the
272  * process terminated.  The caller is responsible for freeing the string when
273  * it is no longer needed. */
274 char *
275 process_status_msg(int status)
276 {
277     struct ds ds = DS_EMPTY_INITIALIZER;
278     if (WIFEXITED(status)) {
279         ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
280     } else if (WIFSIGNALED(status)) {
281         char namebuf[SIGNAL_NAME_BUFSIZE];
282
283         ds_put_format(&ds, "killed (%s)",
284                       signal_name(WTERMSIG(status), namebuf, sizeof namebuf));
285     } else if (WIFSTOPPED(status)) {
286         char namebuf[SIGNAL_NAME_BUFSIZE];
287
288         ds_put_format(&ds, "stopped (%s)",
289                       signal_name(WSTOPSIG(status), namebuf, sizeof namebuf));
290     } else {
291         ds_put_format(&ds, "terminated abnormally (%x)", status);
292     }
293     if (WCOREDUMP(status)) {
294         ds_put_cstr(&ds, ", core dumped");
295     }
296     return ds_cstr(&ds);
297 }
298
299 /* Executes periodic maintenance activities required by the process module. */
300 void
301 process_run(void)
302 {
303     char buf[_POSIX_PIPE_BUF];
304
305     if (!list_is_empty(&all_processes) && read(fds[0], buf, sizeof buf) > 0) {
306         struct process *p;
307
308         LIST_FOR_EACH (p, node, &all_processes) {
309             if (!p->exited) {
310                 int retval, status;
311                 do {
312                     retval = waitpid(p->pid, &status, WNOHANG);
313                 } while (retval == -1 && errno == EINTR);
314                 if (retval == p->pid) {
315                     p->exited = true;
316                     p->status = status;
317                 } else if (retval < 0) {
318                     VLOG_WARN("waitpid: %s", ovs_strerror(errno));
319                     p->exited = true;
320                     p->status = -1;
321                 }
322             }
323         }
324     }
325 }
326
327
328 /* Causes the next call to poll_block() to wake up when process 'p' has
329  * exited. */
330 void
331 process_wait(struct process *p)
332 {
333     if (p->exited) {
334         poll_immediate_wake();
335     } else {
336         poll_fd_wait(fds[0], POLLIN);
337     }
338 }
339
340 char *
341 process_search_path(const char *name)
342 {
343     char *save_ptr = NULL;
344     char *path, *dir;
345     struct stat s;
346
347     if (strchr(name, '/') || !getenv("PATH")) {
348         return stat(name, &s) == 0 ? xstrdup(name) : NULL;
349     }
350
351     path = xstrdup(getenv("PATH"));
352     for (dir = strtok_r(path, ":", &save_ptr); dir;
353          dir = strtok_r(NULL, ":", &save_ptr)) {
354         char *file = xasprintf("%s/%s", dir, name);
355         if (stat(file, &s) == 0) {
356             free(path);
357             return file;
358         }
359         free(file);
360     }
361     free(path);
362     return NULL;
363 }
364 \f
365 static void
366 sigchld_handler(int signr OVS_UNUSED)
367 {
368     ignore(write(fds[1], "", 1));
369 }