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