daemon: Fix loader log dumps
[ladish.git] / daemon / loader.c
blobe1981f54f6e34028d2dba27eff9dad94b430b72d
1 /* -*- Mode: C ; c-basic-offset: 2 -*- */
2 /*
3 * LADI Session Handler (ladish)
5 * Copyright (C) 2008, 2009 Nedko Arnaudov <nedko@arnaudov.name>
6 * Copyright (C) 2008 Juuso Alasuutari <juuso.alasuutari@gmail.com>
7 * Copyright (C) 2002 Robert Ham <rah@bash.sh>
9 **************************************************************************
10 * This file contains code that starts programs
11 **************************************************************************
13 * LADI Session Handler is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * LADI Session Handler is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with LADI Session Handler. If not, see <http://www.gnu.org/licenses/>
25 * or write to the Free Software Foundation, Inc.,
26 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
29 #define LADISH_DEBUG
31 #include "common.h"
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <pty.h> /* forkpty() */
36 #include <sys/wait.h>
38 #include "loader.h"
40 #define XTERM_COMMAND_EXTENSION "&& sh || sh"
42 #define CLIENT_OUTPUT_BUFFER_SIZE 2048
44 struct loader_child
46 struct list_head siblings;
48 char * project_name;
49 char * app_name;
51 bool dead;
52 pid_t pid;
54 bool terminal;
56 int stdout;
57 char stdout_buffer[CLIENT_OUTPUT_BUFFER_SIZE];
58 char stdout_last_line[CLIENT_OUTPUT_BUFFER_SIZE];
59 unsigned int stdout_last_line_repeat_count;
60 char * stdout_buffer_ptr;
62 int stderr;
63 char stderr_buffer[CLIENT_OUTPUT_BUFFER_SIZE];
64 char stderr_last_line[CLIENT_OUTPUT_BUFFER_SIZE];
65 unsigned int stderr_last_line_repeat_count;
66 char * stderr_buffer_ptr;
69 static void (* g_on_child_exit)(pid_t pid);
70 static struct list_head g_childs_list;
72 static struct loader_child *
73 loader_child_find_and_mark_dead(pid_t pid)
75 struct list_head *node_ptr;
76 struct loader_child *child_ptr;
78 list_for_each (node_ptr, &g_childs_list)
80 child_ptr = list_entry(node_ptr, struct loader_child, siblings);
81 if (child_ptr->pid == pid)
83 child_ptr->dead = true;
84 return child_ptr;
88 return NULL;
91 static
92 void
93 loader_check_line_repeat_end(
94 char * project,
95 char * app_name,
96 bool error,
97 unsigned int last_line_repeat_count)
99 if (last_line_repeat_count >= 2)
101 if (error)
103 log_error_plain("%s:%s: stderr line repeated %u times", project, app_name, last_line_repeat_count);
105 else
107 log_info("%s:%s: stdout line repeated %u times", project, app_name, last_line_repeat_count);
112 static void
113 loader_childs_bury(void)
115 struct list_head *node_ptr;
116 struct list_head *next_ptr;
117 struct loader_child *child_ptr;
119 list_for_each_safe (node_ptr, next_ptr, &g_childs_list)
121 child_ptr = list_entry(node_ptr, struct loader_child, siblings);
122 if (child_ptr->dead)
124 loader_check_line_repeat_end(
125 child_ptr->project_name,
126 child_ptr->app_name,
127 false,
128 child_ptr->stdout_last_line_repeat_count);
130 loader_check_line_repeat_end(
131 child_ptr->project_name,
132 child_ptr->app_name,
133 true,
134 child_ptr->stderr_last_line_repeat_count);
136 log_debug("Bury child '%s' with PID %llu", child_ptr->app_name, (unsigned long long)child_ptr->pid);
138 list_del(&child_ptr->siblings);
140 free(child_ptr->project_name);
141 free(child_ptr->app_name);
143 if (!child_ptr->terminal)
145 close(child_ptr->stdout);
146 close(child_ptr->stderr);
149 g_on_child_exit(child_ptr->pid);
150 free(child_ptr);
155 static void loader_sigchld_handler(int signum)
157 int status;
158 pid_t pid;
159 struct loader_child *child_ptr;
161 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
163 child_ptr = loader_child_find_and_mark_dead(pid);
165 if (!child_ptr)
167 log_error("Termination of unknown child process with PID %llu detected", (unsigned long long)pid);
169 else
171 log_info("Termination of child process '%s' with PID %llu detected", child_ptr->app_name, (unsigned long long)pid);
174 if (WIFEXITED(status))
176 log_info("Child exited, status=%d", WEXITSTATUS(status));
178 else if (WIFSIGNALED(status))
180 log_info("Child was killed by signal %d", WTERMSIG(status));
182 else if (WIFSTOPPED(status))
184 log_info("Child was stopped by signal %d", WSTOPSIG(status));
189 void loader_init(void (* on_child_exit)(pid_t pid))
191 g_on_child_exit = on_child_exit;
192 signal(SIGCHLD, loader_sigchld_handler);
193 INIT_LIST_HEAD(&g_childs_list);
196 void loader_uninit(void)
198 loader_childs_bury();
201 #if 0
202 static void loader_exec_program_in_xterm(const char * const * argv)
204 char * dst_ptr;
205 const char * const * src_ptr_ptr;
206 size_t len;
208 log_debug("Executing program '%s' with PID %llu in terminal", argv[0], (unsigned long long)getpid());
210 /* Calculate the command string length */
211 len = strlen(XTERM_COMMAND_EXTENSION) + 1;
212 for (src_ptr_ptr = argv; *src_ptr_ptr != NULL; src_ptr_ptr++)
214 len += strlen(*src_ptr_ptr) + 3; /* three additional chars per argument: two double quotes and a space */
217 char buf[len]; /* dynamically allocate in stack */
219 /* Create the command string */
220 src_ptr_ptr = argv;
221 dst_ptr = buf;
222 while (*src_ptr_ptr != NULL)
224 len = strlen(*src_ptr_ptr);
225 dst_ptr[0] = '"';
226 memcpy(dst_ptr + 1, src_ptr_ptr, len);
227 dst_ptr[1 + len] = '"';
228 dst_ptr[1 + len + 1] = ' ';
229 dst_ptr += len + 3;
230 src_ptr_ptr++;
233 strcat(dst_ptr, XTERM_COMMAND_EXTENSION);
235 /* Execute the command */
236 execlp("xterm", "xterm", "-e", "/bin/sh", "-c", buf, NULL);
238 log_error("Failed to execute command '%s' in terminal: %s", buf, strerror(errno));
240 exit(1);
242 #endif
244 static void loader_exec_program(const char * commandline, const char * working_dir, bool run_in_terminal)
246 const char * argv[4];
248 /* for non terminal processes we use forkpty() that calls login_tty() that calls setsid() */
249 /* we can successful call setsid() only once */
250 if (run_in_terminal)
252 /* no longer anything to do with lashd */
253 if (setsid() == -1)
255 log_error("Could not create new process group: %s", strerror(errno));
259 /* change the working dir */
260 if (chdir(working_dir) == -1)
262 log_error("Could not change directory to working dir '%s' for program '%s': %s", working_dir, argv[0], strerror(errno));
265 if (run_in_terminal)
267 argv[0] = "xterm";
268 argv[1] = "-e";
270 else
272 argv[0] = "sh";
273 argv[1] = "-c";
276 argv[2] = commandline;
277 argv[3] = NULL;
279 log_info("Executing '%s' with PID %llu", commandline, (unsigned long long)getpid());
281 /* Execute it */
282 execvp(argv[0], (char **)argv);
284 log_error("Executing program '%s' failed: %s", argv[0], strerror(errno));
286 exit(1);
289 static
290 void
291 loader_read_child_output(
292 char * project,
293 char * app_name,
294 int fd,
295 bool error,
296 char * buffer_ptr,
297 char ** buffer_ptr_ptr,
298 char * last_line,
299 unsigned int * last_line_repeat_count)
301 ssize_t ret;
302 char *char_ptr;
303 char *eol_ptr;
304 size_t left;
305 size_t max_read;
309 max_read = CLIENT_OUTPUT_BUFFER_SIZE - 1 - (*buffer_ptr_ptr - buffer_ptr);
310 ret = read(fd, *buffer_ptr_ptr, max_read);
311 if (ret > 0)
313 (*buffer_ptr_ptr)[ret] = 0;
314 char_ptr = buffer_ptr;
316 while ((eol_ptr = strchr(char_ptr, '\n')) != NULL)
318 *eol_ptr = 0;
320 if (*last_line_repeat_count > 0 && strcmp(last_line, char_ptr) == 0)
322 if (*last_line_repeat_count == 1)
324 if (error)
326 log_error_plain("%s:%s: last stderr line repeating..", project, app_name);
328 else
330 log_info("%s:%s: last stdout line repeating...", project, app_name);
334 (*last_line_repeat_count)++;
336 else
338 loader_check_line_repeat_end(project, app_name, error, *last_line_repeat_count);
340 strcpy(last_line, char_ptr);
341 *last_line_repeat_count = 1;
343 if (error)
345 log_error_plain("%s:%s: %s", project, app_name, char_ptr);
347 else
349 log_info("%s:%s: %s", project, app_name, char_ptr);
353 char_ptr = eol_ptr + 1;
356 left = ret - (char_ptr - *buffer_ptr_ptr);
357 if (left != 0)
359 /* last line does not end with newline */
361 if (left == CLIENT_OUTPUT_BUFFER_SIZE - 1)
363 /* line is too long to fit in buffer */
364 /* print it like it is, rest (or more) of it will be logged on next interation */
366 if (error)
368 log_error_plain("%s:%s: %s " ANSI_RESET ANSI_COLOR_RED "(truncated) " ANSI_RESET, project, app_name, char_ptr);
370 else
372 log_info("%s:%s: %s " ANSI_RESET ANSI_COLOR_RED "(truncated) " ANSI_RESET, project, app_name, char_ptr);
375 left = 0;
377 else
379 memmove(buffer_ptr, char_ptr, left);
383 *buffer_ptr_ptr = buffer_ptr + left;
386 while (ret == max_read); /* if we have read everything as much as we can, then maybe there is more to read */
389 static void
390 loader_read_childs_output(void)
392 struct list_head * node_ptr;
393 struct loader_child * child_ptr;
395 list_for_each (node_ptr, &g_childs_list)
397 child_ptr = list_entry(node_ptr, struct loader_child, siblings);
399 if (!child_ptr->dead && !child_ptr->terminal)
401 loader_read_child_output(
402 child_ptr->project_name,
403 child_ptr->app_name,
404 child_ptr->stdout,
405 false,
406 child_ptr->stdout_buffer,
407 &child_ptr->stdout_buffer_ptr,
408 child_ptr->stdout_last_line,
409 &child_ptr->stdout_last_line_repeat_count);
411 loader_read_child_output(
412 child_ptr->project_name,
413 child_ptr->app_name,
414 child_ptr->stderr,
415 true,
416 child_ptr->stderr_buffer,
417 &child_ptr->stderr_buffer_ptr,
418 child_ptr->stderr_last_line,
419 &child_ptr->stderr_last_line_repeat_count);
424 void
425 loader_run(void)
427 loader_read_childs_output();
428 loader_childs_bury();
431 bool
432 loader_execute(
433 const char * project_name,
434 const char * app_name,
435 const char * working_dir,
436 bool run_in_terminal,
437 const char * commandline,
438 pid_t * pid_ptr)
440 pid_t pid;
441 struct loader_child * child_ptr;
442 int stderr_pipe[2];
444 child_ptr = malloc(sizeof(struct loader_child));
445 if (child_ptr == NULL)
447 log_error("malloc() failed to allocate struct loader_child");
448 goto fail;
451 child_ptr->project_name = strdup(project_name);
452 if (child_ptr->project_name == NULL)
454 log_error("strdup() failed to duplicate project name '%s'", project_name);
455 goto free_struct;
458 child_ptr->app_name = strdup(app_name);
459 if (child_ptr->app_name == NULL)
461 log_error("strdup() failed to duplicate app name '%s'", app_name);
462 goto free_project_name;
465 child_ptr->dead = false;
466 child_ptr->terminal = run_in_terminal;
467 child_ptr->stdout_buffer_ptr = child_ptr->stdout_buffer;
468 child_ptr->stderr_buffer_ptr = child_ptr->stderr_buffer;
469 child_ptr->stdout_last_line_repeat_count = 0;
470 child_ptr->stderr_last_line_repeat_count = 0;
472 if (!run_in_terminal)
474 if (pipe(stderr_pipe) == -1)
476 log_error("Failed to create stderr pipe");
478 else
480 child_ptr->stderr = stderr_pipe[0];
482 if (fcntl(child_ptr->stderr, F_SETFL, O_NONBLOCK) == -1)
484 log_error("Failed to set nonblocking mode on "
485 "stderr reading end: %s",
486 strerror(errno));
487 close(stderr_pipe[0]);
488 close(stderr_pipe[1]);
493 list_add_tail(&child_ptr->siblings, &g_childs_list);
495 if (!run_in_terminal)
497 /* We need pty to disable libc buffering of stdout */
498 pid = forkpty(&child_ptr->stdout, NULL, NULL, NULL);
500 else
502 pid = fork();
505 if (pid == -1)
507 log_error("Could not fork to exec program %s:%s: %s", project_name, app_name, strerror(errno));
508 list_del(&child_ptr->siblings); /* fork failed so it is not really a child process to watch for. */
509 return false;
512 if (pid == 0)
514 /* Need to close all open file descriptors except the std ones */
515 struct rlimit max_fds;
516 rlim_t fd;
518 getrlimit(RLIMIT_NOFILE, &max_fds);
520 for (fd = 3; fd < max_fds.rlim_cur; ++fd)
522 close(fd);
525 if (!run_in_terminal)
527 /* In child, close unused reading end of pipe */
528 close(stderr_pipe[0]);
530 dup2(stderr_pipe[1], fileno(stderr));
533 loader_exec_program(commandline, working_dir, run_in_terminal);
535 return false; /* We should never get here */
538 if (!run_in_terminal)
540 /* In parent, close unused writing ends of pipe */
541 close(stderr_pipe[1]);
543 if (fcntl(child_ptr->stdout, F_SETFL, O_NONBLOCK) == -1)
545 log_error("Could not set noblocking mode on stdout "
546 "- pty: %s", strerror(errno));
547 close(stderr_pipe[0]);
548 close(child_ptr->stdout);
552 log_info("Forked to run program %s:%s pid = %llu", project_name, app_name, (unsigned long long)pid);
554 *pid_ptr = child_ptr->pid = pid;
556 return true;
558 free_project_name:
559 free(child_ptr->project_name);
561 free_struct:
562 free(child_ptr);
564 fail:
565 return false;
568 unsigned int loader_get_app_count(void)
570 struct list_head * node_ptr;
571 unsigned int count;
573 count = 0;
575 list_for_each(node_ptr, &g_childs_list)
577 count++;
580 return count;