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