2 * collectd - src/exec.c
3 * Copyright (C) 2007-2010 Florian octo Forster
4 * Copyright (C) 2007-2009 Sebastian Harl
5 * Copyright (C) 2008 Peter Holik
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; only version 2 of the License is applicable.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 * Florian octo Forster <octo at collectd.org>
22 * Sebastian Harl <sh at tokkee.org>
23 * Peter Holik <peter at holik.at>
26 #define _DEFAULT_SOURCE
27 #define _BSD_SOURCE /* For setgroups */
33 #include "utils_cmd_putval.h"
34 #include "utils_cmd_putnotif.h"
36 #include <sys/types.h>
43 #define PL_NORMAL 0x01
44 #define PL_NOTIF_ACTION 0x02
46 #define PL_RUNNING 0x10
52 * Access to this structure is serialized using the `pl_lock' lock and the
53 * `PL_RUNNING' flag. The execution of notifications is *not* serialized, so
54 * all functions used to handle notifications MUST NOT write to this structure.
55 * The `pid' and `status' fields are thus unused if the `PL_NOTIF_ACTION' flag
57 * The `PL_RUNNING' flag is set in `exec_read' and unset in `exec_read_one'.
59 struct program_list_s;
60 typedef struct program_list_s program_list_t;
73 typedef struct program_list_and_notification_s
77 } program_list_and_notification_t;
82 static program_list_t *pl_head = NULL;
83 static pthread_mutex_t pl_lock = PTHREAD_MUTEX_INITIALIZER;
88 static void sigchld_handler (int __attribute__((unused)) signal) /* {{{ */
92 while ((pid = waitpid (-1, &status, WNOHANG)) > 0)
95 for (pl = pl_head; pl != NULL; pl = pl->next)
100 } /* while (waitpid) */
101 } /* void sigchld_handler }}} */
103 static int exec_config_exec (oconfig_item_t *ci) /* {{{ */
109 if (ci->children_num != 0)
111 WARNING ("exec plugin: The config option `%s' may not be a block.",
115 if (ci->values_num < 2)
117 WARNING ("exec plugin: The config option `%s' needs at least two "
118 "arguments.", ci->key);
121 if ((ci->values[0].type != OCONFIG_TYPE_STRING)
122 || (ci->values[1].type != OCONFIG_TYPE_STRING))
124 WARNING ("exec plugin: The first two arguments to the `%s' option must "
125 "be string arguments.", ci->key);
129 pl = (program_list_t *) malloc (sizeof (program_list_t));
132 ERROR ("exec plugin: malloc failed.");
135 memset (pl, '\0', sizeof (program_list_t));
137 if (strcasecmp ("NotificationExec", ci->key) == 0)
138 pl->flags |= PL_NOTIF_ACTION;
140 pl->flags |= PL_NORMAL;
142 pl->user = strdup (ci->values[0].value.string);
143 if (pl->user == NULL)
145 ERROR ("exec plugin: strdup failed.");
150 pl->group = strchr (pl->user, ':');
151 if (pl->group != NULL)
157 pl->exec = strdup (ci->values[1].value.string);
158 if (pl->exec == NULL)
160 ERROR ("exec plugin: strdup failed.");
166 pl->argv = (char **) malloc (ci->values_num * sizeof (char *));
167 if (pl->argv == NULL)
169 ERROR ("exec plugin: malloc failed.");
175 memset (pl->argv, '\0', ci->values_num * sizeof (char *));
178 char *tmp = strrchr (ci->values[1].value.string, '/');
180 sstrncpy (buffer, ci->values[1].value.string, sizeof (buffer));
182 sstrncpy (buffer, tmp + 1, sizeof (buffer));
184 pl->argv[0] = strdup (buffer);
185 if (pl->argv[0] == NULL)
187 ERROR ("exec plugin: malloc failed.");
195 for (i = 1; i < (ci->values_num - 1); i++)
197 if (ci->values[i + 1].type == OCONFIG_TYPE_STRING)
199 pl->argv[i] = strdup (ci->values[i + 1].value.string);
203 if (ci->values[i + 1].type == OCONFIG_TYPE_NUMBER)
205 ssnprintf (buffer, sizeof (buffer), "%lf",
206 ci->values[i + 1].value.number);
210 if (ci->values[i + 1].value.boolean)
211 sstrncpy (buffer, "true", sizeof (buffer));
213 sstrncpy (buffer, "false", sizeof (buffer));
216 pl->argv[i] = strdup (buffer);
219 if (pl->argv[i] == NULL)
221 ERROR ("exec plugin: strdup failed.");
226 if (i < (ci->values_num - 1))
239 for (i = 0; pl->argv[i] != NULL; i++)
241 DEBUG ("exec plugin: argv[%i] = %s", i, pl->argv[i]);
248 } /* int exec_config_exec }}} */
250 static int exec_config (oconfig_item_t *ci) /* {{{ */
254 for (i = 0; i < ci->children_num; i++)
256 oconfig_item_t *child = ci->children + i;
257 if ((strcasecmp ("Exec", child->key) == 0)
258 || (strcasecmp ("NotificationExec", child->key) == 0))
259 exec_config_exec (child);
262 WARNING ("exec plugin: Unknown config option `%s'.", child->key);
267 } /* int exec_config }}} */
269 static void set_environment (void) /* {{{ */
274 ssnprintf (buffer, sizeof (buffer), "%.3f",
275 CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
276 setenv ("COLLECTD_INTERVAL", buffer, /* overwrite = */ 1);
278 ssnprintf (buffer, sizeof (buffer), "%s", hostname_g);
279 setenv ("COLLECTD_HOSTNAME", buffer, /* overwrite = */ 1);
281 ssnprintf (buffer, sizeof (buffer), "COLLECTD_INTERVAL=%.3f",
282 CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
285 ssnprintf (buffer, sizeof (buffer), "COLLECTD_HOSTNAME=%s", hostname_g);
288 } /* }}} void set_environment */
290 __attribute__((noreturn))
291 static void exec_child (program_list_t *pl, int uid, int gid, int egid) /* {{{ */
305 if ((gid != egid) && (egid != -1))
311 setgroups (glist_len, glist);
313 #endif /* HAVE_SETGROUPS */
315 status = setgid (gid);
318 ERROR ("exec plugin: setgid (%i) failed: %s",
319 gid, sstrerror (errno, errbuf, sizeof (errbuf)));
325 status = setegid (egid);
328 ERROR ("exec plugin: setegid (%i) failed: %s",
329 egid, sstrerror (errno, errbuf, sizeof (errbuf)));
334 status = setuid (uid);
337 ERROR ("exec plugin: setuid (%i) failed: %s",
338 uid, sstrerror (errno, errbuf, sizeof (errbuf)));
342 execvp (pl->exec, pl->argv);
344 ERROR ("exec plugin: Failed to execute ``%s'': %s",
345 pl->exec, sstrerror (errno, errbuf, sizeof (errbuf)));
347 } /* void exec_child }}} */
349 static void reset_signal_mask (void) /* {{{ */
353 memset (&ss, 0, sizeof (ss));
355 sigprocmask (SIG_SETMASK, &ss, /* old mask = */ NULL);
356 } /* }}} void reset_signal_mask */
358 static int create_pipe (int fd_pipe[2]) /* {{{ */
363 status = pipe (fd_pipe);
366 ERROR ("exec plugin: pipe failed: %s",
367 sstrerror (errno, errbuf, sizeof (errbuf)));
372 } /* }}} int create_pipe */
374 static void close_pipe (int fd_pipe[2]) /* {{{ */
376 if (fd_pipe[0] != -1)
379 if (fd_pipe[1] != -1)
381 } /* }}} void close_pipe */
384 * Creates three pipes (one for reading, one for writing and one for errors),
385 * forks a child, sets up the pipes so that fd_in is connected to STDIN of
386 * the child and fd_out is connected to STDOUT and fd_err is connected to STDERR
387 * of the child. Then is calls `exec_child'.
389 static int fork_child (program_list_t *pl, int *fd_in, int *fd_out, int *fd_err) /* {{{ */
391 int fd_pipe_in[2] = {-1, -1};
392 int fd_pipe_out[2] = {-1, -1};
393 int fd_pipe_err[2] = {-1, -1};
402 struct passwd *sp_ptr;
409 if ((create_pipe(fd_pipe_in) == -1)
410 || (create_pipe(fd_pipe_out) == -1)
411 || (create_pipe(fd_pipe_err) == -1))
415 status = getpwnam_r (pl->user, &sp, nambuf, sizeof (nambuf), &sp_ptr);
418 ERROR ("exec plugin: Failed to get user information for user ``%s'': %s",
419 pl->user, sstrerror (errno, errbuf, sizeof (errbuf)));
425 ERROR ("exec plugin: No such user: `%s'", pl->user);
433 ERROR ("exec plugin: Cowardly refusing to exec program as root.");
437 /* The group configured in the configfile is set as effective group, because
438 * this way the forked process can (re-)gain the user's primary group. */
440 if (NULL != pl->group)
442 if ('\0' != *pl->group) {
443 struct group *gr_ptr = NULL;
446 status = getgrnam_r (pl->group, &gr, nambuf, sizeof (nambuf), &gr_ptr);
449 ERROR ("exec plugin: Failed to get group information "
450 "for group ``%s'': %s", pl->group,
451 sstrerror (errno, errbuf, sizeof (errbuf)));
456 ERROR ("exec plugin: No such group: `%s'", pl->group);
466 } /* if (pl->group == NULL) */
471 ERROR ("exec plugin: fork failed: %s",
472 sstrerror (errno, errbuf, sizeof (errbuf)));
480 /* Close all file descriptors but the pipe end we need. */
481 fd_num = getdtablesize ();
482 for (fd = 0; fd < fd_num; fd++)
484 if ((fd == fd_pipe_in[0])
485 || (fd == fd_pipe_out[1])
486 || (fd == fd_pipe_err[1]))
491 /* Connect the `in' pipe to STDIN */
492 if (fd_pipe_in[0] != STDIN_FILENO)
494 dup2 (fd_pipe_in[0], STDIN_FILENO);
495 close (fd_pipe_in[0]);
498 /* Now connect the `out' pipe to STDOUT */
499 if (fd_pipe_out[1] != STDOUT_FILENO)
501 dup2 (fd_pipe_out[1], STDOUT_FILENO);
502 close (fd_pipe_out[1]);
505 /* Now connect the `err' pipe to STDERR */
506 if (fd_pipe_err[1] != STDERR_FILENO)
508 dup2 (fd_pipe_err[1], STDERR_FILENO);
509 close (fd_pipe_err[1]);
514 /* Unblock all signals */
515 reset_signal_mask ();
517 exec_child (pl, uid, gid, egid);
518 /* does not return */
521 close (fd_pipe_in[0]);
522 close (fd_pipe_out[1]);
523 close (fd_pipe_err[1]);
526 *fd_in = fd_pipe_in[1];
528 close (fd_pipe_in[1]);
531 *fd_out = fd_pipe_out[0];
533 close (fd_pipe_out[0]);
536 *fd_err = fd_pipe_err[0];
538 close (fd_pipe_err[0]);
543 close_pipe(fd_pipe_in);
544 close_pipe(fd_pipe_out);
545 close_pipe(fd_pipe_err);
548 } /* int fork_child }}} */
550 static int parse_line (char *buffer) /* {{{ */
552 if (strncasecmp ("PUTVAL", buffer, strlen ("PUTVAL")) == 0)
553 return (handle_putval (stdout, buffer));
554 else if (strncasecmp ("PUTNOTIF", buffer, strlen ("PUTNOTIF")) == 0)
555 return (handle_putnotif (stdout, buffer));
558 ERROR ("exec plugin: Unable to parse command, ignoring line: \"%s\"",
562 } /* int parse_line }}} */
564 static void *exec_read_one (void *arg) /* {{{ */
566 program_list_t *pl = (program_list_t *) arg;
567 int fd, fd_err, highest_fd;
570 char buffer[1200]; /* if not completely read */
571 char buffer_err[1024];
572 char *pbuffer = buffer;
573 char *pbuffer_err = buffer_err;
575 status = fork_child (pl, NULL, &fd, &fd_err);
578 /* Reset the "running" flag */
579 pthread_mutex_lock (&pl_lock);
580 pl->flags &= ~PL_RUNNING;
581 pthread_mutex_unlock (&pl_lock);
582 pthread_exit ((void *) 1);
586 assert (pl->pid != 0);
590 FD_SET(fd_err, &fdset);
592 /* Determine the highest file descriptor */
593 highest_fd = (fd > fd_err) ? fd : fd_err;
595 /* We use a copy of fdset, as select modifies it */
602 status = select (highest_fd + 1, ©, NULL, NULL, NULL);
610 if (FD_ISSET(fd, ©))
614 len = read(fd, pbuffer, sizeof(buffer) - 1 - (pbuffer - buffer));
618 if (errno == EAGAIN || errno == EINTR) continue;
621 else if (len == 0) break; /* We've reached EOF */
625 len += pbuffer - buffer;
628 while ((pnl = strchr(pbuffer, '\n')))
631 if (*(pnl-1) == '\r' ) *(pnl-1) = '\0';
633 parse_line (pbuffer);
637 /* not completely read ? */
638 if (pbuffer - buffer < len)
640 len -= pbuffer - buffer;
641 memmove(buffer, pbuffer, len);
642 pbuffer = buffer + len;
647 else if (FD_ISSET(fd_err, ©))
651 len = read(fd_err, pbuffer_err, sizeof(buffer_err) - 1 - (pbuffer_err - buffer_err));
655 if (errno == EAGAIN || errno == EINTR)
661 /* We've reached EOF */
662 NOTICE ("exec plugin: Program `%s' has closed STDERR.", pl->exec);
664 /* Remove file descriptor form select() set. */
665 FD_CLR (fd_err, &fdset);
669 /* Clean up file descriptor */
675 pbuffer_err[len] = '\0';
677 len += pbuffer_err - buffer_err;
678 pbuffer_err = buffer_err;
680 while ((pnl = strchr(pbuffer_err, '\n')))
683 if (*(pnl-1) == '\r' ) *(pnl-1) = '\0';
685 ERROR ("exec plugin: exec_read_one: error = %s", pbuffer_err);
689 /* not completely read ? */
690 if (pbuffer_err - buffer_err < len)
692 len -= pbuffer_err - buffer_err;
693 memmove(buffer_err, pbuffer_err, len);
694 pbuffer_err = buffer_err + len;
697 pbuffer_err = buffer_err;
703 DEBUG ("exec plugin: exec_read_one: Waiting for `%s' to exit.", pl->exec);
704 if (waitpid (pl->pid, &status, 0) > 0)
707 DEBUG ("exec plugin: Child %i exited with status %i.",
708 (int) pl->pid, pl->status);
712 pthread_mutex_lock (&pl_lock);
713 pl->flags &= ~PL_RUNNING;
714 pthread_mutex_unlock (&pl_lock);
720 pthread_exit ((void *) 0);
722 } /* void *exec_read_one }}} */
724 static void *exec_notification_one (void *arg) /* {{{ */
726 program_list_t *pl = ((program_list_and_notification_t *) arg)->pl;
727 notification_t *n = &((program_list_and_notification_t *) arg)->n;
728 notification_meta_t *meta;
733 const char *severity;
735 pid = fork_child (pl, &fd, NULL, NULL);
738 pthread_exit ((void *) 1);
741 fh = fdopen (fd, "w");
745 ERROR ("exec plugin: fdopen (%i) failed: %s", fd,
746 sstrerror (errno, errbuf, sizeof (errbuf)));
747 kill (pl->pid, SIGTERM);
751 pthread_exit ((void *) 1);
754 severity = "FAILURE";
755 if (n->severity == NOTIF_WARNING)
756 severity = "WARNING";
757 else if (n->severity == NOTIF_OKAY)
763 severity, CDTIME_T_TO_DOUBLE (n->time));
765 /* Print the optional fields */
766 if (strlen (n->host) > 0)
767 fprintf (fh, "Host: %s\n", n->host);
768 if (strlen (n->plugin) > 0)
769 fprintf (fh, "Plugin: %s\n", n->plugin);
770 if (strlen (n->plugin_instance) > 0)
771 fprintf (fh, "PluginInstance: %s\n", n->plugin_instance);
772 if (strlen (n->type) > 0)
773 fprintf (fh, "Type: %s\n", n->type);
774 if (strlen (n->type_instance) > 0)
775 fprintf (fh, "TypeInstance: %s\n", n->type_instance);
777 for (meta = n->meta; meta != NULL; meta = meta->next)
779 if (meta->type == NM_TYPE_STRING)
780 fprintf (fh, "%s: %s\n", meta->name, meta->nm_value.nm_string);
781 else if (meta->type == NM_TYPE_SIGNED_INT)
782 fprintf (fh, "%s: %"PRIi64"\n", meta->name, meta->nm_value.nm_signed_int);
783 else if (meta->type == NM_TYPE_UNSIGNED_INT)
784 fprintf (fh, "%s: %"PRIu64"\n", meta->name, meta->nm_value.nm_unsigned_int);
785 else if (meta->type == NM_TYPE_DOUBLE)
786 fprintf (fh, "%s: %e\n", meta->name, meta->nm_value.nm_double);
787 else if (meta->type == NM_TYPE_BOOLEAN)
788 fprintf (fh, "%s: %s\n", meta->name,
789 meta->nm_value.nm_boolean ? "true" : "false");
792 fprintf (fh, "\n%s\n", n->message);
797 waitpid (pid, &status, 0);
799 DEBUG ("exec plugin: Child %i exited with status %i.",
803 plugin_notification_meta_free (n->meta);
806 pthread_exit ((void *) 0);
808 } /* void *exec_notification_one }}} */
810 static int exec_init (void) /* {{{ */
814 memset (&sa, '\0', sizeof (sa));
815 sa.sa_handler = sigchld_handler;
816 sigaction (SIGCHLD, &sa, NULL);
819 } /* int exec_init }}} */
821 static int exec_read (void) /* {{{ */
825 for (pl = pl_head; pl != NULL; pl = pl->next)
830 /* Only execute `normal' style executables here. */
831 if ((pl->flags & PL_NORMAL) == 0)
834 pthread_mutex_lock (&pl_lock);
835 /* Skip if a child is already running. */
836 if ((pl->flags & PL_RUNNING) != 0)
838 pthread_mutex_unlock (&pl_lock);
841 pl->flags |= PL_RUNNING;
842 pthread_mutex_unlock (&pl_lock);
844 pthread_attr_init (&attr);
845 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
846 plugin_thread_create (&t, &attr, exec_read_one, (void *) pl);
847 pthread_attr_destroy (&attr);
851 } /* int exec_read }}} */
853 static int exec_notification (const notification_t *n, /* {{{ */
854 user_data_t __attribute__((unused)) *user_data)
857 program_list_and_notification_t *pln;
859 for (pl = pl_head; pl != NULL; pl = pl->next)
864 /* Only execute `notification' style executables here. */
865 if ((pl->flags & PL_NOTIF_ACTION) == 0)
868 /* Skip if a child is already running. */
872 pln = (program_list_and_notification_t *) malloc (sizeof
873 (program_list_and_notification_t));
876 ERROR ("exec plugin: malloc failed.");
881 memcpy (&pln->n, n, sizeof (notification_t));
883 /* Set the `meta' member to NULL, otherwise `plugin_notification_meta_copy'
884 * will run into an endless loop. */
886 plugin_notification_meta_copy (&pln->n, n);
888 pthread_attr_init (&attr);
889 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
890 plugin_thread_create (&t, &attr, exec_notification_one, (void *) pln);
891 pthread_attr_destroy (&attr);
895 } /* }}} int exec_notification */
897 static int exec_shutdown (void) /* {{{ */
900 program_list_t *next;
909 kill (pl->pid, SIGTERM);
910 INFO ("exec plugin: Sent SIGTERM to %hu", (unsigned short int) pl->pid);
921 } /* int exec_shutdown }}} */
923 void module_register (void)
925 plugin_register_complex_config ("exec", exec_config);
926 plugin_register_init ("exec", exec_init);
927 plugin_register_read ("exec", exec_read);
928 plugin_register_notification ("exec", exec_notification,
929 /* user_data = */ NULL);
930 plugin_register_shutdown ("exec", exec_shutdown);
931 } /* void module_register */
934 * vim:shiftwidth=2:softtabstop=2:tabstop=8:fdm=marker