Merge pull request #1844 from rubenk/sigrok
[collectd.git] / src / pinba.c
1 /**
2  * collectd - src/pinba.c (based on code from pinba_engine 0.0.5)
3  * Copyright (c) 2007-2009  Antony Dovgal
4  * Copyright (C) 2010       Phoenix Kayo
5  * Copyright (C) 2010       Florian Forster
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; only version 2 of the License is applicable.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  *
20  * Authors:
21  *   Antony Dovgal <tony at daylessday.org>
22  *   Phoenix Kayo <kayo.k11.4 at gmail.com>
23  *   Florian Forster <octo at collectd.org>
24  **/
25
26 #include "collectd.h"
27
28 #include "common.h"
29 #include "plugin.h"
30 #include "configfile.h"
31
32 #include <netdb.h>
33 #include <poll.h>
34
35 #include "pinba.pb-c.h"
36
37 /* AIX doesn't have MSG_DONTWAIT */
38 #ifndef MSG_DONTWAIT
39 #  define MSG_DONTWAIT MSG_NONBLOCK
40 #endif
41
42 /*
43  * Defines
44  */
45 #ifndef PINBA_UDP_BUFFER_SIZE
46 # define PINBA_UDP_BUFFER_SIZE 65536
47 #endif
48
49 #ifndef PINBA_DEFAULT_NODE
50 # define PINBA_DEFAULT_NODE "::0"
51 #endif
52
53 #ifndef PINBA_DEFAULT_SERVICE
54 # define PINBA_DEFAULT_SERVICE "30002"
55 #endif
56
57 #ifndef PINBA_MAX_SOCKETS
58 # define PINBA_MAX_SOCKETS 16
59 #endif
60
61 /*
62  * Private data structures
63  */
64 /* {{{ */
65 struct pinba_socket_s
66 {
67   struct pollfd fd[PINBA_MAX_SOCKETS];
68   nfds_t fd_num;
69 };
70 typedef struct pinba_socket_s pinba_socket_t;
71
72 /* Fixed point counter value. n is the decimal part multiplied by 10^9. */
73 struct float_counter_s
74 {
75   uint64_t i;
76   uint64_t n; /* nanos */
77 };
78 typedef struct float_counter_s float_counter_t;
79
80 struct pinba_statnode_s
81 {
82   /* collector name, used as plugin instance */
83   char *name;
84
85   /* query data */
86   char *host;
87   char *server;
88   char *script;
89
90   derive_t req_count;
91
92   float_counter_t req_time;
93   float_counter_t ru_utime;
94   float_counter_t ru_stime;
95
96   derive_t doc_size;
97   gauge_t mem_peak;
98 };
99 typedef struct pinba_statnode_s pinba_statnode_t;
100 /* }}} */
101
102 /*
103  * Module global variables
104  */
105 /* {{{ */
106 static pinba_statnode_t *stat_nodes = NULL;
107 static unsigned int stat_nodes_num = 0;
108 static pthread_mutex_t stat_nodes_lock;
109
110 static char *conf_node = NULL;
111 static char *conf_service = NULL;
112
113 static _Bool collector_thread_running = 0;
114 static _Bool collector_thread_do_shutdown = 0;
115 static pthread_t collector_thread_id;
116 /* }}} */
117
118 /*
119  * Functions
120  */
121 static void float_counter_add (float_counter_t *fc, float val) /* {{{ */
122 {
123   uint64_t tmp;
124
125   if (val < 0.0)
126     return;
127
128   tmp = (uint64_t) val;
129   val -= (double) tmp;
130
131   fc->i += tmp;
132   fc->n += (uint64_t) ((val * 1000000000.0) + .5);
133
134   if (fc->n >= 1000000000)
135   {
136     fc->i += 1;
137     fc->n -= 1000000000;
138     assert (fc->n < 1000000000);
139   }
140 } /* }}} void float_counter_add */
141
142 static derive_t float_counter_get (const float_counter_t *fc, /* {{{ */
143     uint64_t factor)
144 {
145   derive_t ret;
146
147   ret = (derive_t) (fc->i * factor);
148   ret += (derive_t) (fc->n / (1000000000 / factor));
149
150   return (ret);
151 } /* }}} derive_t float_counter_get */
152
153 static void strset (char **str, const char *new) /* {{{ */
154 {
155   char *tmp;
156
157   if (!str || !new)
158     return;
159
160   tmp = strdup (new);
161   if (tmp == NULL)
162     return;
163
164   sfree (*str);
165   *str = tmp;
166 } /* }}} void strset */
167
168 static void service_statnode_add(const char *name, /* {{{ */
169     const char *host,
170     const char *server,
171     const char *script)
172 {
173   pinba_statnode_t *node;
174
175   node = realloc (stat_nodes,
176       sizeof (*stat_nodes) * (stat_nodes_num + 1));
177   if (node == NULL)
178   {
179     ERROR ("pinba plugin: realloc failed");
180     return;
181   }
182   stat_nodes = node;
183
184   node = stat_nodes + stat_nodes_num;
185   memset (node, 0, sizeof (*node));
186
187   /* reset strings */
188   node->name   = NULL;
189   node->host   = NULL;
190   node->server = NULL;
191   node->script = NULL;
192
193   node->mem_peak = NAN;
194
195   /* fill query data */
196   strset (&node->name, name);
197   strset (&node->host, host);
198   strset (&node->server, server);
199   strset (&node->script, script);
200
201   /* increment counter */
202   stat_nodes_num++;
203 } /* }}} void service_statnode_add */
204
205 /* Copy the data from the global "stat_nodes" list into the buffer pointed to
206  * by "res", doing the derivation in the process. Returns the next index or
207  * zero if the end of the list has been reached. */
208 static unsigned int service_statnode_collect (pinba_statnode_t *res, /* {{{ */
209     unsigned int index)
210 {
211   pinba_statnode_t *node;
212
213   if (stat_nodes_num == 0)
214     return 0;
215
216   /* begin collecting */
217   if (index == 0)
218     pthread_mutex_lock (&stat_nodes_lock);
219
220   /* end collecting */
221   if (index >= stat_nodes_num)
222   {
223     pthread_mutex_unlock (&stat_nodes_lock);
224     return 0;
225   }
226
227   node = stat_nodes + index;
228   memcpy (res, node, sizeof (*res));
229
230   /* reset node */
231   node->mem_peak = NAN;
232
233   return (index + 1);
234 } /* }}} unsigned int service_statnode_collect */
235
236 static void service_statnode_process (pinba_statnode_t *node, /* {{{ */
237     Pinba__Request* request)
238 {
239   node->req_count++;
240
241   float_counter_add (&node->req_time, request->request_time);
242   float_counter_add (&node->ru_utime, request->ru_utime);
243   float_counter_add (&node->ru_stime, request->ru_stime);
244
245   node->doc_size += request->document_size;
246
247   if (isnan (node->mem_peak)
248       || (node->mem_peak < ((gauge_t) request->memory_peak)))
249     node->mem_peak = (gauge_t) request->memory_peak;
250
251 } /* }}} void service_statnode_process */
252
253 static void service_process_request (Pinba__Request *request) /* {{{ */
254 {
255   pthread_mutex_lock (&stat_nodes_lock);
256
257   for (unsigned int i = 0; i < stat_nodes_num; i++)
258   {
259     if ((stat_nodes[i].host != NULL)
260         && (strcmp (request->hostname, stat_nodes[i].host) != 0))
261       continue;
262
263     if ((stat_nodes[i].server != NULL)
264       && (strcmp (request->server_name, stat_nodes[i].server) != 0))
265       continue;
266
267     if ((stat_nodes[i].script != NULL)
268       && (strcmp (request->script_name, stat_nodes[i].script) != 0))
269       continue;
270
271     service_statnode_process(&stat_nodes[i], request);
272   }
273
274   pthread_mutex_unlock(&stat_nodes_lock);
275 } /* }}} void service_process_request */
276
277 static int pb_del_socket (pinba_socket_t *s, /* {{{ */
278     nfds_t index)
279 {
280   if (index >= s->fd_num)
281     return (EINVAL);
282
283   close (s->fd[index].fd);
284   s->fd[index].fd = -1;
285
286   /* When deleting the last element in the list, no memmove is necessary. */
287   if (index < (s->fd_num - 1))
288   {
289     memmove (&s->fd[index], &s->fd[index + 1],
290         sizeof (s->fd[0]) * (s->fd_num - (index + 1)));
291   }
292
293   s->fd_num--;
294   return (0);
295 } /* }}} int pb_del_socket */
296
297 static int pb_add_socket (pinba_socket_t *s, /* {{{ */
298     const struct addrinfo *ai)
299 {
300   int fd;
301   int tmp;
302   int status;
303
304   if (s->fd_num == PINBA_MAX_SOCKETS)
305   {
306     WARNING ("pinba plugin: Sorry, you have hit the built-in limit of "
307         "%i sockets. Please complain to the collectd developers so we can "
308         "raise the limit.", PINBA_MAX_SOCKETS);
309     return (-1);
310   }
311
312   fd = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol);
313   if (fd < 0)
314   {
315     char errbuf[1024];
316     ERROR ("pinba plugin: socket(2) failed: %s",
317         sstrerror (errno, errbuf, sizeof (errbuf)));
318     return (0);
319   }
320
321   tmp = 1;
322   status = setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof (tmp));
323   if (status != 0)
324   {
325     char errbuf[1024];
326     WARNING ("pinba plugin: setsockopt(SO_REUSEADDR) failed: %s",
327         sstrerror (errno, errbuf, sizeof (errbuf)));
328   }
329
330   status = bind (fd, ai->ai_addr, ai->ai_addrlen);
331   if (status != 0)
332   {
333     char errbuf[1024];
334     ERROR ("pinba plugin: bind(2) failed: %s",
335         sstrerror (errno, errbuf, sizeof (errbuf)));
336     close (fd);
337     return (0);
338   }
339
340   s->fd[s->fd_num].fd = fd;
341   s->fd[s->fd_num].events = POLLIN | POLLPRI;
342   s->fd[s->fd_num].revents = 0;
343   s->fd_num++;
344
345   return (0);
346 } /* }}} int pb_add_socket */
347
348 static pinba_socket_t *pinba_socket_open (const char *node, /* {{{ */
349     const char *service)
350 {
351   pinba_socket_t *s;
352   struct addrinfo *ai_list;
353   int status;
354
355   if (node == NULL)
356     node = PINBA_DEFAULT_NODE;
357
358   if (service == NULL)
359     service = PINBA_DEFAULT_SERVICE;
360
361   struct addrinfo  ai_hints = {
362     .ai_family = AF_UNSPEC,
363     .ai_flags = AI_PASSIVE,
364     .ai_socktype = SOCK_DGRAM
365   };
366
367   status = getaddrinfo (node, service,
368       &ai_hints, &ai_list);
369   if (status != 0)
370   {
371     ERROR ("pinba plugin: getaddrinfo(3) failed: %s",
372         gai_strerror (status));
373     return (NULL);
374   }
375   assert (ai_list != NULL);
376
377   s = calloc (1, sizeof (*s));
378   if (s == NULL)
379   {
380     freeaddrinfo (ai_list);
381     ERROR ("pinba plugin: calloc failed.");
382     return (NULL);
383   }
384
385   for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
386   {
387     status = pb_add_socket (s, ai_ptr);
388     if (status != 0)
389       break;
390   } /* for (ai_list) */
391
392   freeaddrinfo (ai_list);
393
394   if (s->fd_num < 1)
395   {
396     WARNING ("pinba plugin: Unable to open socket for address %s.", node);
397     sfree (s);
398     s = NULL;
399   }
400
401   return (s);
402 } /* }}} pinba_socket_open */
403
404 static void pinba_socket_free (pinba_socket_t *socket) /* {{{ */
405 {
406   if (!socket)
407     return;
408
409   for (nfds_t i = 0; i < socket->fd_num; i++)
410   {
411     if (socket->fd[i].fd < 0)
412       continue;
413     close (socket->fd[i].fd);
414     socket->fd[i].fd = -1;
415   }
416
417   sfree(socket);
418 } /* }}} void pinba_socket_free */
419
420 static int pinba_process_stats_packet (const uint8_t *buffer, /* {{{ */
421     size_t buffer_size)
422 {
423   Pinba__Request *request;
424
425   request = pinba__request__unpack (NULL, buffer_size, buffer);
426
427   if (!request)
428     return (-1);
429
430   service_process_request(request);
431   pinba__request__free_unpacked (request, NULL);
432
433   return (0);
434 } /* }}} int pinba_process_stats_packet */
435
436 static int pinba_udp_read_callback_fn (int sock) /* {{{ */
437 {
438   uint8_t buffer[PINBA_UDP_BUFFER_SIZE];
439   size_t buffer_size;
440   int status;
441
442   while (42)
443   {
444     buffer_size = sizeof (buffer);
445     status = recvfrom (sock, buffer, buffer_size - 1, MSG_DONTWAIT, /* from = */ NULL, /* from len = */ 0);
446     if (status < 0)
447     {
448       char errbuf[1024];
449
450       if ((errno == EINTR)
451 #ifdef EWOULDBLOCK
452           || (errno == EWOULDBLOCK)
453 #endif
454           || (errno == EAGAIN))
455       {
456         continue;
457       }
458
459       WARNING("pinba plugin: recvfrom(2) failed: %s",
460           sstrerror (errno, errbuf, sizeof (errbuf)));
461       return (-1);
462     }
463     else if (status == 0)
464     {
465       DEBUG ("pinba plugin: recvfrom(2) returned unexpected status zero.");
466       return (-1);
467     }
468     else /* if (status > 0) */
469     {
470       assert (((size_t) status) < buffer_size);
471       buffer_size = (size_t) status;
472       buffer[buffer_size] = 0;
473
474       status = pinba_process_stats_packet (buffer, buffer_size);
475       if (status != 0)
476         DEBUG("pinba plugin: Parsing packet failed.");
477       return (status);
478     }
479   } /* while (42) */
480
481   /* not reached */
482   assert (23 == 42);
483   return (-1);
484 } /* }}} void pinba_udp_read_callback_fn */
485
486 static int receive_loop (void) /* {{{ */
487 {
488   pinba_socket_t *s;
489
490   s = pinba_socket_open (conf_node, conf_service);
491   if (s == NULL)
492   {
493     ERROR ("pinba plugin: Collector thread is exiting prematurely.");
494     return (-1);
495   }
496
497   while (!collector_thread_do_shutdown)
498   {
499     int status;
500
501     if (s->fd_num < 1)
502       break;
503
504     status = poll (s->fd, s->fd_num, /* timeout = */ 1000);
505     if (status == 0) /* timeout */
506     {
507       continue;
508     }
509     else if (status < 0)
510     {
511       char errbuf[1024];
512
513       if ((errno == EINTR) || (errno == EAGAIN))
514         continue;
515
516       ERROR ("pinba plugin: poll(2) failed: %s",
517           sstrerror (errno, errbuf, sizeof (errbuf)));
518       pinba_socket_free (s);
519       return (-1);
520     }
521
522     for (nfds_t i = 0; i < s->fd_num; i++)
523     {
524       if (s->fd[i].revents & (POLLERR | POLLHUP | POLLNVAL))
525       {
526         pb_del_socket (s, i);
527         i--;
528       }
529       else if (s->fd[i].revents & (POLLIN | POLLPRI))
530       {
531         pinba_udp_read_callback_fn (s->fd[i].fd);
532       }
533     } /* for (s->fd) */
534   } /* while (!collector_thread_do_shutdown) */
535
536   pinba_socket_free (s);
537   s = NULL;
538
539   return (0);
540 } /* }}} int receive_loop */
541
542 static void *collector_thread (void *arg) /* {{{ */
543 {
544   receive_loop ();
545
546   memset (&collector_thread_id, 0, sizeof (collector_thread_id));
547   collector_thread_running = 0;
548   pthread_exit (NULL);
549   return (NULL);
550 } /* }}} void *collector_thread */
551
552 /*
553  * Plugin declaration section
554  */
555 static int pinba_config_view (const oconfig_item_t *ci) /* {{{ */
556 {
557   char *name   = NULL;
558   char *host   = NULL;
559   char *server = NULL;
560   char *script = NULL;
561   int status;
562
563   status = cf_util_get_string (ci, &name);
564   if (status != 0)
565     return (status);
566
567   for (int i = 0; i < ci->children_num; i++)
568   {
569     oconfig_item_t *child = ci->children + i;
570
571     if (strcasecmp ("Host", child->key) == 0)
572       status = cf_util_get_string (child, &host);
573     else if (strcasecmp ("Server", child->key) == 0)
574       status = cf_util_get_string (child, &server);
575     else if (strcasecmp ("Script", child->key) == 0)
576       status = cf_util_get_string (child, &script);
577     else
578     {
579       WARNING ("pinba plugin: Unknown config option: %s", child->key);
580       status = -1;
581     }
582
583     if (status != 0)
584       break;
585   }
586
587   if (status == 0)
588     service_statnode_add (name, host, server, script);
589
590   sfree (name);
591   sfree (host);
592   sfree (server);
593   sfree (script);
594
595   return (status);
596 } /* }}} int pinba_config_view */
597
598 static int plugin_config (oconfig_item_t *ci) /* {{{ */
599 {
600   /* The lock should not be necessary in the config callback, but let's be
601    * sure.. */
602   pthread_mutex_lock (&stat_nodes_lock);
603
604   for (int i = 0; i < ci->children_num; i++)
605   {
606     oconfig_item_t *child = ci->children + i;
607
608     if (strcasecmp ("Address", child->key) == 0)
609       cf_util_get_string (child, &conf_node);
610     else if (strcasecmp ("Port", child->key) == 0)
611       cf_util_get_service (child, &conf_service);
612     else if (strcasecmp ("View", child->key) == 0)
613       pinba_config_view (child);
614     else
615       WARNING ("pinba plugin: Unknown config option: %s", child->key);
616   }
617
618   pthread_mutex_unlock(&stat_nodes_lock);
619
620   return (0);
621 } /* }}} int pinba_config */
622
623 static int plugin_init (void) /* {{{ */
624 {
625   int status;
626
627   if (stat_nodes == NULL)
628   {
629     /* Collect the "total" data by default. */
630     service_statnode_add ("total",
631         /* host   = */ NULL,
632         /* server = */ NULL,
633         /* script = */ NULL);
634   }
635
636   if (collector_thread_running)
637     return (0);
638
639   status = plugin_thread_create (&collector_thread_id,
640       /* attrs = */ NULL,
641       collector_thread,
642       /* args = */ NULL);
643   if (status != 0)
644   {
645     char errbuf[1024];
646     ERROR ("pinba plugin: pthread_create(3) failed: %s",
647         sstrerror (errno, errbuf, sizeof (errbuf)));
648     return (-1);
649   }
650   collector_thread_running = 1;
651
652   return (0);
653 } /* }}} */
654
655 static int plugin_shutdown (void) /* {{{ */
656 {
657   if (collector_thread_running)
658   {
659     int status;
660
661     DEBUG ("pinba plugin: Shutting down collector thread.");
662     collector_thread_do_shutdown = 1;
663
664     status = pthread_join (collector_thread_id, /* retval = */ NULL);
665     if (status != 0)
666     {
667       char errbuf[1024];
668       ERROR ("pinba plugin: pthread_join(3) failed: %s",
669           sstrerror (status, errbuf, sizeof (errbuf)));
670     }
671
672     collector_thread_running = 0;
673     collector_thread_do_shutdown = 0;
674   } /* if (collector_thread_running) */
675
676   return (0);
677 } /* }}} int plugin_shutdown */
678
679 static int plugin_submit (const pinba_statnode_t *res) /* {{{ */
680 {
681   value_t value;
682   value_list_t vl = VALUE_LIST_INIT;
683
684   vl.values = &value;
685   vl.values_len = 1;
686   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
687   sstrncpy (vl.plugin, "pinba", sizeof (vl.plugin));
688   sstrncpy (vl.plugin_instance, res->name, sizeof (vl.plugin_instance));
689
690   value.derive = res->req_count;
691   sstrncpy (vl.type, "total_requests", sizeof (vl.type));
692   plugin_dispatch_values (&vl);
693
694   value.derive = float_counter_get (&res->req_time, /* factor = */ 1000);
695   sstrncpy (vl.type, "total_time_in_ms", sizeof (vl.type));
696   plugin_dispatch_values (&vl);
697
698   value.derive = res->doc_size;
699   sstrncpy (vl.type, "total_bytes", sizeof (vl.type));
700   plugin_dispatch_values (&vl);
701
702   value.derive = float_counter_get (&res->ru_utime, /* factor = */ 100);
703   sstrncpy (vl.type, "cpu", sizeof (vl.type));
704   sstrncpy (vl.type_instance, "user", sizeof (vl.type_instance));
705   plugin_dispatch_values (&vl);
706
707   value.derive = float_counter_get (&res->ru_stime, /* factor = */ 100);
708   sstrncpy (vl.type, "cpu", sizeof (vl.type));
709   sstrncpy (vl.type_instance, "system", sizeof (vl.type_instance));
710   plugin_dispatch_values (&vl);
711
712   value.gauge = res->mem_peak;
713   sstrncpy (vl.type, "memory", sizeof (vl.type));
714   sstrncpy (vl.type_instance, "peak", sizeof (vl.type_instance));
715   plugin_dispatch_values (&vl);
716
717   return (0);
718 } /* }}} int plugin_submit */
719
720 static int plugin_read (void) /* {{{ */
721 {
722   unsigned int i=0;
723   pinba_statnode_t data;
724
725   while ((i = service_statnode_collect (&data, i)) != 0)
726   {
727     plugin_submit (&data);
728   }
729
730   return 0;
731 } /* }}} int plugin_read */
732
733 void module_register (void) /* {{{ */
734 {
735   plugin_register_complex_config ("pinba", plugin_config);
736   plugin_register_init ("pinba", plugin_init);
737   plugin_register_read ("pinba", plugin_read);
738   plugin_register_shutdown ("pinba", plugin_shutdown);
739 } /* }}} void module_register */
740
741 /* vim: set sw=2 sts=2 et fdm=marker : */