treewide: use designated initializers for ai_hints
[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 <netdb.h>
32 #include <poll.h>
33
34 #include "pinba.pb-c.h"
35
36 /* AIX doesn't have MSG_DONTWAIT */
37 #ifndef MSG_DONTWAIT
38 #  define MSG_DONTWAIT MSG_NONBLOCK
39 #endif
40
41 /*
42  * Defines
43  */
44 #ifndef PINBA_UDP_BUFFER_SIZE
45 # define PINBA_UDP_BUFFER_SIZE 65536
46 #endif
47
48 #ifndef PINBA_DEFAULT_NODE
49 # define PINBA_DEFAULT_NODE "::0"
50 #endif
51
52 #ifndef PINBA_DEFAULT_SERVICE
53 # define PINBA_DEFAULT_SERVICE "30002"
54 #endif
55
56 #ifndef PINBA_MAX_SOCKETS
57 # define PINBA_MAX_SOCKETS 16
58 #endif
59
60 /*
61  * Private data structures
62  */
63 /* {{{ */
64 struct pinba_socket_s
65 {
66   struct pollfd fd[PINBA_MAX_SOCKETS];
67   nfds_t fd_num;
68 };
69 typedef struct pinba_socket_s pinba_socket_t;
70
71 /* Fixed point counter value. n is the decimal part multiplied by 10^9. */
72 struct float_counter_s
73 {
74   uint64_t i;
75   uint64_t n; /* nanos */
76 };
77 typedef struct float_counter_s float_counter_t;
78
79 struct pinba_statnode_s
80 {
81   /* collector name, used as plugin instance */
82   char *name;
83
84   /* query data */
85   char *host;
86   char *server;
87   char *script;
88
89   derive_t req_count;
90
91   float_counter_t req_time;
92   float_counter_t ru_utime;
93   float_counter_t ru_stime;
94
95   derive_t doc_size;
96   gauge_t mem_peak;
97 };
98 typedef struct pinba_statnode_s pinba_statnode_t;
99 /* }}} */
100
101 /*
102  * Module global variables
103  */
104 /* {{{ */
105 static pinba_statnode_t *stat_nodes = NULL;
106 static unsigned int stat_nodes_num = 0;
107 static pthread_mutex_t stat_nodes_lock;
108
109 static char *conf_node = NULL;
110 static char *conf_service = NULL;
111
112 static _Bool collector_thread_running = 0;
113 static _Bool collector_thread_do_shutdown = 0;
114 static pthread_t collector_thread_id;
115 /* }}} */
116
117 /*
118  * Functions
119  */
120 static void float_counter_add (float_counter_t *fc, float val) /* {{{ */
121 {
122   uint64_t tmp;
123
124   if (val < 0.0)
125     return;
126
127   tmp = (uint64_t) val;
128   val -= (double) tmp;
129
130   fc->i += tmp;
131   fc->n += (uint64_t) ((val * 1000000000.0) + .5);
132
133   if (fc->n >= 1000000000)
134   {
135     fc->i += 1;
136     fc->n -= 1000000000;
137     assert (fc->n < 1000000000);
138   }
139 } /* }}} void float_counter_add */
140
141 static derive_t float_counter_get (const float_counter_t *fc, /* {{{ */
142     uint64_t factor)
143 {
144   derive_t ret;
145
146   ret = (derive_t) (fc->i * factor);
147   ret += (derive_t) (fc->n / (1000000000 / factor));
148
149   return (ret);
150 } /* }}} derive_t float_counter_get */
151
152 static void strset (char **str, const char *new) /* {{{ */
153 {
154   char *tmp;
155
156   if (!str || !new)
157     return;
158
159   tmp = strdup (new);
160   if (tmp == NULL)
161     return;
162
163   sfree (*str);
164   *str = tmp;
165 } /* }}} void strset */
166
167 static void service_statnode_add(const char *name, /* {{{ */
168     const char *host,
169     const char *server,
170     const char *script)
171 {
172   pinba_statnode_t *node;
173
174   node = realloc (stat_nodes,
175       sizeof (*stat_nodes) * (stat_nodes_num + 1));
176   if (node == NULL)
177   {
178     ERROR ("pinba plugin: realloc failed");
179     return;
180   }
181   stat_nodes = node;
182
183   node = stat_nodes + stat_nodes_num;
184   memset (node, 0, sizeof (*node));
185
186   /* reset strings */
187   node->name   = NULL;
188   node->host   = NULL;
189   node->server = NULL;
190   node->script = NULL;
191
192   node->mem_peak = NAN;
193
194   /* fill query data */
195   strset (&node->name, name);
196   strset (&node->host, host);
197   strset (&node->server, server);
198   strset (&node->script, script);
199
200   /* increment counter */
201   stat_nodes_num++;
202 } /* }}} void service_statnode_add */
203
204 /* Copy the data from the global "stat_nodes" list into the buffer pointed to
205  * by "res", doing the derivation in the process. Returns the next index or
206  * zero if the end of the list has been reached. */
207 static unsigned int service_statnode_collect (pinba_statnode_t *res, /* {{{ */
208     unsigned int index)
209 {
210   pinba_statnode_t *node;
211
212   if (stat_nodes_num == 0)
213     return 0;
214
215   /* begin collecting */
216   if (index == 0)
217     pthread_mutex_lock (&stat_nodes_lock);
218
219   /* end collecting */
220   if (index >= stat_nodes_num)
221   {
222     pthread_mutex_unlock (&stat_nodes_lock);
223     return 0;
224   }
225
226   node = stat_nodes + index;
227   memcpy (res, node, sizeof (*res));
228
229   /* reset node */
230   node->mem_peak = NAN;
231
232   return (index + 1);
233 } /* }}} unsigned int service_statnode_collect */
234
235 static void service_statnode_process (pinba_statnode_t *node, /* {{{ */
236     Pinba__Request* request)
237 {
238   node->req_count++;
239
240   float_counter_add (&node->req_time, request->request_time);
241   float_counter_add (&node->ru_utime, request->ru_utime);
242   float_counter_add (&node->ru_stime, request->ru_stime);
243
244   node->doc_size += request->document_size;
245
246   if (isnan (node->mem_peak)
247       || (node->mem_peak < ((gauge_t) request->memory_peak)))
248     node->mem_peak = (gauge_t) request->memory_peak;
249
250 } /* }}} void service_statnode_process */
251
252 static void service_process_request (Pinba__Request *request) /* {{{ */
253 {
254   unsigned int i;
255
256   pthread_mutex_lock (&stat_nodes_lock);
257
258   for (i = 0; i < stat_nodes_num; i++)
259   {
260     if ((stat_nodes[i].host != NULL)
261         && (strcmp (request->hostname, stat_nodes[i].host) != 0))
262       continue;
263
264     if ((stat_nodes[i].server != NULL)
265       && (strcmp (request->server_name, stat_nodes[i].server) != 0))
266       continue;
267
268     if ((stat_nodes[i].script != NULL)
269       && (strcmp (request->script_name, stat_nodes[i].script) != 0))
270       continue;
271
272     service_statnode_process(&stat_nodes[i], request);
273   }
274
275   pthread_mutex_unlock(&stat_nodes_lock);
276 } /* }}} void service_process_request */
277
278 static int pb_del_socket (pinba_socket_t *s, /* {{{ */
279     nfds_t index)
280 {
281   if (index >= s->fd_num)
282     return (EINVAL);
283
284   close (s->fd[index].fd);
285   s->fd[index].fd = -1;
286
287   /* When deleting the last element in the list, no memmove is necessary. */
288   if (index < (s->fd_num - 1))
289   {
290     memmove (&s->fd[index], &s->fd[index + 1],
291         sizeof (s->fd[0]) * (s->fd_num - (index + 1)));
292   }
293
294   s->fd_num--;
295   return (0);
296 } /* }}} int pb_del_socket */
297
298 static int pb_add_socket (pinba_socket_t *s, /* {{{ */
299     const struct addrinfo *ai)
300 {
301   int fd;
302   int tmp;
303   int status;
304
305   if (s->fd_num == PINBA_MAX_SOCKETS)
306   {
307     WARNING ("pinba plugin: Sorry, you have hit the built-in limit of "
308         "%i sockets. Please complain to the collectd developers so we can "
309         "raise the limit.", PINBA_MAX_SOCKETS);
310     return (-1);
311   }
312
313   fd = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol);
314   if (fd < 0)
315   {
316     char errbuf[1024];
317     ERROR ("pinba plugin: socket(2) failed: %s",
318         sstrerror (errno, errbuf, sizeof (errbuf)));
319     return (0);
320   }
321
322   tmp = 1;
323   status = setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof (tmp));
324   if (status != 0)
325   {
326     char errbuf[1024];
327     WARNING ("pinba plugin: setsockopt(SO_REUSEADDR) failed: %s",
328         sstrerror (errno, errbuf, sizeof (errbuf)));
329   }
330
331   status = bind (fd, ai->ai_addr, ai->ai_addrlen);
332   if (status != 0)
333   {
334     char errbuf[1024];
335     ERROR ("pinba plugin: bind(2) failed: %s",
336         sstrerror (errno, errbuf, sizeof (errbuf)));
337     close (fd);
338     return (0);
339   }
340
341   s->fd[s->fd_num].fd = fd;
342   s->fd[s->fd_num].events = POLLIN | POLLPRI;
343   s->fd[s->fd_num].revents = 0;
344   s->fd_num++;
345
346   return (0);
347 } /* }}} int pb_add_socket */
348
349 static pinba_socket_t *pinba_socket_open (const char *node, /* {{{ */
350     const char *service)
351 {
352   pinba_socket_t *s;
353   struct addrinfo *ai_list;
354   struct addrinfo *ai_ptr;
355   int status;
356
357   if (node == NULL)
358     node = PINBA_DEFAULT_NODE;
359
360   if (service == NULL)
361     service = PINBA_DEFAULT_SERVICE;
362
363   ai_list = NULL;
364
365   struct addrinfo  ai_hints = {
366     .ai_family = AF_UNSPEC,
367     .ai_flags = AI_PASSIVE,
368     .ai_socktype = SOCK_DGRAM
369   };
370
371   status = getaddrinfo (node, service,
372       &ai_hints, &ai_list);
373   if (status != 0)
374   {
375     ERROR ("pinba plugin: getaddrinfo(3) failed: %s",
376         gai_strerror (status));
377     return (NULL);
378   }
379   assert (ai_list != NULL);
380
381   s = calloc (1, sizeof (*s));
382   if (s == NULL)
383   {
384     freeaddrinfo (ai_list);
385     ERROR ("pinba plugin: calloc failed.");
386     return (NULL);
387   }
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 static int pinba_config_view (const oconfig_item_t *ci) /* {{{ */
563 {
564   char *name   = NULL;
565   char *host   = NULL;
566   char *server = NULL;
567   char *script = NULL;
568   int status;
569   int i;
570
571   status = cf_util_get_string (ci, &name);
572   if (status != 0)
573     return (status);
574
575   for (i = 0; i < ci->children_num; i++)
576   {
577     oconfig_item_t *child = ci->children + i;
578
579     if (strcasecmp ("Host", child->key) == 0)
580       status = cf_util_get_string (child, &host);
581     else if (strcasecmp ("Server", child->key) == 0)
582       status = cf_util_get_string (child, &server);
583     else if (strcasecmp ("Script", child->key) == 0)
584       status = cf_util_get_string (child, &script);
585     else
586     {
587       WARNING ("pinba plugin: Unknown config option: %s", child->key);
588       status = -1;
589     }
590
591     if (status != 0)
592       break;
593   }
594
595   if (status == 0)
596     service_statnode_add (name, host, server, script);
597
598   sfree (name);
599   sfree (host);
600   sfree (server);
601   sfree (script);
602
603   return (status);
604 } /* }}} int pinba_config_view */
605
606 static int plugin_config (oconfig_item_t *ci) /* {{{ */
607 {
608   int i;
609
610   /* The lock should not be necessary in the config callback, but let's be
611    * sure.. */
612   pthread_mutex_lock (&stat_nodes_lock);
613
614   for (i = 0; i < ci->children_num; i++)
615   {
616     oconfig_item_t *child = ci->children + i;
617
618     if (strcasecmp ("Address", child->key) == 0)
619       cf_util_get_string (child, &conf_node);
620     else if (strcasecmp ("Port", child->key) == 0)
621       cf_util_get_service (child, &conf_service);
622     else if (strcasecmp ("View", child->key) == 0)
623       pinba_config_view (child);
624     else
625       WARNING ("pinba plugin: Unknown config option: %s", child->key);
626   }
627
628   pthread_mutex_unlock(&stat_nodes_lock);
629
630   return (0);
631 } /* }}} int pinba_config */
632
633 static int plugin_init (void) /* {{{ */
634 {
635   int status;
636
637   if (stat_nodes == NULL)
638   {
639     /* Collect the "total" data by default. */
640     service_statnode_add ("total",
641         /* host   = */ NULL,
642         /* server = */ NULL,
643         /* script = */ NULL);
644   }
645
646   if (collector_thread_running)
647     return (0);
648
649   status = plugin_thread_create (&collector_thread_id,
650       /* attrs = */ NULL,
651       collector_thread,
652       /* args = */ NULL);
653   if (status != 0)
654   {
655     char errbuf[1024];
656     ERROR ("pinba plugin: pthread_create(3) failed: %s",
657         sstrerror (errno, errbuf, sizeof (errbuf)));
658     return (-1);
659   }
660   collector_thread_running = 1;
661
662   return (0);
663 } /* }}} */
664
665 static int plugin_shutdown (void) /* {{{ */
666 {
667   if (collector_thread_running)
668   {
669     int status;
670
671     DEBUG ("pinba plugin: Shutting down collector thread.");
672     collector_thread_do_shutdown = 1;
673
674     status = pthread_join (collector_thread_id, /* retval = */ NULL);
675     if (status != 0)
676     {
677       char errbuf[1024];
678       ERROR ("pinba plugin: pthread_join(3) failed: %s",
679           sstrerror (status, errbuf, sizeof (errbuf)));
680     }
681
682     collector_thread_running = 0;
683     collector_thread_do_shutdown = 0;
684   } /* if (collector_thread_running) */
685
686   return (0);
687 } /* }}} int plugin_shutdown */
688
689 static int plugin_submit (const pinba_statnode_t *res) /* {{{ */
690 {
691   value_t value;
692   value_list_t vl = VALUE_LIST_INIT;
693
694   vl.values = &value;
695   vl.values_len = 1;
696   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
697   sstrncpy (vl.plugin, "pinba", sizeof (vl.plugin));
698   sstrncpy (vl.plugin_instance, res->name, sizeof (vl.plugin_instance));
699
700   value.derive = res->req_count;
701   sstrncpy (vl.type, "total_requests", sizeof (vl.type));
702   plugin_dispatch_values (&vl);
703
704   value.derive = float_counter_get (&res->req_time, /* factor = */ 1000);
705   sstrncpy (vl.type, "total_time_in_ms", sizeof (vl.type));
706   plugin_dispatch_values (&vl);
707
708   value.derive = res->doc_size;
709   sstrncpy (vl.type, "total_bytes", sizeof (vl.type));
710   plugin_dispatch_values (&vl);
711
712   value.derive = float_counter_get (&res->ru_utime, /* factor = */ 100);
713   sstrncpy (vl.type, "cpu", sizeof (vl.type));
714   sstrncpy (vl.type_instance, "user", sizeof (vl.type_instance));
715   plugin_dispatch_values (&vl);
716
717   value.derive = float_counter_get (&res->ru_stime, /* factor = */ 100);
718   sstrncpy (vl.type, "cpu", sizeof (vl.type));
719   sstrncpy (vl.type_instance, "system", sizeof (vl.type_instance));
720   plugin_dispatch_values (&vl);
721
722   value.gauge = res->mem_peak;
723   sstrncpy (vl.type, "memory", sizeof (vl.type));
724   sstrncpy (vl.type_instance, "peak", sizeof (vl.type_instance));
725   plugin_dispatch_values (&vl);
726
727   return (0);
728 } /* }}} int plugin_submit */
729
730 static int plugin_read (void) /* {{{ */
731 {
732   unsigned int i=0;
733   pinba_statnode_t data;
734
735   while ((i = service_statnode_collect (&data, i)) != 0)
736   {
737     plugin_submit (&data);
738   }
739
740   return 0;
741 } /* }}} int plugin_read */
742
743 void module_register (void) /* {{{ */
744 {
745   plugin_register_complex_config ("pinba", plugin_config);
746   plugin_register_init ("pinba", plugin_init);
747   plugin_register_read ("pinba", plugin_read);
748   plugin_register_shutdown ("pinba", plugin_shutdown);
749 } /* }}} void module_register */
750
751 /* vim: set sw=2 sts=2 et fdm=marker : */