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