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