1 /**
2 * collectd - src/unixsock.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 * Author:
19 * Florian octo Forster <octo at verplant.org>
20 **/
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25 #include "configfile.h"
27 /* FIXME: Replace this with "utils_cmd_getval.h" asap */
28 #include "utils_cache.h"
30 #include "utils_cmd_putval.h"
31 #include "utils_cmd_putnotif.h"
33 /* Folks without pthread will need to disable this plugin. */
34 #include <pthread.h>
36 #include <sys/socket.h>
37 #include <sys/stat.h>
38 #include <sys/un.h>
40 #include <grp.h>
42 #ifndef UNIX_PATH_MAX
43 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
44 #endif
46 #define US_DEFAULT_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-unixsock"
48 /*
49 * Private data structures
50 */
51 /* linked list of cached values */
52 typedef struct value_cache_s
53 {
54 char name[4*DATA_MAX_NAME_LEN];
55 int values_num;
56 gauge_t *gauge;
57 counter_t *counter;
58 const data_set_t *ds;
59 time_t time;
60 struct value_cache_s *next;
61 } value_cache_t;
63 /*
64 * Private variables
65 */
66 /* valid configuration file keys */
67 static const char *config_keys[] =
68 {
69 "SocketFile",
70 "SocketGroup",
71 "SocketPerms",
72 NULL
73 };
74 static int config_keys_num = 3;
76 static int loop = 0;
78 /* socket configuration */
79 static int sock_fd = -1;
80 static char *sock_file = NULL;
81 static char *sock_group = NULL;
82 static int sock_perms = S_IRWXU | S_IRWXG;
84 static pthread_t listen_thread = (pthread_t) 0;
86 /* Linked list and auxilliary variables for saving values */
87 static value_cache_t *cache_head = NULL;
88 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
89 static time_t cache_oldest = -1;
91 /*
92 * Functions
93 */
94 static value_cache_t *cache_search (const char *name)
95 {
96 value_cache_t *vc;
98 for (vc = cache_head; vc != NULL; vc = vc->next)
99 {
100 if (strcmp (vc->name, name) == 0)
101 break;
102 } /* for vc = cache_head .. NULL */
104 return (vc);
105 } /* value_cache_t *cache_search */
107 static int cache_insert (const data_set_t *ds, const value_list_t *vl)
108 {
109 /* We're called from `cache_update' so we don't need to lock the mutex */
110 value_cache_t *vc;
111 int i;
113 DEBUG ("unixsock plugin: cache_insert: ds->type = %s; ds->ds_num = %i;"
114 " vl->values_len = %i;",
115 ds->type, ds->ds_num, vl->values_len);
116 #if COLLECT_DEBUG
117 assert (ds->ds_num == vl->values_len);
118 #else
119 if (ds->ds_num != vl->values_len)
120 {
121 ERROR ("unixsock plugin: ds->type = %s: (ds->ds_num = %i) != "
122 "(vl->values_len = %i)",
123 ds->type, ds->ds_num, vl->values_len);
124 return (-1);
125 }
126 #endif
128 vc = (value_cache_t *) malloc (sizeof (value_cache_t));
129 if (vc == NULL)
130 {
131 char errbuf[1024];
132 pthread_mutex_unlock (&cache_lock);
133 ERROR ("unixsock plugin: malloc failed: %s",
134 sstrerror (errno, errbuf, sizeof (errbuf)));
135 return (-1);
136 }
138 vc->gauge = (gauge_t *) malloc (sizeof (gauge_t) * vl->values_len);
139 if (vc->gauge == NULL)
140 {
141 char errbuf[1024];
142 pthread_mutex_unlock (&cache_lock);
143 ERROR ("unixsock plugin: malloc failed: %s",
144 sstrerror (errno, errbuf, sizeof (errbuf)));
145 free (vc);
146 return (-1);
147 }
149 vc->counter = (counter_t *) malloc (sizeof (counter_t) * vl->values_len);
150 if (vc->counter == NULL)
151 {
152 char errbuf[1024];
153 pthread_mutex_unlock (&cache_lock);
154 ERROR ("unixsock plugin: malloc failed: %s",
155 sstrerror (errno, errbuf, sizeof (errbuf)));
156 free (vc->gauge);
157 free (vc);
158 return (-1);
159 }
161 if (FORMAT_VL (vc->name, sizeof (vc->name), vl, ds))
162 {
163 pthread_mutex_unlock (&cache_lock);
164 ERROR ("unixsock plugin: FORMAT_VL failed.");
165 free (vc->counter);
166 free (vc->gauge);
167 free (vc);
168 return (-1);
169 }
171 for (i = 0; i < ds->ds_num; i++)
172 {
173 if (ds->ds[i].type == DS_TYPE_COUNTER)
174 {
175 vc->gauge[i] = 0.0;
176 vc->counter[i] = vl->values[i].counter;
177 }
178 else if (ds->ds[i].type == DS_TYPE_GAUGE)
179 {
180 vc->gauge[i] = vl->values[i].gauge;
181 vc->counter[i] = 0;
182 }
183 else
184 {
185 vc->gauge[i] = 0.0;
186 vc->counter[i] = 0;
187 }
188 }
189 vc->values_num = ds->ds_num;
190 vc->ds = ds;
192 vc->next = cache_head;
193 cache_head = vc;
195 vc->time = vl->time;
196 if ((vc->time < cache_oldest) || (-1 == cache_oldest))
197 cache_oldest = vc->time;
199 pthread_mutex_unlock (&cache_lock);
200 return (0);
201 } /* int cache_insert */
203 static int cache_update (const data_set_t *ds, const value_list_t *vl)
204 {
205 char name[4*DATA_MAX_NAME_LEN];;
206 value_cache_t *vc;
207 int i;
209 if (FORMAT_VL (name, sizeof (name), vl, ds) != 0)
210 return (-1);
212 pthread_mutex_lock (&cache_lock);
214 vc = cache_search (name);
216 /* pthread_mutex_lock is called by cache_insert. */
217 if (vc == NULL)
218 return (cache_insert (ds, vl));
220 assert (vc->values_num == ds->ds_num);
221 assert (vc->values_num == vl->values_len);
223 /* Avoid floating-point exceptions due to division by zero. */
224 if (vc->time >= vl->time)
225 {
226 pthread_mutex_unlock (&cache_lock);
227 ERROR ("unixsock plugin: vc->time >= vl->time. vc->time = %u; "
228 "vl->time = %u; vl = %s;",
229 (unsigned int) vc->time, (unsigned int) vl->time,
230 name);
231 return (-1);
232 } /* if (vc->time >= vl->time) */
234 /*
235 * Update the values. This is possibly a lot more that you'd expect
236 * because we honor min and max values and handle counter overflows here.
237 */
238 for (i = 0; i < ds->ds_num; i++)
239 {
240 if (ds->ds[i].type == DS_TYPE_COUNTER)
241 {
242 if (vl->values[i].counter < vc->counter[i])
243 {
244 if (vl->values[i].counter <= 4294967295U)
245 {
246 vc->gauge[i] = ((4294967295U - vl->values[i].counter)
247 + vc->counter[i]) / (vl->time - vc->time);
248 }
249 else
250 {
251 vc->gauge[i] = ((18446744073709551615ULL - vl->values[i].counter)
252 + vc->counter[i]) / (vl->time - vc->time);
253 }
254 }
255 else
256 {
257 vc->gauge[i] = (vl->values[i].counter - vc->counter[i])
258 / (vl->time - vc->time);
259 }
261 vc->counter[i] = vl->values[i].counter;
262 }
263 else if (ds->ds[i].type == DS_TYPE_GAUGE)
264 {
265 vc->gauge[i] = vl->values[i].gauge;
266 vc->counter[i] = 0;
267 }
268 else
269 {
270 vc->gauge[i] = NAN;
271 vc->counter[i] = 0;
272 }
274 if (isnan (vc->gauge[i])
275 || (!isnan (ds->ds[i].min) && (vc->gauge[i] < ds->ds[i].min))
276 || (!isnan (ds->ds[i].max) && (vc->gauge[i] > ds->ds[i].max)))
277 vc->gauge[i] = NAN;
278 } /* for i = 0 .. ds->ds_num */
280 vc->ds = ds;
281 vc->time = vl->time;
283 if ((vc->time < cache_oldest) || (-1 == cache_oldest))
284 cache_oldest = vc->time;
286 pthread_mutex_unlock (&cache_lock);
287 return (0);
288 } /* int cache_update */
290 static void cache_flush (int max_age)
291 {
292 value_cache_t *this;
293 value_cache_t *prev;
294 time_t now;
296 pthread_mutex_lock (&cache_lock);
298 now = time (NULL);
300 if ((now - cache_oldest) <= max_age)
301 {
302 pthread_mutex_unlock (&cache_lock);
303 return;
304 }
306 cache_oldest = now;
308 prev = NULL;
309 this = cache_head;
311 while (this != NULL)
312 {
313 if ((now - this->time) <= max_age)
314 {
315 if (this->time < cache_oldest)
316 cache_oldest = this->time;
318 prev = this;
319 this = this->next;
320 continue;
321 }
323 if (prev == NULL)
324 cache_head = this->next;
325 else
326 prev->next = this->next;
328 free (this->gauge);
329 free (this->counter);
330 free (this);
332 if (prev == NULL)
333 this = cache_head;
334 else
335 this = prev->next;
336 } /* while (this != NULL) */
338 pthread_mutex_unlock (&cache_lock);
339 } /* void cache_flush */
341 static int us_open_socket (void)
342 {
343 struct sockaddr_un sa;
344 int status;
346 sock_fd = socket (PF_UNIX, SOCK_STREAM, 0);
347 if (sock_fd < 0)
348 {
349 char errbuf[1024];
350 ERROR ("unixsock plugin: socket failed: %s",
351 sstrerror (errno, errbuf, sizeof (errbuf)));
352 return (-1);
353 }
355 memset (&sa, '\0', sizeof (sa));
356 sa.sun_family = AF_UNIX;
357 strncpy (sa.sun_path, (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
358 sizeof (sa.sun_path) - 1);
359 /* unlink (sa.sun_path); */
361 DEBUG ("unixsock plugin: socket path = %s", sa.sun_path);
363 status = bind (sock_fd, (struct sockaddr *) &sa, sizeof (sa));
364 if (status != 0)
365 {
366 char errbuf[1024];
367 sstrerror (errno, errbuf, sizeof (errbuf));
368 ERROR ("unixsock plugin: bind failed: %s", errbuf);
369 close (sock_fd);
370 sock_fd = -1;
371 return (-1);
372 }
374 chmod (sa.sun_path, sock_perms);
376 status = listen (sock_fd, 8);
377 if (status != 0)
378 {
379 char errbuf[1024];
380 ERROR ("unixsock plugin: listen failed: %s",
381 sstrerror (errno, errbuf, sizeof (errbuf)));
382 close (sock_fd);
383 sock_fd = -1;
384 return (-1);
385 }
387 do
388 {
389 char *grpname;
390 struct group *g;
391 struct group sg;
392 char grbuf[2048];
394 grpname = (sock_group != NULL) ? sock_group : COLLECTD_GRP_NAME;
395 g = NULL;
397 status = getgrnam_r (grpname, &sg, grbuf, sizeof (grbuf), &g);
398 if (status != 0)
399 {
400 char errbuf[1024];
401 WARNING ("unixsock plugin: getgrnam_r (%s) failed: %s", grpname,
402 sstrerror (errno, errbuf, sizeof (errbuf)));
403 break;
404 }
405 if (g == NULL)
406 {
407 WARNING ("unixsock plugin: No such group: `%s'",
408 grpname);
409 break;
410 }
412 if (chown ((sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
413 (uid_t) -1, g->gr_gid) != 0)
414 {
415 char errbuf[1024];
416 WARNING ("unixsock plugin: chown (%s, -1, %i) failed: %s",
417 (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
418 (int) g->gr_gid,
419 sstrerror (errno, errbuf, sizeof (errbuf)));
420 }
421 } while (0);
423 return (0);
424 } /* int us_open_socket */
426 static int us_handle_getval (FILE *fh, char **fields, int fields_num)
427 {
428 char *hostname;
429 char *plugin;
430 char *plugin_instance;
431 char *type;
432 char *type_instance;
433 gauge_t *values;
434 size_t values_num;
436 const data_set_t *ds;
438 int status;
439 int i;
441 if (fields_num != 2)
442 {
443 DEBUG ("unixsock plugin: Wrong number of fields: %i", fields_num);
444 fprintf (fh, "-1 Wrong number of fields: Got %i, expected 2.\n",
445 fields_num);
446 fflush (fh);
447 return (-1);
448 }
449 DEBUG ("unixsock plugin: Got query for `%s'", fields[1]);
451 if (strlen (fields[1]) < strlen ("h/p/t"))
452 {
453 fprintf (fh, "-1 Invalied identifier, %s", fields[1]);
454 fflush (fh);
455 return (-1);
456 }
458 status = parse_identifier (fields[1], &hostname,
459 &plugin, &plugin_instance,
460 &type, &type_instance);
461 if (status != 0)
462 {
463 DEBUG ("unixsock plugin: Cannot parse `%s'", fields[1]);
464 fprintf (fh, "-1 Cannot parse identifier.\n");
465 fflush (fh);
466 return (-1);
467 }
469 ds = plugin_get_ds (type);
470 if (ds == NULL)
471 {
472 DEBUG ("unixsock plugin: plugin_get_ds (%s) == NULL;", type);
473 fprintf (fh, "-1 Type `%s' is unknown.\n", type);
474 fflush (fh);
475 return (-1);
476 }
478 values = NULL;
479 values_num = 0;
480 status = uc_get_rate_by_name (fields[1], &values, &values_num);
481 if (status != 0)
482 {
483 fprintf (fh, "-1 No such value");
484 fflush (fh);
485 return (-1);
486 }
488 if (ds->ds_num != values_num)
489 {
490 ERROR ("ds[%s]->ds_num = %i, "
491 "but uc_get_rate_by_name returned %i values.",
492 ds->type, ds->ds_num, values_num);
493 fprintf (fh, "-1 Error reading value from cache.\n");
494 fflush (fh);
495 sfree (values);
496 return (-1);
497 }
499 fprintf (fh, "%u", (unsigned int) values_num);
500 for (i = 0; i < values_num; i++)
501 {
502 fprintf (fh, " %s=", ds->ds[i].name);
503 if (isnan (values[i]))
504 fprintf (fh, "NaN");
505 else
506 fprintf (fh, "%12e", values[i]);
507 }
509 fprintf (fh, "\n");
510 fflush (fh);
512 sfree (values);
514 return (0);
515 } /* int us_handle_getval */
517 static int us_handle_listval (FILE *fh, char **fields, int fields_num)
518 {
519 char buffer[1024];
520 char **value_list = NULL;
521 int value_list_len = 0;
522 value_cache_t *entry;
523 int i;
525 if (fields_num != 1)
526 {
527 DEBUG ("unixsock plugin: us_handle_listval: "
528 "Wrong number of fields: %i", fields_num);
529 fprintf (fh, "-1 Wrong number of fields: Got %i, expected 1.\n",
530 fields_num);
531 fflush (fh);
532 return (-1);
533 }
535 pthread_mutex_lock (&cache_lock);
537 for (entry = cache_head; entry != NULL; entry = entry->next)
538 {
539 char **tmp;
541 snprintf (buffer, sizeof (buffer), "%u %s\n",
542 (unsigned int) entry->time, entry->name);
543 buffer[sizeof (buffer) - 1] = '\0';
545 tmp = realloc (value_list, sizeof (char *) * (value_list_len + 1));
546 if (tmp == NULL)
547 continue;
548 value_list = tmp;
550 value_list[value_list_len] = strdup (buffer);
552 if (value_list[value_list_len] != NULL)
553 value_list_len++;
554 } /* for (entry) */
556 pthread_mutex_unlock (&cache_lock);
558 DEBUG ("unixsock plugin: us_handle_listval: value_list_len = %i", value_list_len);
559 fprintf (fh, "%i Values found\n", value_list_len);
560 for (i = 0; i < value_list_len; i++)
561 fputs (value_list[i], fh);
562 fflush (fh);
564 return (0);
565 } /* int us_handle_listval */
567 static void *us_handle_client (void *arg)
568 {
569 int fd;
570 FILE *fh;
571 char buffer[1024];
572 char *fields[128];
573 int fields_num;
575 fd = *((int *) arg);
576 free (arg);
577 arg = NULL;
579 DEBUG ("Reading from fd #%i", fd);
581 fh = fdopen (fd, "r+");
582 if (fh == NULL)
583 {
584 char errbuf[1024];
585 ERROR ("unixsock plugin: fdopen failed: %s",
586 sstrerror (errno, errbuf, sizeof (errbuf)));
587 close (fd);
588 pthread_exit ((void *) 1);
589 }
591 while (fgets (buffer, sizeof (buffer), fh) != NULL)
592 {
593 int len;
595 len = strlen (buffer);
596 while ((len > 0)
597 && ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
598 buffer[--len] = '\0';
600 if (len == 0)
601 continue;
603 DEBUG ("fgets -> buffer = %s; len = %i;", buffer, len);
605 fields_num = strsplit (buffer, fields,
606 sizeof (fields) / sizeof (fields[0]));
608 if (fields_num < 1)
609 {
610 close (fd);
611 break;
612 }
614 if (strcasecmp (fields[0], "getval") == 0)
615 {
616 us_handle_getval (fh, fields, fields_num);
617 }
618 else if (strcasecmp (fields[0], "putval") == 0)
619 {
620 handle_putval (fh, fields, fields_num);
621 }
622 else if (strcasecmp (fields[0], "listval") == 0)
623 {
624 us_handle_listval (fh, fields, fields_num);
625 }
626 else if (strcasecmp (fields[0], "putnotif") == 0)
627 {
628 handle_putnotif (fh, fields, fields_num);
629 }
630 else
631 {
632 fprintf (fh, "-1 Unknown command: %s\n", fields[0]);
633 fflush (fh);
634 }
635 } /* while (fgets) */
637 DEBUG ("Exiting..");
638 close (fd);
640 pthread_exit ((void *) 0);
641 } /* void *us_handle_client */
643 static void *us_server_thread (void *arg)
644 {
645 int status;
646 int *remote_fd;
647 pthread_t th;
648 pthread_attr_t th_attr;
650 if (us_open_socket () != 0)
651 pthread_exit ((void *) 1);
653 while (loop != 0)
654 {
655 DEBUG ("unixsock plugin: Calling accept..");
656 status = accept (sock_fd, NULL, NULL);
657 if (status < 0)
658 {
659 char errbuf[1024];
661 if (errno == EINTR)
662 continue;
664 ERROR ("unixsock plugin: accept failed: %s",
665 sstrerror (errno, errbuf, sizeof (errbuf)));
666 close (sock_fd);
667 sock_fd = -1;
668 pthread_exit ((void *) 1);
669 }
671 remote_fd = (int *) malloc (sizeof (int));
672 if (remote_fd == NULL)
673 {
674 char errbuf[1024];
675 WARNING ("unixsock plugin: malloc failed: %s",
676 sstrerror (errno, errbuf, sizeof (errbuf)));
677 close (status);
678 continue;
679 }
680 *remote_fd = status;
682 DEBUG ("Spawning child to handle connection on fd #%i", *remote_fd);
684 pthread_attr_init (&th_attr);
685 pthread_attr_setdetachstate (&th_attr, PTHREAD_CREATE_DETACHED);
687 status = pthread_create (&th, &th_attr, us_handle_client, (void *) remote_fd);
688 if (status != 0)
689 {
690 char errbuf[1024];
691 WARNING ("unixsock plugin: pthread_create failed: %s",
692 sstrerror (errno, errbuf, sizeof (errbuf)));
693 close (*remote_fd);
694 free (remote_fd);
695 continue;
696 }
697 } /* while (loop) */
699 close (sock_fd);
700 sock_fd = -1;
702 status = unlink ((sock_file != NULL) ? sock_file : US_DEFAULT_PATH);
703 if (status != 0)
704 {
705 char errbuf[1024];
706 NOTICE ("unixsock plugin: unlink (%s) failed: %s",
707 (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
708 sstrerror (errno, errbuf, sizeof (errbuf)));
709 }
711 return ((void *) 0);
712 } /* void *us_server_thread */
714 static int us_config (const char *key, const char *val)
715 {
716 if (strcasecmp (key, "SocketFile") == 0)
717 {
718 sfree (sock_file);
719 sock_file = strdup (val);
720 }
721 else if (strcasecmp (key, "SocketGroup") == 0)
722 {
723 sfree (sock_group);
724 sock_group = strdup (val);
725 }
726 else if (strcasecmp (key, "SocketPerms") == 0)
727 {
728 sock_perms = (int) strtol (val, NULL, 8);
729 }
730 else
731 {
732 return (-1);
733 }
735 return (0);
736 } /* int us_config */
738 static int us_init (void)
739 {
740 int status;
742 loop = 1;
744 status = pthread_create (&listen_thread, NULL, us_server_thread, NULL);
745 if (status != 0)
746 {
747 char errbuf[1024];
748 ERROR ("unixsock plugin: pthread_create failed: %s",
749 sstrerror (errno, errbuf, sizeof (errbuf)));
750 return (-1);
751 }
753 return (0);
754 } /* int us_init */
756 static int us_shutdown (void)
757 {
758 void *ret;
760 loop = 0;
762 if (listen_thread != (pthread_t) 0)
763 {
764 pthread_kill (listen_thread, SIGTERM);
765 pthread_join (listen_thread, &ret);
766 listen_thread = (pthread_t) 0;
767 }
769 plugin_unregister_init ("unixsock");
770 plugin_unregister_write ("unixsock");
771 plugin_unregister_shutdown ("unixsock");
773 return (0);
774 } /* int us_shutdown */
776 static int us_write (const data_set_t *ds, const value_list_t *vl)
777 {
778 cache_update (ds, vl);
779 cache_flush (2 * interval_g);
781 return (0);
782 }
784 void module_register (void)
785 {
786 plugin_register_config ("unixsock", us_config,
787 config_keys, config_keys_num);
788 plugin_register_init ("unixsock", us_init);
789 plugin_register_write ("unixsock", us_write);
790 plugin_register_shutdown ("unixsock", us_shutdown);
791 } /* void module_register (void) */
793 /* vim: set sw=4 ts=4 sts=4 tw=78 : */