Fix compile time issues
[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 "plugin.h"
29 #include "utils/common/common.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
284   if (s->fd_num == PINBA_MAX_SOCKETS) {
285     WARNING("pinba plugin: Sorry, you have hit the built-in limit of "
286             "%i sockets. Please complain to the collectd developers so we can "
287             "raise the limit.",
288             PINBA_MAX_SOCKETS);
289     return -1;
290   }
291
292   int fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
293   if (fd < 0) {
294     ERROR("pinba plugin: socket(2) failed: %s", STRERRNO);
295     return 0;
296   }
297
298   int status = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int));
299   if (status != 0) {
300     WARNING("pinba plugin: setsockopt(SO_REUSEADDR) failed: %s", STRERRNO);
301   }
302
303   status = bind(fd, ai->ai_addr, ai->ai_addrlen);
304   if (status != 0) {
305     ERROR("pinba plugin: bind(2) failed: %s", STRERRNO);
306     close(fd);
307     return 0;
308   }
309
310   s->fd[s->fd_num].fd = fd;
311   s->fd[s->fd_num].events = POLLIN | POLLPRI;
312   s->fd[s->fd_num].revents = 0;
313   s->fd_num++;
314
315   return 0;
316 } /* }}} int pb_add_socket */
317
318 static pinba_socket_t *pinba_socket_open(const char *node, /* {{{ */
319                                          const char *service) {
320   pinba_socket_t *s;
321   struct addrinfo *ai_list;
322   int status;
323
324   if (node == NULL)
325     node = PINBA_DEFAULT_NODE;
326
327   if (service == NULL)
328     service = PINBA_DEFAULT_SERVICE;
329
330   struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
331                               .ai_flags = AI_PASSIVE,
332                               .ai_socktype = SOCK_DGRAM};
333
334   status = getaddrinfo(node, service, &ai_hints, &ai_list);
335   if (status != 0) {
336     ERROR("pinba plugin: getaddrinfo(3) failed: %s", gai_strerror(status));
337     return NULL;
338   }
339   assert(ai_list != NULL);
340
341   s = calloc(1, sizeof(*s));
342   if (s == NULL) {
343     freeaddrinfo(ai_list);
344     ERROR("pinba plugin: calloc failed.");
345     return NULL;
346   }
347
348   for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
349        ai_ptr = ai_ptr->ai_next) {
350     status = pb_add_socket(s, ai_ptr);
351     if (status != 0)
352       break;
353   } /* for (ai_list) */
354
355   freeaddrinfo(ai_list);
356
357   if (s->fd_num < 1) {
358     WARNING("pinba plugin: Unable to open socket for address %s.", node);
359     sfree(s);
360     s = NULL;
361   }
362
363   return s;
364 } /* }}} pinba_socket_open */
365
366 static void pinba_socket_free(pinba_socket_t *socket) /* {{{ */
367 {
368   if (!socket)
369     return;
370
371   for (nfds_t i = 0; i < socket->fd_num; i++) {
372     if (socket->fd[i].fd < 0)
373       continue;
374     close(socket->fd[i].fd);
375     socket->fd[i].fd = -1;
376   }
377
378   sfree(socket);
379 } /* }}} void pinba_socket_free */
380
381 static int pinba_process_stats_packet(const uint8_t *buffer, /* {{{ */
382                                       size_t buffer_size) {
383   Pinba__Request *request;
384
385   request = pinba__request__unpack(NULL, buffer_size, buffer);
386
387   if (!request)
388     return -1;
389
390   service_process_request(request);
391   pinba__request__free_unpacked(request, NULL);
392
393   return 0;
394 } /* }}} int pinba_process_stats_packet */
395
396 static int pinba_udp_read_callback_fn(int sock) /* {{{ */
397 {
398   uint8_t buffer[PINBA_UDP_BUFFER_SIZE];
399   size_t buffer_size;
400   int status;
401
402   while (42) {
403     buffer_size = sizeof(buffer);
404     status = recvfrom(sock, buffer, buffer_size - 1, MSG_DONTWAIT,
405                       /* from = */ NULL, /* from len = */ 0);
406     if (status < 0) {
407
408       if ((errno == EINTR)
409 #ifdef EWOULDBLOCK
410           || (errno == EWOULDBLOCK)
411 #endif
412           || (errno == EAGAIN)) {
413         continue;
414       }
415
416       WARNING("pinba plugin: recvfrom(2) failed: %s", STRERRNO);
417       return -1;
418     } else if (status == 0) {
419       DEBUG("pinba plugin: recvfrom(2) returned unexpected status zero.");
420       return -1;
421     } else /* if (status > 0) */
422     {
423       assert(((size_t)status) < buffer_size);
424       buffer_size = (size_t)status;
425       buffer[buffer_size] = 0;
426
427       status = pinba_process_stats_packet(buffer, buffer_size);
428       if (status != 0)
429         DEBUG("pinba plugin: Parsing packet failed.");
430       return status;
431     }
432   } /* while (42) */
433
434   /* not reached */
435   assert(23 == 42);
436   return -1;
437 } /* }}} void pinba_udp_read_callback_fn */
438
439 static int receive_loop(void) /* {{{ */
440 {
441   pinba_socket_t *s;
442
443   s = pinba_socket_open(conf_node, conf_service);
444   if (s == NULL) {
445     ERROR("pinba plugin: Collector thread is exiting prematurely.");
446     return -1;
447   }
448
449   while (!collector_thread_do_shutdown) {
450     int status;
451
452     if (s->fd_num < 1)
453       break;
454
455     status = poll(s->fd, s->fd_num, /* timeout = */ 1000);
456     if (status == 0) /* timeout */
457     {
458       continue;
459     } else if (status < 0) {
460       if ((errno == EINTR) || (errno == EAGAIN))
461         continue;
462
463       ERROR("pinba plugin: poll(2) failed: %s", STRERRNO);
464       pinba_socket_free(s);
465       return -1;
466     }
467
468     for (nfds_t i = 0; i < s->fd_num; i++) {
469       if (s->fd[i].revents & (POLLERR | POLLHUP | POLLNVAL)) {
470         pb_del_socket(s, i);
471         i--;
472       } else if (s->fd[i].revents & (POLLIN | POLLPRI)) {
473         pinba_udp_read_callback_fn(s->fd[i].fd);
474       }
475     } /* for (s->fd) */
476   }   /* while (!collector_thread_do_shutdown) */
477
478   pinba_socket_free(s);
479   s = NULL;
480
481   return 0;
482 } /* }}} int receive_loop */
483
484 static void *collector_thread(void *arg) /* {{{ */
485 {
486   receive_loop();
487
488   memset(&collector_thread_id, 0, sizeof(collector_thread_id));
489   collector_thread_running = false;
490   pthread_exit(NULL);
491   return NULL;
492 } /* }}} void *collector_thread */
493
494 /*
495  * Plugin declaration section
496  */
497 static int pinba_config_view(const oconfig_item_t *ci) /* {{{ */
498 {
499   char *name = NULL;
500   char *host = NULL;
501   char *server = NULL;
502   char *script = NULL;
503   int status;
504
505   status = cf_util_get_string(ci, &name);
506   if (status != 0)
507     return status;
508
509   for (int i = 0; i < ci->children_num; i++) {
510     oconfig_item_t *child = ci->children + i;
511
512     if (strcasecmp("Host", child->key) == 0)
513       status = cf_util_get_string(child, &host);
514     else if (strcasecmp("Server", child->key) == 0)
515       status = cf_util_get_string(child, &server);
516     else if (strcasecmp("Script", child->key) == 0)
517       status = cf_util_get_string(child, &script);
518     else {
519       WARNING("pinba plugin: Unknown config option: %s", child->key);
520       status = -1;
521     }
522
523     if (status != 0)
524       break;
525   }
526
527   if (status == 0)
528     service_statnode_add(name, host, server, script);
529
530   sfree(name);
531   sfree(host);
532   sfree(server);
533   sfree(script);
534
535   return status;
536 } /* }}} int pinba_config_view */
537
538 static int plugin_config(oconfig_item_t *ci) /* {{{ */
539 {
540   /* The lock should not be necessary in the config callback, but let's be
541    * sure.. */
542   pthread_mutex_lock(&stat_nodes_lock);
543
544   for (int i = 0; i < ci->children_num; i++) {
545     oconfig_item_t *child = ci->children + i;
546
547     if (strcasecmp("Address", child->key) == 0)
548       cf_util_get_string(child, &conf_node);
549     else if (strcasecmp("Port", child->key) == 0)
550       cf_util_get_service(child, &conf_service);
551     else if (strcasecmp("View", child->key) == 0)
552       pinba_config_view(child);
553     else
554       WARNING("pinba plugin: Unknown config option: %s", child->key);
555   }
556
557   pthread_mutex_unlock(&stat_nodes_lock);
558
559   return 0;
560 } /* }}} int pinba_config */
561
562 static int plugin_init(void) /* {{{ */
563 {
564   int status;
565
566   if (stat_nodes == NULL) {
567     /* Collect the "total" data by default. */
568     service_statnode_add("total",
569                          /* host   = */ NULL,
570                          /* server = */ NULL,
571                          /* script = */ NULL);
572   }
573
574   if (collector_thread_running)
575     return 0;
576
577   status = plugin_thread_create(&collector_thread_id,
578                                 /* attrs = */ NULL, collector_thread,
579                                 /* args = */ NULL, "pinba collector");
580   if (status != 0) {
581     ERROR("pinba plugin: pthread_create(3) failed: %s", STRERRNO);
582     return -1;
583   }
584   collector_thread_running = true;
585
586   return 0;
587 } /* }}} */
588
589 static int plugin_shutdown(void) /* {{{ */
590 {
591   if (collector_thread_running) {
592     int status;
593
594     DEBUG("pinba plugin: Shutting down collector thread.");
595     collector_thread_do_shutdown = true;
596
597     status = pthread_join(collector_thread_id, /* retval = */ NULL);
598     if (status != 0) {
599       ERROR("pinba plugin: pthread_join(3) failed: %s", STRERROR(status));
600     }
601
602     collector_thread_running = false;
603     collector_thread_do_shutdown = false;
604   } /* if (collector_thread_running) */
605
606   return 0;
607 } /* }}} int plugin_shutdown */
608
609 static int plugin_submit(const pinba_statnode_t *res) /* {{{ */
610 {
611   value_list_t vl = VALUE_LIST_INIT;
612
613   vl.values_len = 1;
614   sstrncpy(vl.plugin, "pinba", sizeof(vl.plugin));
615   sstrncpy(vl.plugin_instance, res->name, sizeof(vl.plugin_instance));
616
617   vl.values = &(value_t){.derive = res->req_count};
618   sstrncpy(vl.type, "total_requests", sizeof(vl.type));
619   plugin_dispatch_values(&vl);
620
621   vl.values = &(value_t){
622       .derive = float_counter_get(&res->req_time, /* factor = */ 1000)};
623   sstrncpy(vl.type, "total_time_in_ms", sizeof(vl.type));
624   plugin_dispatch_values(&vl);
625
626   vl.values = &(value_t){.derive = res->doc_size};
627   sstrncpy(vl.type, "total_bytes", sizeof(vl.type));
628   plugin_dispatch_values(&vl);
629
630   vl.values = &(value_t){
631       .derive = float_counter_get(&res->ru_utime, /* factor = */ 100)};
632   sstrncpy(vl.type, "cpu", sizeof(vl.type));
633   sstrncpy(vl.type_instance, "user", sizeof(vl.type_instance));
634   plugin_dispatch_values(&vl);
635
636   vl.values = &(value_t){
637       .derive = float_counter_get(&res->ru_stime, /* factor = */ 100)};
638   sstrncpy(vl.type, "cpu", sizeof(vl.type));
639   sstrncpy(vl.type_instance, "system", sizeof(vl.type_instance));
640   plugin_dispatch_values(&vl);
641
642   vl.values = &(value_t){.gauge = res->mem_peak};
643   sstrncpy(vl.type, "memory", sizeof(vl.type));
644   sstrncpy(vl.type_instance, "peak", sizeof(vl.type_instance));
645   plugin_dispatch_values(&vl);
646
647   return 0;
648 } /* }}} int plugin_submit */
649
650 static int plugin_read(void) /* {{{ */
651 {
652   unsigned int i = 0;
653   pinba_statnode_t data;
654
655   while ((i = service_statnode_collect(&data, i)) != 0) {
656     plugin_submit(&data);
657   }
658
659   return 0;
660 } /* }}} int plugin_read */
661
662 void module_register(void) /* {{{ */
663 {
664   plugin_register_complex_config("pinba", plugin_config);
665   plugin_register_init("pinba", plugin_init);
666   plugin_register_read("pinba", plugin_read);
667   plugin_register_shutdown("pinba", plugin_shutdown);
668 } /* }}} void module_register */