exec plugin: Changed the format in which notifications are passed to the programs.
[collectd.git] / src / exec.c
1 /**
2  * collectd - src/exec.c
3  * Copyright (C) 2007,2008  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25
26 #include "utils_cmd_putval.h"
27 #include "utils_cmd_putnotif.h"
28
29 #include <sys/types.h>
30 #include <pwd.h>
31 #include <grp.h>
32 #include <signal.h>
33
34 #include <pthread.h>
35
36 #define PL_NORMAL        0x01
37 #define PL_NOTIF_ACTION  0x02
38 #define PL_NAGIOS_PLUGIN 0x04
39
40 #define PL_RUNNING       0x10
41
42 /*
43  * Private data types
44  */
45 /*
46  * Access to this structure is serialized using the `pl_lock' lock and the
47  * `PL_RUNNING' flag. The execution of notifications is *not* serialized, so
48  * all functions used to handle notifications MUST NOT write to this structure.
49  * The `pid' and `status' fields are thus unused if the `PL_NOTIF_ACTION' flag
50  * is set.
51  * The `PL_RUNNING' flag is set in `exec_read' and unset in `exec_read_one'.
52  */
53 struct program_list_s;
54 typedef struct program_list_s program_list_t;
55 struct program_list_s
56 {
57   char           *user;
58   char           *group;
59   char           *exec;
60   char          **argv;
61   int             pid;
62   int             status;
63   int             flags;
64   program_list_t *next;
65 };
66
67 typedef struct program_list_and_notification_s
68 {
69   program_list_t *pl;
70   notification_t n;
71 } program_list_and_notification_t;
72
73 /*
74  * Private variables
75  */
76 static program_list_t *pl_head = NULL;
77 static pthread_mutex_t pl_lock = PTHREAD_MUTEX_INITIALIZER;
78
79 /*
80  * Functions
81  */
82 static void sigchld_handler (int signal) /* {{{ */
83 {
84   pid_t pid;
85   int status;
86   while ((pid = waitpid (-1, &status, WNOHANG)) > 0)
87   {
88     program_list_t *pl;
89     for (pl = pl_head; pl != NULL; pl = pl->next)
90       if (pl->pid == pid)
91         break;
92     if (pl != NULL)
93       pl->status = status;
94   } /* while (waitpid) */
95 } /* void sigchld_handler }}} */
96
97 static int exec_config_exec (oconfig_item_t *ci) /* {{{ */
98 {
99   program_list_t *pl;
100   char buffer[128];
101   int i;
102
103   if (ci->children_num != 0)
104   {
105     WARNING ("exec plugin: The config option `%s' may not be a block.",
106         ci->key);
107     return (-1);
108   }
109   if (ci->values_num < 2)
110   {
111     WARNING ("exec plugin: The config option `%s' needs at least two "
112         "arguments.", ci->key);
113     return (-1);
114   }
115   if ((ci->values[0].type != OCONFIG_TYPE_STRING)
116       || (ci->values[1].type != OCONFIG_TYPE_STRING))
117   {
118     WARNING ("exec plugin: The first two arguments to the `%s' option must "
119         "be string arguments.", ci->key);
120     return (-1);
121   }
122
123   pl = (program_list_t *) malloc (sizeof (program_list_t));
124   if (pl == NULL)
125   {
126     ERROR ("exec plugin: malloc failed.");
127     return (-1);
128   }
129   memset (pl, '\0', sizeof (program_list_t));
130
131 #if 0
132   if (strcasecmp ("NagiosExec", ci->key) == 0)
133     pl->flags |= PL_NAGIOS_PLUGIN;
134   else
135 #endif
136   if (strcasecmp ("NotificationExec", ci->key) == 0)
137     pl->flags |= PL_NOTIF_ACTION;
138   else
139     pl->flags |= PL_NORMAL;
140
141   pl->user = strdup (ci->values[0].value.string);
142   if (pl->user == NULL)
143   {
144     ERROR ("exec plugin: strdup failed.");
145     sfree (pl);
146     return (-1);
147   }
148
149   pl->group = strchr (pl->user, ':');
150   if (pl->group != NULL)
151   {
152     *pl->group = '\0';
153     pl->group++;
154   }
155
156   pl->exec = strdup (ci->values[1].value.string);
157   if (pl->exec == NULL)
158   {
159     ERROR ("exec plugin: strdup failed.");
160     sfree (pl->user);
161     sfree (pl);
162     return (-1);
163   }
164
165   pl->argv = (char **) malloc (ci->values_num * sizeof (char *));
166   if (pl->argv == NULL)
167   {
168     ERROR ("exec plugin: malloc failed.");
169     sfree (pl->exec);
170     sfree (pl->user);
171     sfree (pl);
172     return (-1);
173   }
174   memset (pl->argv, '\0', ci->values_num * sizeof (char *));
175
176   {
177     char *tmp = strrchr (ci->values[1].value.string, '/');
178     if (tmp == NULL)
179       strncpy (buffer, ci->values[1].value.string, sizeof (buffer));
180     else
181       strncpy (buffer, tmp + 1, sizeof (buffer));
182     buffer[sizeof (buffer) - 1] = '\0';
183   }
184   pl->argv[0] = strdup (buffer);
185   if (pl->argv[0] == NULL)
186   {
187     ERROR ("exec plugin: malloc failed.");
188     sfree (pl->argv);
189     sfree (pl->exec);
190     sfree (pl->user);
191     sfree (pl);
192     return (-1);
193   }
194
195   for (i = 1; i < (ci->values_num - 1); i++)
196   {
197     if (ci->values[i + 1].type == OCONFIG_TYPE_STRING)
198     {
199       pl->argv[i] = strdup (ci->values[i + 1].value.string);
200     }
201     else
202     {
203       if (ci->values[i + 1].type == OCONFIG_TYPE_NUMBER)
204       {
205         snprintf (buffer, sizeof (buffer), "%lf",
206             ci->values[i + 1].value.number);
207       }
208       else
209       {
210         if (ci->values[i + 1].value.boolean)
211           strncpy (buffer, "true", sizeof (buffer));
212         else
213           strncpy (buffer, "false", sizeof (buffer));
214       }
215       buffer[sizeof (buffer) - 1] = '\0';
216
217       pl->argv[i] = strdup (buffer);
218     }
219
220     if (pl->argv[i] == NULL)
221     {
222       ERROR ("exec plugin: strdup failed.");
223       break;
224     }
225   } /* for (i) */
226
227   if (i < (ci->values_num - 1))
228   {
229     while ((--i) >= 0)
230     {
231       sfree (pl->argv[i]);
232     }
233     sfree (pl->argv);
234     sfree (pl->exec);
235     sfree (pl->user);
236     sfree (pl);
237     return (-1);
238   }
239
240   for (i = 0; pl->argv[i] != NULL; i++)
241   {
242     DEBUG ("exec plugin: argv[%i] = %s", i, pl->argv[i]);
243   }
244
245   pl->next = pl_head;
246   pl_head = pl;
247
248   return (0);
249 } /* int exec_config_exec }}} */
250
251 static int exec_config (oconfig_item_t *ci) /* {{{ */
252 {
253   int i;
254
255   for (i = 0; i < ci->children_num; i++)
256   {
257     oconfig_item_t *child = ci->children + i;
258     if ((strcasecmp ("Exec", child->key) == 0)
259 #if 0
260         || (strcasecmp ("NagiosExec", child->key) == 0)
261 #endif
262         || (strcasecmp ("NotificationExec", child->key) == 0))
263       exec_config_exec (child);
264     else
265     {
266       WARNING ("exec plugin: Unknown config option `%s'.", child->key);
267     }
268   } /* for (i) */
269
270   return (0);
271 } /* int exec_config }}} */
272
273 static void exec_child (program_list_t *pl) /* {{{ */
274 {
275   int status;
276   int uid;
277   int gid;
278   int egid;
279
280   struct passwd *sp_ptr;
281   struct passwd sp;
282   char nambuf[2048];
283   char errbuf[1024];
284
285   sp_ptr = NULL;
286   status = getpwnam_r (pl->user, &sp, nambuf, sizeof (nambuf), &sp_ptr);
287   if (status != 0)
288   {
289     ERROR ("exec plugin: getpwnam_r failed: %s",
290         sstrerror (errno, errbuf, sizeof (errbuf)));
291     exit (-1);
292   }
293   if (sp_ptr == NULL)
294   {
295     ERROR ("exec plugin: No such user: `%s'", pl->user);
296     exit (-1);
297   }
298
299   uid = sp.pw_uid;
300   gid = sp.pw_gid;
301   if (uid == 0)
302   {
303     ERROR ("exec plugin: Cowardly refusing to exec program as root.");
304     exit (-1);
305   }
306
307   /* The group configured in the configfile is set as effective group, because
308    * this way the forked process can (re-)gain the user's primary group. */
309   egid = -1;
310   if (NULL != pl->group)
311   {
312     if ('\0' != *pl->group) {
313       struct group *gr_ptr = NULL;
314       struct group gr;
315
316       status = getgrnam_r (pl->group, &gr, nambuf, sizeof (nambuf), &gr_ptr);
317       if (0 != status)
318       {
319         ERROR ("exec plugin: getgrnam_r failed: %s",
320             sstrerror (errno, errbuf, sizeof (errbuf)));
321         exit (-1);
322       }
323       if (NULL == gr_ptr)
324       {
325         ERROR ("exec plugin: No such group: `%s'", pl->group);
326         exit (-1);
327       }
328
329       egid = gr.gr_gid;
330     }
331     else
332     {
333       egid = gid;
334     }
335   } /* if (pl->group == NULL) */
336
337   status = setgid (gid);
338   if (status != 0)
339   {
340     ERROR ("exec plugin: setgid (%i) failed: %s",
341         gid, sstrerror (errno, errbuf, sizeof (errbuf)));
342     exit (-1);
343   }
344
345   if (egid != -1)
346   {
347     status = setegid (egid);
348     if (status != 0)
349     {
350       ERROR ("exec plugin: setegid (%i) failed: %s",
351           egid, sstrerror (errno, errbuf, sizeof (errbuf)));
352       exit (-1);
353     }
354   }
355
356   status = setuid (uid);
357   if (status != 0)
358   {
359     ERROR ("exec plugin: setuid (%i) failed: %s",
360         uid, sstrerror (errno, errbuf, sizeof (errbuf)));
361     exit (-1);
362   }
363
364   status = execvp (pl->exec, pl->argv);
365
366   ERROR ("exec plugin: exec failed: %s",
367       sstrerror (errno, errbuf, sizeof (errbuf)));
368   exit (-1);
369 } /* void exec_child }}} */
370
371 /*
372  * Creates two pipes (one for reading, ong for writing), forks a child, sets up
373  * the pipes so that fd_in is connected to STDIN of the child and fd_out is
374  * connected to STDOUT and STDERR of the child. Then is calls `exec_child'.
375  */
376 static int fork_child (program_list_t *pl, int *fd_in, int *fd_out) /* {{{ */
377 {
378   int fd_pipe_in[2];
379   int fd_pipe_out[2];
380   int status;
381   int pid;
382
383   if (pl->pid != 0)
384     return (-1);
385
386   status = pipe (fd_pipe_in);
387   if (status != 0)
388   {
389     char errbuf[1024];
390     ERROR ("exec plugin: pipe failed: %s",
391         sstrerror (errno, errbuf, sizeof (errbuf)));
392     return (-1);
393   }
394
395   status = pipe (fd_pipe_out);
396   if (status != 0)
397   {
398     char errbuf[1024];
399     ERROR ("exec plugin: pipe failed: %s",
400         sstrerror (errno, errbuf, sizeof (errbuf)));
401     return (-1);
402   }
403
404   pid = fork ();
405   if (pid < 0)
406   {
407     char errbuf[1024];
408     ERROR ("exec plugin: fork failed: %s",
409         sstrerror (errno, errbuf, sizeof (errbuf)));
410     return (-1);
411   }
412   else if (pid == 0)
413   {
414     close (fd_pipe_in[1]);
415     close (fd_pipe_out[0]);
416
417     /* If the `out' pipe has the filedescriptor STDIN we have to be careful
418      * with the `dup's below. So, if this is the case we have to handle the
419      * `out' pipe first. */
420     if (fd_pipe_out[1] == STDIN_FILENO)
421     {
422       int new_fileno = (fd_pipe_in[0] == STDOUT_FILENO)
423         ? STDERR_FILENO : STDOUT_FILENO;
424       dup2 (fd_pipe_out[1], new_fileno);
425       close (fd_pipe_out[1]);
426       fd_pipe_out[1] = new_fileno;
427     }
428     /* Now `fd_pipe_out[1]' is either `STDOUT' or `STDERR', but definitely not
429      * `STDIN_FILENO'. */
430
431     /* Connect the `in' pipe to STDIN */
432     if (fd_pipe_in[0] != STDIN_FILENO)
433     {
434       dup2 (fd_pipe_in[0], STDIN_FILENO);
435       close (fd_pipe_in[0]);
436       fd_pipe_in[0] = STDIN_FILENO;
437     }
438
439     /* Now connect the `out' pipe to STDOUT and STDERR */
440     if (fd_pipe_out[1] != STDOUT_FILENO)
441       dup2 (fd_pipe_out[1], STDOUT_FILENO);
442     if (fd_pipe_out[1] != STDERR_FILENO)
443       dup2 (fd_pipe_out[1], STDERR_FILENO);
444
445     /* If the pipe has some FD that's something completely different, close it
446      * now. */
447     if ((fd_pipe_out[1] != STDOUT_FILENO) && (fd_pipe_out[1] != STDERR_FILENO))
448     {
449       close (fd_pipe_out[1]);
450       fd_pipe_out[1] = STDOUT_FILENO;
451     }
452
453     exec_child (pl);
454     /* does not return */
455   }
456
457   close (fd_pipe_in[0]);
458   close (fd_pipe_out[1]);
459
460   if (fd_in != NULL)
461     *fd_in = fd_pipe_in[1];
462   else
463     close (fd_pipe_in[1]);
464
465   if (fd_out != NULL)
466     *fd_out = fd_pipe_out[0];
467   else
468     close (fd_pipe_out[0]);
469
470   return (pid);
471 } /* int fork_child }}} */
472
473 static int parse_line (char *buffer) /* {{{ */
474 {
475   char *fields[256];
476   int fields_num;
477
478   fields[0] = "PUTVAL";
479   fields_num = strsplit (buffer, fields + 1, STATIC_ARRAY_SIZE(fields) - 1);
480
481   if (strcasecmp (fields[1], "putval") == 0)
482     return (handle_putval (stdout, fields + 1, fields_num));
483   else if (strcasecmp (fields[1], "putnotif") == 0)
484     return (handle_putnotif (stdout, fields + 1, fields_num));
485
486   /* compatibility code */
487   return (handle_putval (stdout, fields, fields_num + 1));
488 } /* int parse_line }}} */
489
490 static void *exec_read_one (void *arg) /* {{{ */
491 {
492   program_list_t *pl = (program_list_t *) arg;
493   int fd;
494   FILE *fh;
495   char buffer[1024];
496   int status;
497
498   status = fork_child (pl, NULL, &fd);
499   if (status < 0)
500     pthread_exit ((void *) 1);
501   pl->pid = status;
502
503   assert (pl->pid != 0);
504
505   fh = fdopen (fd, "r");
506   if (fh == NULL)
507   {
508     char errbuf[1024];
509     ERROR ("exec plugin: fdopen (%i) failed: %s", fd,
510         sstrerror (errno, errbuf, sizeof (errbuf)));
511     kill (pl->pid, SIGTERM);
512     pl->pid = 0;
513     close (fd);
514     pthread_exit ((void *) 1);
515   }
516
517   buffer[0] = '\0';
518   while (fgets (buffer, sizeof (buffer), fh) != NULL)
519   {
520     int len;
521
522     len = strlen (buffer);
523
524     /* Remove newline from end. */
525     while ((len > 0) && ((buffer[len - 1] == '\n')
526           || (buffer[len - 1] == '\r')))
527       buffer[--len] = '\0';
528
529     DEBUG ("exec plugin: exec_read_one: buffer = %s", buffer);
530
531     if (pl->flags & PL_NAGIOS_PLUGIN)
532       break;
533
534     parse_line (buffer);
535   } /* while (fgets) */
536
537   fclose (fh);
538
539   if (waitpid (pl->pid, &status, 0) > 0)
540     pl->status = status;
541
542   DEBUG ("exec plugin: Child %i exited with status %i.",
543       (int) pl->pid, pl->status);
544
545   if (pl->flags & PL_NAGIOS_PLUGIN)
546   {
547     notification_t n;
548
549     memset (&n, '\0', sizeof (n));
550     
551     n.severity = NOTIF_FAILURE;
552     if (pl->status == 0)
553       n.severity = NOTIF_OKAY;
554     else if (pl->status == 1)
555       n.severity = NOTIF_WARNING;
556
557     strncpy (n.message, buffer, sizeof (n.message));
558     n.message[sizeof (n.message) - 1] = '\0';
559
560     n.time = time (NULL);
561
562     strncpy (n.host, hostname_g, sizeof (n.host));
563     n.host[sizeof (n.host) - 1] = '\0';
564
565     plugin_dispatch_notification (&n);
566   }
567
568   pl->pid = 0;
569
570   pthread_mutex_lock (&pl_lock);
571   pl->flags &= ~PL_RUNNING;
572   pthread_mutex_unlock (&pl_lock);
573
574   pthread_exit ((void *) 0);
575   return (NULL);
576 } /* void *exec_read_one }}} */
577
578 static void *exec_notification_one (void *arg) /* {{{ */
579 {
580   program_list_t *pl = ((program_list_and_notification_t *) arg)->pl;
581   const notification_t *n = &((program_list_and_notification_t *) arg)->n;
582   int fd;
583   FILE *fh;
584   int pid;
585   int status;
586   const char *severity;
587
588   pid = fork_child (pl, &fd, NULL);
589   if (pid < 0) {
590     sfree (arg);
591     pthread_exit ((void *) 1);
592   }
593
594   fh = fdopen (fd, "w");
595   if (fh == NULL)
596   {
597     char errbuf[1024];
598     ERROR ("exec plugin: fdopen (%i) failed: %s", fd,
599         sstrerror (errno, errbuf, sizeof (errbuf)));
600     kill (pl->pid, SIGTERM);
601     pl->pid = 0;
602     close (fd);
603     sfree (arg);
604     pthread_exit ((void *) 1);
605   }
606
607   severity = "FAILURE";
608   if (n->severity == NOTIF_WARNING)
609     severity = "WARNING";
610   else if (n->severity == NOTIF_OKAY)
611     severity = "OKAY";
612
613   fprintf (fh,
614       "Severity: %s\n"
615       "Time: %u\n",
616       severity, (unsigned int) n->time);
617
618   /* Print the optional fields */
619   if (strlen (n->host) > 0)
620     fprintf (fh, "Host: %s\n", n->host);
621   if (strlen (n->plugin) > 0)
622     fprintf (fh, "Plugin: %s\n", n->plugin);
623   if (strlen (n->plugin_instance) > 0)
624     fprintf (fh, "PluginInstance: %s\n", n->plugin_instance);
625   if (strlen (n->type) > 0)
626     fprintf (fh, "Type: %s\n", n->type);
627   if (strlen (n->type_instance) > 0)
628     fprintf (fh, "TypeInstance: %s\n", n->type_instance);
629
630   fprintf (fh, "\n%s\n", n->message);
631
632   fflush (fh);
633   fclose (fh);
634
635   waitpid (pid, &status, 0);
636
637   DEBUG ("exec plugin: Child %i exited with status %i.",
638       pid, status);
639
640   sfree (arg);
641   pthread_exit ((void *) 0);
642   return (NULL);
643 } /* void *exec_notification_one }}} */
644
645 static int exec_init (void) /* {{{ */
646 {
647   struct sigaction sa;
648
649   memset (&sa, '\0', sizeof (sa));
650   sa.sa_handler = sigchld_handler;
651   sigaction (SIGCHLD, &sa, NULL);
652
653   return (0);
654 } /* int exec_init }}} */
655
656 static int exec_read (void) /* {{{ */
657 {
658   program_list_t *pl;
659
660   for (pl = pl_head; pl != NULL; pl = pl->next)
661   {
662     pthread_t t;
663     pthread_attr_t attr;
664
665     /* Only execute `normal' and `nagios' style executables here. */
666     if ((pl->flags & (PL_NAGIOS_PLUGIN | PL_NORMAL)) == 0)
667       continue;
668
669     pthread_mutex_lock (&pl_lock);
670     /* Skip if a child is already running. */
671     if ((pl->flags & PL_RUNNING) != 0)
672     {
673       pthread_mutex_unlock (&pl_lock);
674       continue;
675     }
676     pl->flags |= PL_RUNNING;
677     pthread_mutex_unlock (&pl_lock);
678
679     pthread_attr_init (&attr);
680     pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
681     pthread_create (&t, &attr, exec_read_one, (void *) pl);
682   } /* for (pl) */
683
684   return (0);
685 } /* int exec_read }}} */
686
687 static int exec_notification (const notification_t *n)
688 {
689   program_list_t *pl;
690   program_list_and_notification_t *pln;
691
692   for (pl = pl_head; pl != NULL; pl = pl->next)
693   {
694     pthread_t t;
695     pthread_attr_t attr;
696
697     /* Only execute `notification' style executables here. */
698     if ((pl->flags & PL_NOTIF_ACTION) == 0)
699       continue;
700
701     /* Skip if a child is already running. */
702     if (pl->pid != 0)
703       continue;
704
705     pln = (program_list_and_notification_t *) malloc (sizeof
706         (program_list_and_notification_t));
707     if (pln == NULL)
708     {
709       ERROR ("exec plugin: malloc failed.");
710       continue;
711     }
712
713     pln->pl = pl;
714     memcpy (&pln->n, n, sizeof (notification_t));
715
716     pthread_attr_init (&attr);
717     pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
718     pthread_create (&t, &attr, exec_notification_one, (void *) pln);
719   } /* for (pl) */
720
721   return (0);
722 } /* int exec_notification */
723
724 static int exec_shutdown (void) /* {{{ */
725 {
726   program_list_t *pl;
727   program_list_t *next;
728
729   pl = pl_head;
730   while (pl != NULL)
731   {
732     next = pl->next;
733
734     if (pl->pid > 0)
735     {
736       kill (pl->pid, SIGTERM);
737       INFO ("exec plugin: Sent SIGTERM to %hu", (unsigned short int) pl->pid);
738     }
739
740     sfree (pl->user);
741     sfree (pl);
742
743     pl = next;
744   } /* while (pl) */
745   pl_head = NULL;
746
747   return (0);
748 } /* int exec_shutdown }}} */
749
750 void module_register (void)
751 {
752   plugin_register_complex_config ("exec", exec_config);
753   plugin_register_init ("exec", exec_init);
754   plugin_register_read ("exec", exec_read);
755   plugin_register_notification ("exec", exec_notification);
756   plugin_register_shutdown ("exec", exec_shutdown);
757 } /* void module_register */
758
759 /*
760  * vim:shiftwidth=2:softtabstop=2:tabstop=8:fdm=marker
761  */