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