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