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