Merge branch 'collectd-5.4' into collectd-5.5
[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     close (fd);
340     return (0);
341   }
342
343   s->fd[s->fd_num].fd = fd;
344   s->fd[s->fd_num].events = POLLIN | POLLPRI;
345   s->fd[s->fd_num].revents = 0;
346   s->fd_num++;
347
348   return (0);
349 } /* }}} int pb_add_socket */
350
351 static pinba_socket_t *pinba_socket_open (const char *node, /* {{{ */
352     const char *service)
353 {
354   pinba_socket_t *s;
355   struct addrinfo *ai_list;
356   struct addrinfo *ai_ptr;
357   struct addrinfo  ai_hints;
358   int status;
359
360   memset (&ai_hints, 0, sizeof (ai_hints));
361   ai_hints.ai_flags = AI_PASSIVE;
362   ai_hints.ai_family = AF_UNSPEC;
363   ai_hints.ai_socktype = SOCK_DGRAM;
364   ai_hints.ai_addr = NULL;
365   ai_hints.ai_canonname = NULL;
366   ai_hints.ai_next = NULL;
367
368   if (node == NULL)
369     node = PINBA_DEFAULT_NODE;
370
371   if (service == NULL)
372     service = PINBA_DEFAULT_SERVICE;
373
374   ai_list = NULL;
375   status = getaddrinfo (node, service,
376       &ai_hints, &ai_list);
377   if (status != 0)
378   {
379     ERROR ("pinba plugin: getaddrinfo(3) failed: %s",
380         gai_strerror (status));
381     return (NULL);
382   }
383   assert (ai_list != NULL);
384
385   s = malloc (sizeof (*s));
386   if (s == NULL)
387   {
388     freeaddrinfo (ai_list);
389     ERROR ("pinba plugin: malloc failed.");
390     return (NULL);
391   }
392   memset (s, 0, sizeof (*s));
393
394   for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
395   {
396     status = pb_add_socket (s, ai_ptr);
397     if (status != 0)
398       break;
399   } /* for (ai_list) */
400   
401   freeaddrinfo (ai_list);
402
403   if (s->fd_num < 1)
404   {
405     WARNING ("pinba plugin: Unable to open socket for address %s.", node);
406     sfree (s);
407     s = NULL;
408   }
409
410   return (s);
411 } /* }}} pinba_socket_open */
412
413 static void pinba_socket_free (pinba_socket_t *socket) /* {{{ */
414 {
415   nfds_t i;
416
417   if (!socket)
418     return;
419   
420   for (i = 0; i < socket->fd_num; i++)
421   {
422     if (socket->fd[i].fd < 0)
423       continue;
424     close (socket->fd[i].fd);
425     socket->fd[i].fd = -1;
426   }
427   
428   sfree(socket);
429 } /* }}} void pinba_socket_free */
430
431 static int pinba_process_stats_packet (const uint8_t *buffer, /* {{{ */
432     size_t buffer_size)
433 {
434   Pinba__Request *request;  
435   
436   request = pinba__request__unpack (NULL, buffer_size, buffer);
437   
438   if (!request)
439     return (-1);
440
441   service_process_request(request);
442   pinba__request__free_unpacked (request, NULL);
443     
444   return (0);
445 } /* }}} int pinba_process_stats_packet */
446
447 static int pinba_udp_read_callback_fn (int sock) /* {{{ */
448 {
449   uint8_t buffer[PINBA_UDP_BUFFER_SIZE];
450   size_t buffer_size;
451   int status;
452
453   while (42)
454   {
455     buffer_size = sizeof (buffer);
456     status = recvfrom (sock, buffer, buffer_size - 1, MSG_DONTWAIT, /* from = */ NULL, /* from len = */ 0);
457     if (status < 0)
458     {
459       char errbuf[1024];
460
461       if ((errno == EINTR)
462 #ifdef EWOULDBLOCK
463           || (errno == EWOULDBLOCK)
464 #endif
465           || (errno == EAGAIN))
466       {
467         continue;
468       }
469
470       WARNING("pinba plugin: recvfrom(2) failed: %s",
471           sstrerror (errno, errbuf, sizeof (errbuf)));
472       return (-1);
473     }
474     else if (status == 0)
475     {
476       DEBUG ("pinba plugin: recvfrom(2) returned unexpected status zero.");
477       return (-1);
478     }
479     else /* if (status > 0) */
480     {
481       assert (((size_t) status) < buffer_size);
482       buffer_size = (size_t) status;
483       buffer[buffer_size] = 0;
484
485       status = pinba_process_stats_packet (buffer, buffer_size);
486       if (status != 0)
487         DEBUG("pinba plugin: Parsing packet failed.");
488       return (status);
489     }
490   } /* while (42) */
491
492   /* not reached */
493   assert (23 == 42);
494   return (-1);
495 } /* }}} void pinba_udp_read_callback_fn */
496
497 static int receive_loop (void) /* {{{ */
498 {
499   pinba_socket_t *s;
500
501   s = pinba_socket_open (conf_node, conf_service);
502   if (s == NULL)
503   {
504     ERROR ("pinba plugin: Collector thread is exiting prematurely.");
505     return (-1);
506   }
507
508   while (!collector_thread_do_shutdown)
509   {
510     int status;
511     nfds_t i;
512
513     if (s->fd_num < 1)
514       break;
515
516     status = poll (s->fd, s->fd_num, /* timeout = */ 1000);
517     if (status == 0) /* timeout */
518     {
519       continue;
520     }
521     else if (status < 0)
522     {
523       char errbuf[1024];
524
525       if ((errno == EINTR) || (errno == EAGAIN))
526         continue;
527
528       ERROR ("pinba plugin: poll(2) failed: %s",
529           sstrerror (errno, errbuf, sizeof (errbuf)));
530       pinba_socket_free (s);
531       return (-1);
532     }
533
534     for (i = 0; i < s->fd_num; i++)
535     {
536       if (s->fd[i].revents & (POLLERR | POLLHUP | POLLNVAL))
537       {
538         pb_del_socket (s, i);
539         i--;
540       }
541       else if (s->fd[i].revents & (POLLIN | POLLPRI))
542       {
543         pinba_udp_read_callback_fn (s->fd[i].fd);
544       }
545     } /* for (s->fd) */
546   } /* while (!collector_thread_do_shutdown) */
547
548   pinba_socket_free (s);
549   s = NULL;
550
551   return (0);
552 } /* }}} int receive_loop */
553
554 static void *collector_thread (void *arg) /* {{{ */
555 {
556   receive_loop ();
557
558   memset (&collector_thread_id, 0, sizeof (collector_thread_id));
559   collector_thread_running = 0;
560   pthread_exit (NULL);
561   return (NULL);
562 } /* }}} void *collector_thread */
563
564 /*
565  * Plugin declaration section
566  */
567 static int pinba_config_view (const oconfig_item_t *ci) /* {{{ */
568 {
569   char *name   = NULL;
570   char *host   = NULL;
571   char *server = NULL;
572   char *script = NULL;
573   int status;
574   int i;
575
576   status = cf_util_get_string (ci, &name);
577   if (status != 0)
578     return (status);
579
580   for (i = 0; i < ci->children_num; i++)
581   {
582     oconfig_item_t *child = ci->children + i;
583
584     if (strcasecmp ("Host", child->key) == 0)
585       status = cf_util_get_string (child, &host);
586     else if (strcasecmp ("Server", child->key) == 0)
587       status = cf_util_get_string (child, &server);
588     else if (strcasecmp ("Script", child->key) == 0)
589       status = cf_util_get_string (child, &script);
590     else
591     {
592       WARNING ("pinba plugin: Unknown config option: %s", child->key);
593       status = -1;
594     }
595
596     if (status != 0)
597       break;
598   }
599
600   if (status == 0)
601     service_statnode_add (name, host, server, script);
602
603   sfree (name);
604   sfree (host);
605   sfree (server);
606   sfree (script);
607
608   return (status);
609 } /* }}} int pinba_config_view */
610
611 static int plugin_config (oconfig_item_t *ci) /* {{{ */
612 {
613   int i;
614   
615   /* The lock should not be necessary in the config callback, but let's be
616    * sure.. */
617   pthread_mutex_lock (&stat_nodes_lock);
618
619   for (i = 0; i < ci->children_num; i++)
620   {
621     oconfig_item_t *child = ci->children + i;
622
623     if (strcasecmp ("Address", child->key) == 0)
624       cf_util_get_string (child, &conf_node);
625     else if (strcasecmp ("Port", child->key) == 0)
626       cf_util_get_service (child, &conf_service);
627     else if (strcasecmp ("View", child->key) == 0)
628       pinba_config_view (child);
629     else
630       WARNING ("pinba plugin: Unknown config option: %s", child->key);
631   }
632
633   pthread_mutex_unlock(&stat_nodes_lock);
634   
635   return (0);
636 } /* }}} int pinba_config */
637
638 static int plugin_init (void) /* {{{ */
639 {
640   int status;
641
642   if (stat_nodes == NULL)
643   {
644     /* Collect the "total" data by default. */
645     service_statnode_add ("total",
646         /* host   = */ NULL,
647         /* server = */ NULL,
648         /* script = */ NULL);
649   }
650
651   if (collector_thread_running)
652     return (0);
653
654   status = plugin_thread_create (&collector_thread_id,
655       /* attrs = */ NULL,
656       collector_thread,
657       /* args = */ NULL);
658   if (status != 0)
659   {
660     char errbuf[1024];
661     ERROR ("pinba plugin: pthread_create(3) failed: %s",
662         sstrerror (errno, errbuf, sizeof (errbuf)));
663     return (-1);
664   }
665   collector_thread_running = 1;
666
667   return (0);
668 } /* }}} */
669
670 static int plugin_shutdown (void) /* {{{ */
671 {
672   if (collector_thread_running)
673   {
674     int status;
675
676     DEBUG ("pinba plugin: Shutting down collector thread.");
677     collector_thread_do_shutdown = 1;
678
679     status = pthread_join (collector_thread_id, /* retval = */ NULL);
680     if (status != 0)
681     {
682       char errbuf[1024];
683       ERROR ("pinba plugin: pthread_join(3) failed: %s",
684           sstrerror (status, errbuf, sizeof (errbuf)));
685     }
686
687     collector_thread_running = 0;
688     collector_thread_do_shutdown = 0;
689   } /* if (collector_thread_running) */
690
691   return (0);
692 } /* }}} int plugin_shutdown */
693
694 static int plugin_submit (const pinba_statnode_t *res) /* {{{ */
695 {
696   value_t value;
697   value_list_t vl = VALUE_LIST_INIT;
698   
699   vl.values = &value;
700   vl.values_len = 1;
701   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
702   sstrncpy (vl.plugin, "pinba", sizeof (vl.plugin));
703   sstrncpy (vl.plugin_instance, res->name, sizeof (vl.plugin_instance));
704
705   value.derive = res->req_count;
706   sstrncpy (vl.type, "total_requests", sizeof (vl.type)); 
707   plugin_dispatch_values (&vl);
708
709   value.derive = float_counter_get (&res->req_time, /* factor = */ 1000);
710   sstrncpy (vl.type, "total_time_in_ms", sizeof (vl.type)); 
711   plugin_dispatch_values (&vl);
712
713   value.derive = res->doc_size;
714   sstrncpy (vl.type, "total_bytes", sizeof (vl.type)); 
715   plugin_dispatch_values (&vl);
716
717   value.derive = float_counter_get (&res->ru_utime, /* factor = */ 100);
718   sstrncpy (vl.type, "cpu", sizeof (vl.type));
719   sstrncpy (vl.type_instance, "user", sizeof (vl.type_instance));
720   plugin_dispatch_values (&vl);
721
722   value.derive = float_counter_get (&res->ru_stime, /* factor = */ 100);
723   sstrncpy (vl.type, "cpu", sizeof (vl.type));
724   sstrncpy (vl.type_instance, "system", sizeof (vl.type_instance));
725   plugin_dispatch_values (&vl);
726
727   value.gauge = res->mem_peak;
728   sstrncpy (vl.type, "memory", sizeof (vl.type));
729   sstrncpy (vl.type_instance, "peak", sizeof (vl.type_instance));
730   plugin_dispatch_values (&vl);
731
732   return (0);
733 } /* }}} int plugin_submit */
734
735 static int plugin_read (void) /* {{{ */
736 {
737   unsigned int i=0;
738   pinba_statnode_t data;
739   
740   while ((i = service_statnode_collect (&data, i)) != 0)
741   {
742     plugin_submit (&data);
743   }
744   
745   return 0;
746 } /* }}} int plugin_read */
747
748 void module_register (void) /* {{{ */
749 {
750   plugin_register_complex_config ("pinba", plugin_config);
751   plugin_register_init ("pinba", plugin_init);
752   plugin_register_read ("pinba", plugin_read);
753   plugin_register_shutdown ("pinba", plugin_shutdown);
754 } /* }}} void module_register */
755
756 /* vim: set sw=2 sts=2 et fdm=marker : */