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 #include "utils_cmd_putval.h"
28 #include "utils_cmd_putnotif.h"
30 /* Folks without pthread will need to disable this plugin. */
31 #include <pthread.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/un.h>
37 #include <grp.h>
39 #ifndef UNIX_PATH_MAX
40 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
41 #endif
43 #define US_DEFAULT_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-unixsock"
45 /*
46 * Private data structures
47 */
48 /* linked list of cached values */
49 typedef struct value_cache_s
50 {
51 char name[4*DATA_MAX_NAME_LEN];
52 int values_num;
53 gauge_t *gauge;
54 counter_t *counter;
55 const data_set_t *ds;
56 time_t time;
57 struct value_cache_s *next;
58 } value_cache_t;
60 /*
61 * Private variables
62 */
63 /* valid configuration file keys */
64 static const char *config_keys[] =
65 {
66 "SocketFile",
67 "SocketGroup",
68 "SocketPerms",
69 NULL
70 };
71 static int config_keys_num = 3;
73 static int loop = 0;
75 /* socket configuration */
76 static int sock_fd = -1;
77 static char *sock_file = NULL;
78 static char *sock_group = NULL;
79 static int sock_perms = S_IRWXU | S_IRWXG;
81 static pthread_t listen_thread = (pthread_t) 0;
83 /* Linked list and auxilliary variables for saving values */
84 static value_cache_t *cache_head = NULL;
85 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
86 static time_t cache_oldest = -1;
88 /*
89 * Functions
90 */
91 static value_cache_t *cache_search (const char *name)
92 {
93 value_cache_t *vc;
95 for (vc = cache_head; vc != NULL; vc = vc->next)
96 {
97 if (strcmp (vc->name, name) == 0)
98 break;
99 } /* for vc = cache_head .. NULL */
101 return (vc);
102 } /* value_cache_t *cache_search */
104 static int cache_insert (const data_set_t *ds, const value_list_t *vl)
105 {
106 /* We're called from `cache_update' so we don't need to lock the mutex */
107 value_cache_t *vc;
108 int i;
110 DEBUG ("unixsock plugin: cache_insert: ds->type = %s; ds->ds_num = %i;"
111 " vl->values_len = %i;",
112 ds->type, ds->ds_num, vl->values_len);
113 #if COLLECT_DEBUG
114 assert (ds->ds_num == vl->values_len);
115 #else
116 if (ds->ds_num != vl->values_len)
117 {
118 ERROR ("unixsock plugin: ds->type = %s: (ds->ds_num = %i) != "
119 "(vl->values_len = %i)",
120 ds->type, ds->ds_num, vl->values_len);
121 return (-1);
122 }
123 #endif
125 vc = (value_cache_t *) malloc (sizeof (value_cache_t));
126 if (vc == NULL)
127 {
128 char errbuf[1024];
129 pthread_mutex_unlock (&cache_lock);
130 ERROR ("unixsock plugin: malloc failed: %s",
131 sstrerror (errno, errbuf, sizeof (errbuf)));
132 return (-1);
133 }
135 vc->gauge = (gauge_t *) malloc (sizeof (gauge_t) * vl->values_len);
136 if (vc->gauge == NULL)
137 {
138 char errbuf[1024];
139 pthread_mutex_unlock (&cache_lock);
140 ERROR ("unixsock plugin: malloc failed: %s",
141 sstrerror (errno, errbuf, sizeof (errbuf)));
142 free (vc);
143 return (-1);
144 }
146 vc->counter = (counter_t *) malloc (sizeof (counter_t) * vl->values_len);
147 if (vc->counter == NULL)
148 {
149 char errbuf[1024];
150 pthread_mutex_unlock (&cache_lock);
151 ERROR ("unixsock plugin: malloc failed: %s",
152 sstrerror (errno, errbuf, sizeof (errbuf)));
153 free (vc->gauge);
154 free (vc);
155 return (-1);
156 }
158 if (FORMAT_VL (vc->name, sizeof (vc->name), vl, ds))
159 {
160 pthread_mutex_unlock (&cache_lock);
161 ERROR ("unixsock plugin: FORMAT_VL failed.");
162 free (vc->counter);
163 free (vc->gauge);
164 free (vc);
165 return (-1);
166 }
168 for (i = 0; i < ds->ds_num; i++)
169 {
170 if (ds->ds[i].type == DS_TYPE_COUNTER)
171 {
172 vc->gauge[i] = 0.0;
173 vc->counter[i] = vl->values[i].counter;
174 }
175 else if (ds->ds[i].type == DS_TYPE_GAUGE)
176 {
177 vc->gauge[i] = vl->values[i].gauge;
178 vc->counter[i] = 0;
179 }
180 else
181 {
182 vc->gauge[i] = 0.0;
183 vc->counter[i] = 0;
184 }
185 }
186 vc->values_num = ds->ds_num;
187 vc->ds = ds;
189 vc->next = cache_head;
190 cache_head = vc;
192 vc->time = vl->time;
193 if ((vc->time < cache_oldest) || (-1 == cache_oldest))
194 cache_oldest = vc->time;
196 pthread_mutex_unlock (&cache_lock);
197 return (0);
198 } /* int cache_insert */
200 static int cache_update (const data_set_t *ds, const value_list_t *vl)
201 {
202 char name[4*DATA_MAX_NAME_LEN];;
203 value_cache_t *vc;
204 int i;
206 if (FORMAT_VL (name, sizeof (name), vl, ds) != 0)
207 return (-1);
209 pthread_mutex_lock (&cache_lock);
211 vc = cache_search (name);
213 /* pthread_mutex_lock is called by cache_insert. */
214 if (vc == NULL)
215 return (cache_insert (ds, vl));
217 assert (vc->values_num == ds->ds_num);
218 assert (vc->values_num == vl->values_len);
220 /* Avoid floating-point exceptions due to division by zero. */
221 if (vc->time >= vl->time)
222 {
223 pthread_mutex_unlock (&cache_lock);
224 ERROR ("unixsock plugin: vc->time >= vl->time. vc->time = %u; "
225 "vl->time = %u; vl = %s;",
226 (unsigned int) vc->time, (unsigned int) vl->time,
227 name);
228 return (-1);
229 } /* if (vc->time >= vl->time) */
231 /*
232 * Update the values. This is possibly a lot more that you'd expect
233 * because we honor min and max values and handle counter overflows here.
234 */
235 for (i = 0; i < ds->ds_num; i++)
236 {
237 if (ds->ds[i].type == DS_TYPE_COUNTER)
238 {
239 if (vl->values[i].counter < vc->counter[i])
240 {
241 if (vl->values[i].counter <= 4294967295U)
242 {
243 vc->gauge[i] = ((4294967295U - vl->values[i].counter)
244 + vc->counter[i]) / (vl->time - vc->time);
245 }
246 else
247 {
248 vc->gauge[i] = ((18446744073709551615ULL - vl->values[i].counter)
249 + vc->counter[i]) / (vl->time - vc->time);
250 }
251 }
252 else
253 {
254 vc->gauge[i] = (vl->values[i].counter - vc->counter[i])
255 / (vl->time - vc->time);
256 }
258 vc->counter[i] = vl->values[i].counter;
259 }
260 else if (ds->ds[i].type == DS_TYPE_GAUGE)
261 {
262 vc->gauge[i] = vl->values[i].gauge;
263 vc->counter[i] = 0;
264 }
265 else
266 {
267 vc->gauge[i] = NAN;
268 vc->counter[i] = 0;
269 }
271 if (isnan (vc->gauge[i])
272 || (!isnan (ds->ds[i].min) && (vc->gauge[i] < ds->ds[i].min))
273 || (!isnan (ds->ds[i].max) && (vc->gauge[i] > ds->ds[i].max)))
274 vc->gauge[i] = NAN;
275 } /* for i = 0 .. ds->ds_num */
277 vc->ds = ds;
278 vc->time = vl->time;
280 if ((vc->time < cache_oldest) || (-1 == cache_oldest))
281 cache_oldest = vc->time;
283 pthread_mutex_unlock (&cache_lock);
284 return (0);
285 } /* int cache_update */
287 static void cache_flush (int max_age)
288 {
289 value_cache_t *this;
290 value_cache_t *prev;
291 time_t now;
293 pthread_mutex_lock (&cache_lock);
295 now = time (NULL);
297 if ((now - cache_oldest) <= max_age)
298 {
299 pthread_mutex_unlock (&cache_lock);
300 return;
301 }
303 cache_oldest = now;
305 prev = NULL;
306 this = cache_head;
308 while (this != NULL)
309 {
310 if ((now - this->time) <= max_age)
311 {
312 if (this->time < cache_oldest)
313 cache_oldest = this->time;
315 prev = this;
316 this = this->next;
317 continue;
318 }
320 if (prev == NULL)
321 cache_head = this->next;
322 else
323 prev->next = this->next;
325 free (this->gauge);
326 free (this->counter);
327 free (this);
329 if (prev == NULL)
330 this = cache_head;
331 else
332 this = prev->next;
333 } /* while (this != NULL) */
335 pthread_mutex_unlock (&cache_lock);
336 } /* void cache_flush */
338 static int us_open_socket (void)
339 {
340 struct sockaddr_un sa;
341 int status;
343 sock_fd = socket (PF_UNIX, SOCK_STREAM, 0);
344 if (sock_fd < 0)
345 {
346 char errbuf[1024];
347 ERROR ("unixsock plugin: socket failed: %s",
348 sstrerror (errno, errbuf, sizeof (errbuf)));
349 return (-1);
350 }
352 memset (&sa, '\0', sizeof (sa));
353 sa.sun_family = AF_UNIX;
354 strncpy (sa.sun_path, (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
355 sizeof (sa.sun_path) - 1);
356 /* unlink (sa.sun_path); */
358 DEBUG ("unixsock plugin: socket path = %s", sa.sun_path);
360 status = bind (sock_fd, (struct sockaddr *) &sa, sizeof (sa));
361 if (status != 0)
362 {
363 char errbuf[1024];
364 sstrerror (errno, errbuf, sizeof (errbuf));
365 ERROR ("unixsock plugin: bind failed: %s", errbuf);
366 close (sock_fd);
367 sock_fd = -1;
368 return (-1);
369 }
371 chmod (sa.sun_path, sock_perms);
373 status = listen (sock_fd, 8);
374 if (status != 0)
375 {
376 char errbuf[1024];
377 ERROR ("unixsock plugin: listen failed: %s",
378 sstrerror (errno, errbuf, sizeof (errbuf)));
379 close (sock_fd);
380 sock_fd = -1;
381 return (-1);
382 }
384 do
385 {
386 char *grpname;
387 struct group *g;
388 struct group sg;
389 char grbuf[2048];
391 grpname = (sock_group != NULL) ? sock_group : COLLECTD_GRP_NAME;
392 g = NULL;
394 status = getgrnam_r (grpname, &sg, grbuf, sizeof (grbuf), &g);
395 if (status != 0)
396 {
397 char errbuf[1024];
398 WARNING ("unixsock plugin: getgrnam_r (%s) failed: %s", grpname,
399 sstrerror (errno, errbuf, sizeof (errbuf)));
400 break;
401 }
402 if (g == NULL)
403 {
404 WARNING ("unixsock plugin: No such group: `%s'",
405 grpname);
406 break;
407 }
409 if (chown ((sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
410 (uid_t) -1, g->gr_gid) != 0)
411 {
412 char errbuf[1024];
413 WARNING ("unixsock plugin: chown (%s, -1, %i) failed: %s",
414 (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
415 (int) g->gr_gid,
416 sstrerror (errno, errbuf, sizeof (errbuf)));
417 }
418 } while (0);
420 return (0);
421 } /* int us_open_socket */
423 static int us_handle_getval (FILE *fh, char **fields, int fields_num)
424 {
425 char *hostname;
426 char *plugin;
427 char *plugin_instance;
428 char *type;
429 char *type_instance;
430 char name[4*DATA_MAX_NAME_LEN];
431 value_cache_t *vc;
432 int status;
433 int i;
435 if (fields_num != 2)
436 {
437 DEBUG ("unixsock plugin: Wrong number of fields: %i", fields_num);
438 fprintf (fh, "-1 Wrong number of fields: Got %i, expected 2.\n",
439 fields_num);
440 fflush (fh);
441 return (-1);
442 }
443 DEBUG ("unixsock plugin: Got query for `%s'", fields[1]);
445 status = parse_identifier (fields[1], &hostname,
446 &plugin, &plugin_instance,
447 &type, &type_instance);
448 if (status != 0)
449 {
450 DEBUG ("unixsock plugin: Cannot parse `%s'", fields[1]);
451 fprintf (fh, "-1 Cannot parse identifier.\n");
452 fflush (fh);
453 return (-1);
454 }
456 status = format_name (name, sizeof (name),
457 hostname, plugin, plugin_instance, type, type_instance);
458 if (status != 0)
459 {
460 fprintf (fh, "-1 format_name failed.\n");
461 return (-1);
462 }
464 pthread_mutex_lock (&cache_lock);
466 DEBUG ("vc = cache_search (%s)", name);
467 vc = cache_search (name);
469 if (vc == NULL)
470 {
471 DEBUG ("Did not find cache entry.");
472 fprintf (fh, "-1 No such value");
473 }
474 else
475 {
476 DEBUG ("Found cache entry.");
477 fprintf (fh, "%i", vc->values_num);
478 for (i = 0; i < vc->values_num; i++)
479 {
480 fprintf (fh, " %s=", vc->ds->ds[i].name);
481 if (isnan (vc->gauge[i]))
482 fprintf (fh, "NaN");
483 else
484 fprintf (fh, "%12e", vc->gauge[i]);
485 }
486 }
488 /* Free the mutex as soon as possible and definitely before flushing */
489 pthread_mutex_unlock (&cache_lock);
491 fprintf (fh, "\n");
492 fflush (fh);
494 return (0);
495 } /* int us_handle_getval */
497 static int us_handle_listval (FILE *fh, char **fields, int fields_num)
498 {
499 char buffer[1024];
500 char **value_list = NULL;
501 int value_list_len = 0;
502 value_cache_t *entry;
503 int i;
505 if (fields_num != 1)
506 {
507 DEBUG ("unixsock plugin: us_handle_listval: "
508 "Wrong number of fields: %i", fields_num);
509 fprintf (fh, "-1 Wrong number of fields: Got %i, expected 1.\n",
510 fields_num);
511 fflush (fh);
512 return (-1);
513 }
515 pthread_mutex_lock (&cache_lock);
517 for (entry = cache_head; entry != NULL; entry = entry->next)
518 {
519 char **tmp;
521 snprintf (buffer, sizeof (buffer), "%u %s\n",
522 (unsigned int) entry->time, entry->name);
523 buffer[sizeof (buffer) - 1] = '\0';
525 tmp = realloc (value_list, sizeof (char *) * (value_list_len + 1));
526 if (tmp == NULL)
527 continue;
528 value_list = tmp;
530 value_list[value_list_len] = strdup (buffer);
532 if (value_list[value_list_len] != NULL)
533 value_list_len++;
534 } /* for (entry) */
536 pthread_mutex_unlock (&cache_lock);
538 DEBUG ("unixsock plugin: us_handle_listval: value_list_len = %i", value_list_len);
539 fprintf (fh, "%i Values found\n", value_list_len);
540 for (i = 0; i < value_list_len; i++)
541 fputs (value_list[i], fh);
542 fflush (fh);
544 return (0);
545 } /* int us_handle_listval */
547 static void *us_handle_client (void *arg)
548 {
549 int fd;
550 FILE *fh;
551 char buffer[1024];
552 char *fields[128];
553 int fields_num;
555 fd = *((int *) arg);
556 free (arg);
557 arg = NULL;
559 DEBUG ("Reading from fd #%i", fd);
561 fh = fdopen (fd, "r+");
562 if (fh == NULL)
563 {
564 char errbuf[1024];
565 ERROR ("unixsock plugin: fdopen failed: %s",
566 sstrerror (errno, errbuf, sizeof (errbuf)));
567 close (fd);
568 pthread_exit ((void *) 1);
569 }
571 while (fgets (buffer, sizeof (buffer), fh) != NULL)
572 {
573 int len;
575 len = strlen (buffer);
576 while ((len > 0)
577 && ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
578 buffer[--len] = '\0';
580 if (len == 0)
581 continue;
583 DEBUG ("fgets -> buffer = %s; len = %i;", buffer, len);
585 fields_num = strsplit (buffer, fields,
586 sizeof (fields) / sizeof (fields[0]));
588 if (fields_num < 1)
589 {
590 close (fd);
591 break;
592 }
594 if (strcasecmp (fields[0], "getval") == 0)
595 {
596 us_handle_getval (fh, fields, fields_num);
597 }
598 else if (strcasecmp (fields[0], "putval") == 0)
599 {
600 handle_putval (fh, fields, fields_num);
601 }
602 else if (strcasecmp (fields[0], "listval") == 0)
603 {
604 us_handle_listval (fh, fields, fields_num);
605 }
606 else if (strcasecmp (fields[0], "putnotif") == 0)
607 {
608 handle_putnotif (fh, fields, fields_num);
609 }
610 else
611 {
612 fprintf (fh, "-1 Unknown command: %s\n", fields[0]);
613 fflush (fh);
614 }
615 } /* while (fgets) */
617 DEBUG ("Exiting..");
618 close (fd);
620 pthread_exit ((void *) 0);
621 } /* void *us_handle_client */
623 static void *us_server_thread (void *arg)
624 {
625 int status;
626 int *remote_fd;
627 pthread_t th;
628 pthread_attr_t th_attr;
630 if (us_open_socket () != 0)
631 pthread_exit ((void *) 1);
633 while (loop != 0)
634 {
635 DEBUG ("unixsock plugin: Calling accept..");
636 status = accept (sock_fd, NULL, NULL);
637 if (status < 0)
638 {
639 char errbuf[1024];
641 if (errno == EINTR)
642 continue;
644 ERROR ("unixsock plugin: accept failed: %s",
645 sstrerror (errno, errbuf, sizeof (errbuf)));
646 close (sock_fd);
647 sock_fd = -1;
648 pthread_exit ((void *) 1);
649 }
651 remote_fd = (int *) malloc (sizeof (int));
652 if (remote_fd == NULL)
653 {
654 char errbuf[1024];
655 WARNING ("unixsock plugin: malloc failed: %s",
656 sstrerror (errno, errbuf, sizeof (errbuf)));
657 close (status);
658 continue;
659 }
660 *remote_fd = status;
662 DEBUG ("Spawning child to handle connection on fd #%i", *remote_fd);
664 pthread_attr_init (&th_attr);
665 pthread_attr_setdetachstate (&th_attr, PTHREAD_CREATE_DETACHED);
667 status = pthread_create (&th, &th_attr, us_handle_client, (void *) remote_fd);
668 if (status != 0)
669 {
670 char errbuf[1024];
671 WARNING ("unixsock plugin: pthread_create failed: %s",
672 sstrerror (errno, errbuf, sizeof (errbuf)));
673 close (*remote_fd);
674 free (remote_fd);
675 continue;
676 }
677 } /* while (loop) */
679 close (sock_fd);
680 sock_fd = -1;
682 status = unlink ((sock_file != NULL) ? sock_file : US_DEFAULT_PATH);
683 if (status != 0)
684 {
685 char errbuf[1024];
686 NOTICE ("unixsock plugin: unlink (%s) failed: %s",
687 (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
688 sstrerror (errno, errbuf, sizeof (errbuf)));
689 }
691 return ((void *) 0);
692 } /* void *us_server_thread */
694 static int us_config (const char *key, const char *val)
695 {
696 if (strcasecmp (key, "SocketFile") == 0)
697 {
698 sfree (sock_file);
699 sock_file = strdup (val);
700 }
701 else if (strcasecmp (key, "SocketGroup") == 0)
702 {
703 sfree (sock_group);
704 sock_group = strdup (val);
705 }
706 else if (strcasecmp (key, "SocketPerms") == 0)
707 {
708 sock_perms = (int) strtol (val, NULL, 8);
709 }
710 else
711 {
712 return (-1);
713 }
715 return (0);
716 } /* int us_config */
718 static int us_init (void)
719 {
720 int status;
722 loop = 1;
724 status = pthread_create (&listen_thread, NULL, us_server_thread, NULL);
725 if (status != 0)
726 {
727 char errbuf[1024];
728 ERROR ("unixsock plugin: pthread_create failed: %s",
729 sstrerror (errno, errbuf, sizeof (errbuf)));
730 return (-1);
731 }
733 return (0);
734 } /* int us_init */
736 static int us_shutdown (void)
737 {
738 void *ret;
740 loop = 0;
742 if (listen_thread != (pthread_t) 0)
743 {
744 pthread_kill (listen_thread, SIGTERM);
745 pthread_join (listen_thread, &ret);
746 listen_thread = (pthread_t) 0;
747 }
749 plugin_unregister_init ("unixsock");
750 plugin_unregister_write ("unixsock");
751 plugin_unregister_shutdown ("unixsock");
753 return (0);
754 } /* int us_shutdown */
756 static int us_write (const data_set_t *ds, const value_list_t *vl)
757 {
758 cache_update (ds, vl);
759 cache_flush (2 * interval_g);
761 return (0);
762 }
764 void module_register (void)
765 {
766 plugin_register_config ("unixsock", us_config,
767 config_keys, config_keys_num);
768 plugin_register_init ("unixsock", us_init);
769 plugin_register_write ("unixsock", us_write);
770 plugin_register_shutdown ("unixsock", us_shutdown);
771 } /* void module_register (void) */
773 /* vim: set sw=4 ts=4 sts=4 tw=78 : */