Replace all syslog-calls with one of the new logging-macros.
[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
27 /* Folks without pthread will need to disable this plugin. */
28 #include <pthread.h>
29
30 #include <sys/socket.h>
31 #include <sys/un.h>
32 #include <sys/poll.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 PREFIX"/var/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 /* 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 = (pthread_t) 0;
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 *hostname,
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/%s",
113                                         hostname, plugin, type);
114                 else
115                         status = snprintf (ret, ret_len, "%s/%s/%s-%s",
116                                         hostname, 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/%s",
122                                         hostname, plugin, plugin_instance, type);
123                 else
124                         status = snprintf (ret, ret_len, "%s/%s-%s/%s-%s",
125                                         hostname, plugin, plugin_instance, 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         DEBUG ("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                 ERROR ("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                 ERROR ("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                 ERROR ("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->host, vl->plugin, vl->plugin_instance,
175                                 ds->type, vl->type_instance) != 0)
176         {
177                 pthread_mutex_unlock (&cache_lock);
178                 ERROR ("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         vc->ds = ds;
205
206         vc->next = cache_head;
207         cache_head = vc;
208
209         vc->time = vl->time;
210         if (vc->time < cache_oldest)
211                 cache_oldest = vc->time;
212
213         pthread_mutex_unlock (&cache_lock);
214         return (0);
215 } /* int cache_insert */
216
217 static int cache_update (const data_set_t *ds, const value_list_t *vl)
218 {
219         char name[4*DATA_MAX_NAME_LEN];;
220         value_cache_t *vc;
221         int i;
222
223         if (cache_alloc_name (name, sizeof (name),
224                                 vl->host,
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                         vc->counter[i] = vl->values[i].counter;
267                 }
268                 else if (ds->ds[i].type == DS_TYPE_GAUGE)
269                 {
270                         vc->gauge[i] = vl->values[i].gauge;
271                         vc->counter[i] = 0;
272                 }
273                 else
274                 {
275                         vc->gauge[i] = NAN;
276                         vc->counter[i] = 0;
277                 }
278
279                 if (isnan (vc->gauge[i])
280                                 || (!isnan (ds->ds[i].min) && (vc->gauge[i] < ds->ds[i].min))
281                                 || (!isnan (ds->ds[i].max) && (vc->gauge[i] > ds->ds[i].max)))
282                         vc->gauge[i] = NAN;
283         } /* for i = 0 .. ds->ds_num */
284
285         vc->ds = ds;
286         vc->time = vl->time;
287
288         if (vc->time < cache_oldest)
289                 cache_oldest = vc->time;
290
291         pthread_mutex_unlock (&cache_lock);
292         return (0);
293 } /* int cache_update */
294
295 static void cache_flush (int max_age)
296 {
297         value_cache_t *this;
298         value_cache_t *prev;
299         time_t now;
300
301         pthread_mutex_lock (&cache_lock);
302
303         now = time (NULL);
304
305         if ((now - cache_oldest) <= max_age)
306         {
307                 pthread_mutex_unlock (&cache_lock);
308                 return;
309         }
310         
311         cache_oldest = now;
312
313         prev = NULL;
314         this = cache_head;
315
316         while (this != NULL)
317         {
318                 if ((now - this->time) <= max_age)
319                 {
320                         if (this->time < cache_oldest)
321                                 cache_oldest = this->time;
322
323                         prev = this;
324                         this = this->next;
325                         continue;
326                 }
327
328                 if (prev == NULL)
329                         cache_head = this->next;
330                 else
331                         prev->next = this->next;
332
333                 free (this->gauge);
334                 free (this->counter);
335                 free (this);
336
337                 if (prev == NULL)
338                         this = cache_head;
339                 else
340                         this = prev->next;
341         } /* while (this != NULL) */
342
343         pthread_mutex_unlock (&cache_lock);
344 } /* int cache_flush */
345
346 static int us_open_socket (void)
347 {
348         struct sockaddr_un sa;
349         int status;
350
351         sock_fd = socket (PF_UNIX, SOCK_STREAM, 0);
352         if (sock_fd < 0)
353         {
354                 ERROR ("unixsock plugin: socket failed: %s",
355                                 strerror (errno));
356                 return (-1);
357         }
358
359         memset (&sa, '\0', sizeof (sa));
360         sa.sun_family = AF_UNIX;
361         strncpy (sa.sun_path, (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
362                         sizeof (sa.sun_path) - 1);
363         /* unlink (sa.sun_path); */
364
365         status = bind (sock_fd, (struct sockaddr *) &sa, sizeof (sa));
366         if (status != 0)
367         {
368                 DEBUG ("bind failed: %s; sa.sun_path = %s",
369                                 strerror (errno), sa.sun_path);
370                 ERROR ("unixsock plugin: bind failed: %s",
371                                 strerror (errno));
372                 close (sock_fd);
373                 sock_fd = -1;
374                 return (-1);
375         }
376
377         status = listen (sock_fd, 8);
378         if (status != 0)
379         {
380                 ERROR ("unixsock plugin: listen failed: %s",
381                                 strerror (errno));
382                 close (sock_fd);
383                 sock_fd = -1;
384                 return (-1);
385         }
386
387         do
388         {
389                 char *grpname;
390                 struct group *g;
391                 struct group sg;
392                 char grbuf[2048];
393
394                 grpname = (sock_group != NULL) ? sock_group : COLLECTD_GRP_NAME;
395                 g = NULL;
396
397                 status = getgrnam_r (grpname, &sg, grbuf, sizeof (grbuf), &g);
398                 if (status != 0)
399                 {
400                         WARNING ("unixsock plugin: getgrnam_r (%s) failed: %s",
401                                         grpname, strerror (status));
402                         break;
403                 }
404                 if (g == NULL)
405                 {
406                         WARNING ("unixsock plugin: No such group: `%s'",
407                                         grpname);
408                         break;
409                 }
410
411                 if (chown ((sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
412                                         (uid_t) -1, g->gr_gid) != 0)
413                 {
414                         WARNING ("unixsock plugin: chown (%s, -1, %i) failed: %s",
415                                         (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
416                                         (int) g->gr_gid,
417                                         strerror (errno));
418                 }
419         } while (0);
420
421         return (0);
422 } /* int us_open_socket */
423
424 static int us_handle_getval (FILE *fh, char **fields, int fields_num)
425 {
426         char *hostname = fields[1];
427         char *plugin;
428         char *plugin_instance;
429         char *type;
430         char *type_instance;
431         char  name[4*DATA_MAX_NAME_LEN];
432         value_cache_t *vc;
433         int   status;
434         int   i;
435
436         if (fields_num != 2)
437                 return (-1);
438
439         plugin = strchr (hostname, '/');
440         if (plugin == NULL)
441                 return (-1);
442         *plugin = '\0'; plugin++;
443
444         type = strchr (plugin, '/');
445         if (type == NULL)
446                 return (-1);
447         *type = '\0'; type++;
448
449         plugin_instance = strchr (plugin, '-');
450         if (plugin_instance != NULL)
451         {
452                 *plugin_instance = '\0';
453                 plugin_instance++;
454         }
455
456         type_instance = strchr (type, '-');
457         if (type_instance != NULL)
458         {
459                 *type_instance = '\0';
460                 type_instance++;
461         }
462
463         status = cache_alloc_name (name, sizeof (name),
464                         hostname, plugin, plugin_instance, type, type_instance);
465         if (status != 0)
466                 return (-1);
467
468         pthread_mutex_lock (&cache_lock);
469
470         DEBUG ("vc = cache_search (%s)", name);
471         vc = cache_search (name);
472
473         if (vc == NULL)
474         {
475                 DEBUG ("Did not find cache entry.");
476                 fprintf (fh, "-1 No such value");
477         }
478         else
479         {
480                 DEBUG ("Found cache entry.");
481                 fprintf (fh, "%i", vc->values_num);
482                 for (i = 0; i < vc->values_num; i++)
483                 {
484                         fprintf (fh, " %s=", vc->ds->ds[i].name);
485                         if (isnan (vc->gauge[i]))
486                                 fprintf (fh, "NaN");
487                         else
488                                 fprintf (fh, "%12e", vc->gauge[i]);
489                 }
490         }
491
492         /* Free the mutex as soon as possible and definitely before flushing */
493         pthread_mutex_unlock (&cache_lock);
494
495         fprintf (fh, "\n");
496         fflush (fh);
497
498         return (0);
499 } /* int us_handle_getval */
500
501 static void *us_handle_client (void *arg)
502 {
503         int fd;
504         FILE *fh;
505         char buffer[1024];
506         char *fields[128];
507         int   fields_num;
508
509         fd = *((int *) arg);
510         free (arg);
511         arg = NULL;
512
513         DEBUG ("Reading from fd #%i", fd);
514
515         fh = fdopen (fd, "r+");
516         if (fh == NULL)
517         {
518                 ERROR ("unixsock plugin: fdopen failed: %s",
519                                 strerror (errno));
520                 close (fd);
521                 pthread_exit ((void *) 1);
522         }
523
524         while (fgets (buffer, sizeof (buffer), fh) != NULL)
525         {
526                 int len;
527
528                 len = strlen (buffer);
529                 while ((len > 0)
530                                 && ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
531                         buffer[--len] = '\0';
532
533                 if (len == 0)
534                         continue;
535
536                 DEBUG ("fgets -> buffer = %s; len = %i;", buffer, len);
537
538                 fields_num = strsplit (buffer, fields,
539                                 sizeof (fields) / sizeof (fields[0]));
540
541                 if (fields_num < 1)
542                 {
543                         close (fd);
544                         break;
545                 }
546
547                 if (strcasecmp (fields[0], "getval") == 0)
548                 {
549                         us_handle_getval (fh, fields, fields_num);
550                 }
551                 else
552                 {
553                         fprintf (fh, "Unknown command: %s\n", fields[0]);
554                         fflush (fh);
555                 }
556         } /* while (fgets) */
557
558         DEBUG ("Exiting..");
559         close (fd);
560
561         pthread_exit ((void *) 0);
562 } /* void *us_handle_client */
563
564 static void *us_server_thread (void *arg)
565 {
566         int  status;
567         int *remote_fd;
568         pthread_t th;
569         pthread_attr_t th_attr;
570
571         if (us_open_socket () != 0)
572                 pthread_exit ((void *) 1);
573
574         while (42)
575         {
576                 DEBUG ("Calling accept..");
577                 status = accept (sock_fd, NULL, NULL);
578                 if (status < 0)
579                 {
580                         if (errno == EINTR)
581                                 continue;
582
583                         ERROR ("unixsock plugin: accept failed: %s",
584                                         strerror (errno));
585                         close (sock_fd);
586                         sock_fd = -1;
587                         pthread_exit ((void *) 1);
588                 }
589
590                 remote_fd = (int *) malloc (sizeof (int));
591                 if (remote_fd == NULL)
592                 {
593                         WARNING ("unixsock plugin: malloc failed: %s",
594                                         strerror (errno));
595                         close (status);
596                         continue;
597                 }
598                 *remote_fd = status;
599
600                 DEBUG ("Spawning child to handle connection on fd #%i", *remote_fd);
601
602                 pthread_attr_init (&th_attr);
603                 pthread_attr_setdetachstate (&th_attr, PTHREAD_CREATE_DETACHED);
604
605                 status = pthread_create (&th, &th_attr, us_handle_client, (void *) remote_fd);
606                 if (status != 0)
607                 {
608                         WARNING ("unixsock plugin: pthread_create failed: %s",
609                                         strerror (status));
610                         close (*remote_fd);
611                         free (remote_fd);
612                         continue;
613                 }
614         } /* while (42) */
615
616         return ((void *) 0);
617 } /* void *us_server_thread */
618
619 static int us_config (const char *key, const char *val)
620 {
621         if (strcasecmp (key, "SocketFile") == 0)
622         {
623                 sfree (sock_file);
624                 sock_file = strdup (val);
625         }
626         else if (strcasecmp (key, "SocketGroup") == 0)
627         {
628                 sfree (sock_group);
629                 sock_group = strdup (val);
630         }
631         else if (strcasecmp (key, "SocketPerms") == 0)
632         {
633                 sock_perms = (int) strtol (val, NULL, 8);
634         }
635         else
636         {
637                 return (-1);
638         }
639
640         return (0);
641 } /* int us_config */
642
643 static int us_init (void)
644 {
645         int status;
646
647         status = pthread_create (&listen_thread, NULL, us_server_thread, NULL);
648         if (status != 0)
649         {
650                 ERROR ("unixsock plugin: pthread_create failed: %s",
651                                 strerror (status));
652                 return (-1);
653         }
654
655         return (0);
656 } /* int us_init */
657
658 static int us_shutdown (void)
659 {
660         void *ret;
661
662         if (listen_thread != (pthread_t) 0)
663         {
664                 pthread_kill (listen_thread, SIGTERM);
665                 pthread_join (listen_thread, &ret);
666                 listen_thread = (pthread_t) 0;
667         }
668
669         plugin_unregister_init ("unixsock");
670         plugin_unregister_write ("unixsock");
671         plugin_unregister_shutdown ("unixsock");
672
673         return (0);
674 } /* int us_shutdown */
675
676 static int us_write (const data_set_t *ds, const value_list_t *vl)
677 {
678         cache_update (ds, vl);
679         cache_flush (2 * atoi (COLLECTD_STEP));
680
681         return (0);
682 }
683
684 void module_register (void)
685 {
686         plugin_register_config ("unixsock", us_config,
687                         config_keys, config_keys_num);
688         plugin_register_init ("unixsock", us_init);
689         plugin_register_write ("unixsock", us_write);
690         plugin_register_shutdown ("unixsock", us_shutdown);
691 } /* void module_register (void) */
692
693 /* vim: set sw=4 ts=4 sts=4 tw=78 : */