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