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