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