8aa5a585165fc590ebe56bd1ebe9d2088e9a7063
[rrdd.git] / src / rrdd.c
1 /**
2  * collectd - src/rrdd.c
3  * Copyright (C) 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 #define RRDD_DEBUG 1
23
24 #include "rrdd.h"
25
26 #if RRDD_DEBUG
27 # define RRDD_LOG(severity, ...) do { fprintf (stderr, __VA_ARGS__); fprintf (stderr, "\n"); } while (0)
28 #else
29 # define RRDD_LOG(severity, ...) syslog ((severity), __VA_ARGS__)
30 #endif
31
32 /*
33  * Types
34  */
35 struct listen_socket_s
36 {
37   int fd;
38   char path[PATH_MAX + 1];
39 };
40 typedef struct listen_socket_s listen_socket_t;
41
42 struct cache_item_s;
43 typedef struct cache_item_s cache_item_t;
44 struct cache_item_s
45 {
46   char *file;
47   char **values;
48   int values_num;
49   time_t last_flush_time;
50 #define CI_FLAGS_IN_TREE  0x01
51 #define CI_FLAGS_IN_QUEUE 0x02
52   int flags;
53
54   cache_item_t *next;
55 };
56
57 /*
58  * Variables
59  */
60 static listen_socket_t *listen_fds = NULL;
61 static size_t listen_fds_num = 0;
62
63 static int do_shutdown = 0;
64
65 static pthread_t queue_thread;
66
67 static pthread_t *connetion_threads = NULL;
68 static pthread_mutex_t connetion_threads_lock = PTHREAD_MUTEX_INITIALIZER;
69 static int connetion_threads_num = 0;
70
71 /* Cache stuff */
72 static avl_tree_t     *cache_tree = NULL;
73 static cache_item_t   *cache_queue_head = NULL;
74 static cache_item_t   *cache_queue_tail = NULL;
75 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
76 static pthread_cond_t  cache_cond = PTHREAD_COND_INITIALIZER;
77
78 /* 
79  * Functions
80  */
81 static void sig_int_handler (int signal) /* {{{ */
82 {
83   do_shutdown++;
84 } /* }}} void sig_int_handler */
85
86 static void sig_term_handler (int signal) /* {{{ */
87 {
88   do_shutdown++;
89 } /* }}} void sig_term_handler */
90
91 static int cache_tree_compare (const void *v0, const void *v1) /* {{{ */
92 {
93   cache_item_t *c0 = (cache_item_t *) v0;
94   cache_item_t *c1 = (cache_item_t *) v1;
95
96   assert (c0->file != NULL);
97   assert (c1->file != NULL);
98
99   return (strcmp (c0->file, c1->file));
100 } /* }}} int cache_tree_compare */
101
102 static void cache_tree_free (void *v) /* {{{ */
103 {
104   cache_item_t *c = (cache_item_t *) v;
105
106   assert (c->values_num == 0);
107   assert ((c->flags & CI_FLAGS_IN_TREE) != 0);
108   assert ((c->flags & CI_FLAGS_IN_QUEUE) == 0);
109
110   free (c->file);
111   c->file = NULL;
112   free (c);
113 } /* }}} void cache_tree_free */
114
115 static void *queue_thread_main (void *args) /* {{{ */
116 {
117   pthread_mutex_lock (&cache_lock);
118   while ((do_shutdown == 0) || (cache_queue_head != NULL))
119   {
120     cache_item_t *ci;
121
122     char *file;
123     char **values;
124     int values_num;
125     int status;
126     int i;
127
128     if (cache_queue_head == NULL)
129       pthread_cond_wait (&cache_cond, &cache_lock);
130
131     if (cache_queue_head == NULL)
132       continue;
133
134     ci = cache_queue_head;
135
136     /* copy the relevant parts */
137     file = strdup (ci->file);
138     if (file == NULL)
139     {
140       RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
141       continue;
142     }
143
144     values = ci->values;
145     values_num = ci->values_num;
146
147     ci->values = NULL;
148     ci->values_num = 0;
149
150     ci->last_flush_time = time (NULL);
151     ci->flags &= ~(CI_FLAGS_IN_QUEUE);
152
153     cache_queue_head = ci->next;
154     if (cache_queue_head == NULL)
155       cache_queue_tail = NULL;
156     ci->next = NULL;
157
158     pthread_mutex_unlock (&cache_lock);
159
160     RRDD_LOG (LOG_DEBUG, "queue_thread_main: rrd_update (%s, %i, %p)",
161         file, values_num, (void *) values);
162
163     status = rrd_update_r (file, NULL, values_num, values);
164     if (status != 0)
165     {
166       RRDD_LOG (LOG_ERR, "queue_thread_main: "
167           "rrd_update_r failed with status %i.",
168           status);
169     }
170
171     free (file);
172     for (i = 0; i < values_num; i++)
173       free (values[i]);
174
175     pthread_mutex_lock (&cache_lock);
176   } /* while (do_shutdown == 0) */
177   pthread_mutex_unlock (&cache_lock);
178
179   RRDD_LOG (LOG_DEBUG, "queue_thread_main: Exiting.");
180
181   return (NULL);
182 } /* }}} void *queue_thread_main */
183
184 static int handle_request_update (int fd, /* {{{ */
185     char *buffer, int buffer_size)
186 {
187   char *file;
188   char *value;
189   char *buffer_ptr;
190   int values_num = 0;
191
192   time_t now;
193
194   avl_node_t *node;
195   cache_item_t ci_temp;
196   cache_item_t *ci;
197
198   char answer[4096];
199
200   now = time (NULL);
201
202   RRDD_LOG (LOG_DEBUG, "handle_request_update (%i, %p, %i)",
203       fd, (void *) buffer, buffer_size);
204
205   buffer_ptr = buffer;
206
207   file = buffer_ptr;
208   buffer_ptr += strlen (file) + 1;
209
210   ci_temp.file = file;
211
212   pthread_mutex_lock (&cache_lock);
213
214   node = avl_search (cache_tree, (void *) &ci_temp);
215   if (node == NULL)
216   {
217     ci = (cache_item_t *) malloc (sizeof (cache_item_t));
218     if (ci == NULL)
219     {
220       pthread_mutex_unlock (&cache_lock);
221       RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
222       return (-1);
223     }
224     memset (ci, 0, sizeof (cache_item_t));
225
226     ci->file = strdup (file);
227     if (ci->file == NULL)
228     {
229       pthread_mutex_unlock (&cache_lock);
230       RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
231       free (ci);
232       return (-1);
233     }
234
235     ci->values = NULL;
236     ci->values_num = 0;
237     ci->last_flush_time = now;
238     ci->flags = CI_FLAGS_IN_TREE;
239
240     if (avl_insert (cache_tree, (void *) ci) == NULL)
241     {
242       pthread_mutex_unlock (&cache_lock);
243       RRDD_LOG (LOG_ERR, "handle_request_update: avl_insert failed.");
244       free (ci->file);
245       free (ci);
246       return (-1);
247     }
248
249     RRDD_LOG (LOG_DEBUG, "handle_request_update: Created new AVL node %s.",
250         ci->file);
251   }
252   else /* if (ci != NULL) */
253   {
254     ci = (cache_item_t *) node->item;
255   }
256   assert (ci != NULL);
257
258   while (*buffer_ptr != 0)
259   {
260     char **temp;
261
262     value = buffer_ptr;
263     buffer_ptr += strlen (value) + 1;
264
265     temp = (char **) realloc (ci->values,
266         sizeof (char *) * (ci->values_num + 1));
267     if (temp == NULL)
268     {
269       RRDD_LOG (LOG_ERR, "handle_request_update: realloc failed.");
270       continue;
271     }
272     ci->values = temp;
273
274     ci->values[ci->values_num] = strdup (value);
275     if (ci->values[ci->values_num] == NULL)
276     {
277       RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
278       continue;
279     }
280     ci->values_num++;
281
282     values_num++;
283   }
284
285   /* FIXME: Timeout should not be hard-coded. */
286   if (((now - ci->last_flush_time) > 300)
287       && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0))
288   {
289     RRDD_LOG (LOG_DEBUG, "handle_request_update: Adding %s to the update queue.",
290         ci->file);
291
292     assert (ci->next == NULL);
293
294     if (cache_queue_tail == NULL)
295       cache_queue_head = ci;
296     else
297       cache_queue_tail->next = ci;
298     cache_queue_tail = ci;
299
300     pthread_cond_signal (&cache_cond);
301   }
302
303   pthread_mutex_unlock (&cache_lock);
304
305   snprintf (answer, sizeof (answer), "0 Enqueued %i value(s)\n", values_num);
306   answer[sizeof (answer) - 1] = 0;
307
308   write (fd, answer, sizeof (answer));
309
310   return (0);
311 } /* }}} int handle_request_update */
312
313 static int handle_request (int fd) /* {{{ */
314 {
315   char buffer[4096];
316   int buffer_size;
317
318   RRDD_LOG (LOG_DEBUG, "handle_request (%i)", fd);
319
320   buffer_size = read (fd, buffer, sizeof (buffer));
321   if (buffer_size < 1)
322   {
323     RRDD_LOG (LOG_ERR, "handle_request: read(2) failed.");
324     return (-1);
325   }
326   assert (((size_t) buffer_size) <= sizeof (buffer));
327
328   if ((buffer[buffer_size - 2] != 0)
329       || (buffer[buffer_size - 1] != 0))
330   {
331     RRDD_LOG (LOG_INFO, "handle_request: malformed request.");
332     return (-1);
333   }
334
335   /* fields in the buffer a separated by null bytes. */
336   if (strcmp (buffer, "update") == 0)
337   {
338     int offset = strlen ("update") + 1;
339     return (handle_request_update (fd, buffer + offset,
340           buffer_size - offset));
341   }
342   else
343   {
344     RRDD_LOG (LOG_INFO, "handle_request: unknown command: %s.", buffer);
345     return (-1);
346   }
347 } /* }}} int handle_request */
348
349 static void *connection_thread_main (void *args) /* {{{ */
350 {
351   pthread_t self;
352   int i;
353   int fd;
354   
355   fd = *((int *) args);
356
357   RRDD_LOG (LOG_DEBUG, "connection_thread_main: Adding myself to "
358       "connetion_threads[]..");
359   pthread_mutex_lock (&connetion_threads_lock);
360   {
361     pthread_t *temp;
362
363     temp = (pthread_t *) realloc (connetion_threads,
364         sizeof (pthread_t) * (connetion_threads_num + 1));
365     if (temp == NULL)
366     {
367       RRDD_LOG (LOG_ERR, "connection_thread_main: realloc failed.");
368     }
369     else
370     {
371       connetion_threads = temp;
372       connetion_threads[connetion_threads_num] = pthread_self ();
373       connetion_threads_num++;
374     }
375   }
376   pthread_mutex_unlock (&connetion_threads_lock);
377   RRDD_LOG (LOG_DEBUG, "connection_thread_main: done");
378
379   while (do_shutdown == 0)
380   {
381     struct pollfd pollfd;
382     int status;
383
384     pollfd.fd = fd;
385     pollfd.events = POLLIN | POLLPRI;
386     pollfd.revents = 0;
387
388     status = poll (&pollfd, 1, /* timeout = */ 500);
389     if (status == 0) /* timeout */
390       continue;
391     else if (status < 0) /* error */
392     {
393       status = errno;
394       if (status == EINTR)
395         continue;
396       RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
397       continue;
398     }
399
400     if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
401     {
402       close (fd);
403       break;
404     }
405     else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
406     {
407       RRDD_LOG (LOG_WARNING, "connection_thread_main: poll(2) returned "
408           "something unexpected.");
409       close (fd);
410       break;
411     }
412
413     status = handle_request (fd);
414     if (status != 0)
415     {
416       close (fd);
417       break;
418     }
419   }
420
421   self = pthread_self ();
422   /* Remove this thread from the connection threads list */
423   pthread_mutex_lock (&connetion_threads_lock);
424   /* Find out own index in the array */
425   for (i = 0; i < connetion_threads_num; i++)
426     if (pthread_equal (connetion_threads[i], self) != 0)
427       break;
428   assert (i < connetion_threads_num);
429
430   /* Move the trailing threads forward. */
431   if (i < (connetion_threads_num - 1))
432   {
433     memmove (connetion_threads + i,
434         connetion_threads + i + 1,
435         sizeof (pthread_t) * (connetion_threads_num - i - 1));
436   }
437
438   connetion_threads_num--;
439   pthread_mutex_unlock (&connetion_threads_lock);
440
441   free (args);
442   return (NULL);
443 } /* }}} void *connection_thread_main */
444
445 static int open_listen_socket (const char *path) /* {{{ */
446 {
447   int fd;
448   struct sockaddr_un sa;
449   listen_socket_t *temp;
450   int status;
451
452   temp = (listen_socket_t *) realloc (listen_fds,
453       sizeof (listen_fds[0]) * (listen_fds_num + 1));
454   if (temp == NULL)
455   {
456     RRDD_LOG (LOG_ERR, "open_listen_socket: realloc failed.");
457     return (-1);
458   }
459   listen_fds = temp;
460   memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
461
462   fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
463   if (fd < 0)
464   {
465     RRDD_LOG (LOG_ERR, "open_listen_socket: socket(2) failed.");
466     return (-1);
467   }
468
469   memset (&sa, 0, sizeof (sa));
470   sa.sun_family = AF_UNIX;
471   strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
472
473   status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
474   if (status != 0)
475   {
476     RRDD_LOG (LOG_ERR, "open_listen_socket: bind(2) failed.");
477     close (fd);
478     unlink (path);
479     return (-1);
480   }
481
482   status = listen (fd, /* backlog = */ 10);
483   if (status != 0)
484   {
485     RRDD_LOG (LOG_ERR, "open_listen_socket: listen(2) failed.");
486     close (fd);
487     unlink (path);
488     return (-1);
489   }
490   
491   listen_fds[listen_fds_num].fd = fd;
492   strncpy (listen_fds[listen_fds_num].path, path,
493       sizeof (listen_fds[listen_fds_num].path) - 1);
494   listen_fds_num++;
495
496   return (0);
497 } /* }}} int open_listen_socket */
498
499 static int close_listen_sockets (void) /* {{{ */
500 {
501   size_t i;
502
503   for (i = 0; i < listen_fds_num; i++)
504   {
505     close (listen_fds[i].fd);
506     unlink (listen_fds[i].path);
507   }
508
509   free (listen_fds);
510   listen_fds = NULL;
511   listen_fds_num = 0;
512
513   return (0);
514 } /* }}} int close_listen_sockets */
515
516 static void *listen_thread_main (void *args) /* {{{ */
517 {
518   char buffer[4096];
519   int status;
520   int i;
521
522   status = open_listen_socket (RRDD_SOCK_PATH);
523   if (status != 0)
524   {
525     RRDD_LOG (LOG_ERR, "listen_thread_main: open_listen_socket failed.");
526     return (NULL);
527   }
528
529   while (do_shutdown == 0)
530   {
531     int *client_sd;
532     struct sockaddr_un client_sa;
533     socklen_t client_sa_size;
534     pthread_t tid;
535
536     client_sd = (int *) malloc (sizeof (int));
537     if (client_sd == NULL)
538     {
539       RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
540       sleep (120);
541       continue;
542     }
543
544     client_sa_size = sizeof (client_sa);
545     /* FIXME: Don't implement listen_fds as a list or use poll(2) here! */
546     *client_sd = accept (listen_fds[0].fd,
547         (struct sockaddr *) &client_sa, &client_sa_size);
548     if (*client_sd < 0)
549     {
550       RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
551       continue;
552     }
553
554     RRDD_LOG (LOG_DEBUG, "listen_thread_main: accept(2) returned fd #%i.",
555         *client_sd);
556
557     status = pthread_create (&tid, /* attr = */ NULL, connection_thread_main,
558         /* args = */ (void *) client_sd);
559     if (status != 0)
560     {
561       RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
562       close (*client_sd);
563       free (client_sd);
564       continue;
565     }
566
567     RRDD_LOG (LOG_DEBUG, "listen_thread_main: pthread_create succeeded: "
568         "tid = %lu",
569         *((unsigned long *) &tid));
570   } /* while (do_shutdown == 0) */
571
572   close_listen_sockets ();
573
574   pthread_mutex_lock (&connetion_threads_lock);
575   while (connetion_threads_num > 0)
576   {
577     pthread_t wait_for;
578
579     wait_for = connetion_threads[0];
580
581     pthread_mutex_unlock (&connetion_threads_lock);
582     pthread_join (wait_for, /* retval = */ NULL);
583     pthread_mutex_lock (&connetion_threads_lock);
584   }
585   pthread_mutex_unlock (&connetion_threads_lock);
586
587   RRDD_LOG (LOG_DEBUG, "listen_thread_main: Exiting.");
588
589   return (NULL);
590 } /* }}} void *listen_thread_main */
591
592 static int daemonize (void) /* {{{ */
593 {
594   pid_t child;
595   int status;
596
597 #if !RRDD_DEBUG
598   child = fork ();
599   if (child < 0)
600   {
601     fprintf (stderr, "daemonize: fork(2) failed.\n");
602     return (-1);
603   }
604   else if (child > 0)
605   {
606     return (1);
607   }
608
609   /* Change into the /tmp directory. */
610   chdir ("/tmp");
611
612   /* Become session leader */
613   setsid ();
614
615   /* Open the first three file descriptors to /dev/null */
616   close (2);
617   close (1);
618   close (0);
619
620   open ("/dev/null", O_RDWR);
621   dup (0);
622   dup (0);
623 #endif /* RRDD_DEBUG */
624
625   {
626     struct sigaction sa;
627
628     memset (&sa, 0, sizeof (sa));
629     sa.sa_handler = sig_int_handler;
630     sigaction (SIGINT, &sa, NULL);
631
632     memset (&sa, 0, sizeof (sa));
633     sa.sa_handler = sig_term_handler;
634     sigaction (SIGINT, &sa, NULL);
635   }
636
637   openlog ("rrdd", LOG_PID, LOG_DAEMON);
638
639   cache_tree = avl_alloc_tree (cache_tree_compare, cache_tree_free);
640   if (cache_tree == NULL)
641   {
642     RRDD_LOG (LOG_ERR, "daemonize: avl_alloc_tree failed.");
643     return (-1);
644   }
645
646   memset (&queue_thread, 0, sizeof (queue_thread));
647   status = pthread_create (&queue_thread, /* attr = */ NULL,
648       queue_thread_main, /* args = */ NULL);
649   if (status != 0)
650   {
651     RRDD_LOG (LOG_ERR, "daemonize: pthread_create failed.");
652     return (-1);
653   }
654
655   return (0);
656 } /* }}} int daemonize */
657
658 static int cleanup (void) /* {{{ */
659 {
660   RRDD_LOG (LOG_DEBUG, "cleanup ()");
661
662   do_shutdown++;
663
664   RRDD_LOG (LOG_DEBUG, "cleanup: Joining queue_thread..");
665   pthread_cond_signal (&cache_cond);
666   pthread_join (queue_thread, /* return = */ NULL);
667   RRDD_LOG (LOG_DEBUG, "cleanup: done");
668
669   closelog ();
670
671   return (0);
672 } /* }}} int cleanup */
673
674 int main (int argc, char **argv)
675 {
676   int status;
677
678   printf ("%s by Florian Forster, Version %s\n",
679       PACKAGE_NAME, PACKAGE_VERSION);
680
681   status = daemonize ();
682   if (status == 1)
683   {
684     struct sigaction sigchld;
685
686     memset (&sigchld, 0, sizeof (sigchld));
687     sigchld.sa_handler = SIG_IGN;
688     sigaction (SIGCHLD, &sigchld, NULL);
689
690     return (0);
691   }
692   else if (status != 0)
693   {
694     fprintf (stderr, "daemonize failed, exiting.\n");
695     return (1);
696   }
697
698   listen_thread_main (NULL);
699
700   cleanup ();
701
702   return (0);
703 } /* int main */
704
705 /*
706  * vim: set sw=2 sts=2 ts=8 et fdm=marker :
707  */