pinba plugin: Use mutexes rather than R/W-locks.
[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  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; only version 2 of the License is applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Antony Dovgal <tony at daylessday.org>
21  *   Phoenix Kayo <kayo.k11.4 at gmail.com>
22  **/
23
24 #include "collectd.h"
25 #include "common.h"
26 #include "plugin.h"
27 #include "configfile.h"
28
29 #include <pthread.h>
30 #include <sys/socket.h>
31 #include <netdb.h>
32 #include <poll.h>
33
34 #include "pinba.pb-c.h"
35
36 typedef uint8_t u_char;
37
38 #include <event.h>
39
40 /*
41  *  Service declaration section
42  */
43 #ifndef PINBA_UDP_BUFFER_SIZE
44 # define PINBA_UDP_BUFFER_SIZE 65536
45 #endif
46
47 #ifndef PINBA_DEFAULT_ADDRESS
48 # define PINBA_DEFAULT_ADDRESS "127.0.0.1" /* FIXME */
49 #endif
50
51 #ifndef PINBA_DEFAULT_PORT
52 # define PINBA_DEFAULT_PORT 12345 /* FIXME */
53 #endif
54
55 #ifndef PINBA_MAX_SOCKETS
56 # define PINBA_MAX_SOCKETS 16
57 #endif
58
59 #ifndef NI_MAXSERV
60 # define NI_MAXSERV 32
61 #endif
62
63 /*
64  * Private data structures
65  */
66 typedef struct _pinba_statres_ pinba_statres;
67 struct _pinba_statres_ {
68   const char *name;
69   double req_per_sec;
70   double req_time;
71   double ru_utime;
72   double ru_stime;
73   double doc_size;
74   double mem_peak;
75 };
76
77 struct pinba_socket_s {
78   int listen_sock;
79   struct event *accept_event;
80
81   struct pollfd fd[PINBA_MAX_SOCKETS];
82   nfds_t fd_num;
83 };
84 typedef struct pinba_socket_s pinba_socket_t;
85
86 typedef double pinba_time_t;
87 typedef uint32_t pinba_size_t;
88
89 static struct event_base *temp_base = NULL;
90
91 static pinba_socket_t *temp_sock = NULL;
92
93 static pthread_t temp_thrd;
94
95 typedef struct pinba_statnode_s pinba_statnode_t;
96 struct pinba_statnode_s
97 {
98   /* collector name */
99   char *name;
100   /* query data */
101   char *host;
102   char *server;
103   char *script;
104   /* collected data */
105   pinba_time_t last_coll;
106   pinba_size_t req_count;
107   pinba_time_t req_time;
108   pinba_time_t ru_utime;
109   pinba_time_t ru_stime;
110   pinba_size_t doc_size;
111   pinba_size_t mem_peak;
112 };
113
114 static pinba_statnode_t *stat_nodes = NULL;
115 static unsigned int stat_nodes_num = 0;
116 static pthread_mutex_t stat_nodes_lock;
117
118 char service_status=0;
119 char *service_address = PINBA_DEFAULT_ADDRESS;
120 unsigned int service_port=PINBA_DEFAULT_PORT;
121
122 static pinba_time_t now (void) /* {{{ */
123 {
124   static struct timeval tv;
125   
126   gettimeofday (&tv, /* tz = */ NULL);
127   
128   return (double)tv.tv_sec+((double)tv.tv_usec/(double)1000000);
129 } /* }}} */
130
131 static void service_statnode_reset (pinba_statnode_t *node) /* {{{ */
132 {
133   node->last_coll=now();
134   node->req_count=0;
135   node->req_time=0.0;
136   node->ru_utime=0.0;
137   node->ru_stime=0.0;
138   node->doc_size=0;
139   node->mem_peak=0;
140 } /* }}} void service_statnode_reset */
141
142 static void strset (char **str, const char *new) /* {{{ */
143 {
144   char *tmp;
145
146   if (!str || !new)
147     return;
148
149   tmp = strdup (new);
150   if (tmp == NULL)
151     return;
152
153   sfree (*str);
154   *str = tmp;
155 } /* }}} void strset */
156
157 static void service_statnode_add(const char *name, /* {{{ */
158     const char *host,
159     const char *server,
160     const char *script)
161 {
162   pinba_statnode_t *node;
163   DEBUG("adding node `%s' to collector { %s, %s, %s }", name, host?host:"", server?server:"", script?script:"");
164   
165   stat_nodes=realloc(stat_nodes, sizeof(pinba_statnode_t)*(stat_nodes_num+1));
166   if(!stat_nodes){
167     ERROR("Realloc failed!");
168     exit(-1);
169   }
170   
171   node=&stat_nodes[stat_nodes_num];
172   
173   /* reset stat data */
174   service_statnode_reset(node);
175   
176   /* reset strings */
177   node->name=NULL;
178   node->host=NULL;
179   node->server=NULL;
180   node->script=NULL;
181   
182   /* fill query data */
183   strset(&node->name, name);
184   strset(&node->host, host);
185   strset(&node->server, server);
186   strset(&node->script, script);
187   
188   /* increment counter */
189   stat_nodes_num++;
190 } /* }}} void service_statnode_add */
191
192 static void service_statnode_free (void)
193 {
194   unsigned int i;
195
196   if(stat_nodes_num < 1)
197     return;
198
199   for (i = 0; i < stat_nodes_num; i++)
200   {
201     sfree (stat_nodes[i].name);
202     sfree (stat_nodes[i].host);
203     sfree (stat_nodes[i].server);
204     sfree (stat_nodes[i].script);
205   }
206
207   sfree (stat_nodes);
208   stat_nodes_num = 0;
209
210   pthread_mutex_destroy (&stat_nodes_lock);
211 }
212
213 static void service_statnode_init (void)
214 {
215   /* only total info collect by default */
216   service_statnode_free();
217   
218   DEBUG("initializing collector..");
219   pthread_mutex_init(&stat_nodes_lock, 0);
220 }
221
222 static void service_statnode_begin (void)
223 {
224   service_statnode_init();
225   pthread_mutex_lock(&stat_nodes_lock);
226   
227   service_statnode_add("total", NULL, NULL, NULL);
228 }
229
230 static void service_statnode_end (void)
231 {
232   pthread_mutex_unlock(&stat_nodes_lock);
233 }
234
235 static unsigned int service_statnode_collect (pinba_statres *res, /* {{{ */
236     unsigned int index)
237 {
238   pinba_statnode_t* node;
239   pinba_time_t delta;
240   
241   if (stat_nodes_num == 0)
242     return 0;
243   
244   /* begin collecting */
245   if (index == 0)
246     pthread_mutex_lock (&stat_nodes_lock);
247   
248   /* end collecting */
249   if (index >= stat_nodes_num)
250   {
251     pthread_mutex_unlock (&stat_nodes_lock);
252     return 0;
253   }
254   
255   node = stat_nodes + index;
256   delta = now() - node->last_coll;
257   
258   res->name = node->name;
259   res->req_per_sec = node->req_count / delta;
260   
261   if (node->req_count == 0)
262     node->req_count = 1;
263
264   res->req_time = node->req_time / node->req_count;
265   res->ru_utime = node->ru_utime / node->req_count;
266   res->ru_stime = node->ru_stime / node->req_count;
267   res->ru_stime = node->ru_stime / node->req_count;
268   res->doc_size = node->doc_size / node->req_count;
269   res->mem_peak = node->mem_peak / node->req_count;
270   
271   service_statnode_reset (node);
272   return (index + 1);
273 } /* }}} unsigned int service_statnode_collect */
274
275 static void service_statnode_process (pinba_statnode_t *node,
276     Pinba__Request* request)
277 {
278   node->req_count++;
279   node->req_time+=request->request_time;
280   node->ru_utime+=request->ru_utime;
281   node->ru_stime+=request->ru_stime;
282   node->doc_size+=request->document_size;
283   node->mem_peak+=request->memory_peak;
284 }
285
286 static void service_process_request (Pinba__Request *request)
287 {
288   unsigned int i;
289
290   pthread_mutex_lock (&stat_nodes_lock);
291   
292   for (i = 0; i < stat_nodes_num; i++)
293   {
294     if(stat_nodes[i].host && strcmp(request->hostname, stat_nodes[i].host))
295       continue;
296     if(stat_nodes[i].server && strcmp(request->server_name, stat_nodes[i].server))
297       continue;
298     if(stat_nodes[i].script && strcmp(request->script_name, stat_nodes[i].script))
299       continue;
300
301     service_statnode_process(&stat_nodes[i], request);
302   }
303   
304   pthread_mutex_unlock(&stat_nodes_lock);
305 }
306
307 static void *pinba_main (void *arg)
308 {
309   DEBUG("entering listen-loop..");
310   
311   service_status=1;
312   event_base_dispatch(temp_base);
313   
314   /* unreachable */
315   return NULL;
316 }
317
318 static void pinba_socket_free (pinba_socket_t *socket) /* {{{ */
319 {
320   if (!socket)
321     return;
322   
323   if (socket->listen_sock >= 0)
324   {
325     close(socket->listen_sock);
326     socket->listen_sock = -1;
327   }
328   
329   if (socket->accept_event)
330   {
331     event_del(socket->accept_event);
332     free(socket->accept_event);
333     socket->accept_event = NULL;
334   }
335   
336   free(socket);
337 } /* }}} void pinba_socket_free */
338
339 static int pinba_process_stats_packet (const uint8_t *buffer, /* {{{ */
340     size_t buffer_size)
341 {
342   Pinba__Request *request;  
343   
344   request = pinba__request__unpack (NULL, buffer_size, buffer);
345   
346   if (!request)
347     return (-1);
348
349   service_process_request(request);
350   pinba__request__free_unpacked (request, NULL);
351     
352   return (0);
353 } /* }}} int pinba_process_stats_packet */
354
355 static void pinba_udp_read_callback_fn (int sock, short event, void *arg) /* {{{ */
356 {
357   uint8_t buffer[PINBA_UDP_BUFFER_SIZE];
358   size_t buffer_size;
359   int status;
360
361   if ((event & EV_READ) == 0)
362     return;
363
364   while (42)
365   {
366     buffer_size = sizeof (buffer);
367     status = recvfrom (sock, buffer, buffer_size - 1, MSG_DONTWAIT, /* from = */ NULL, /* from len = */ 0);
368     if (status < 0)
369     {
370       char errbuf[1024];
371
372       if ((errno == EINTR)
373 #ifdef EWOULDBLOCK
374           || (errno == EWOULDBLOCK)
375 #endif
376           || (errno == EAGAIN))
377       {
378         continue;
379       }
380
381       WARNING("pinba plugin: recvfrom(2) failed: %s",
382           sstrerror (errno, errbuf, sizeof (errbuf)));
383       return;
384     }
385     else if (status == 0)
386     {
387       DEBUG ("pinba plugin: recvfrom(2) returned unexpected status zero.");
388       return;
389     }
390     else /* if (status > 0) */
391     {
392       assert (((size_t) status) < buffer_size);
393       buffer_size = (size_t) status;
394       buffer[buffer_size] = 0;
395
396       status = pinba_process_stats_packet (buffer, buffer_size);
397       if (status != 0)
398         DEBUG("pinba plugin: Parsing packet failed.");
399       return;
400     }
401
402     /* not reached */
403     assert (23 == 42);
404   } /* while (42) */
405 } /* }}} void pinba_udp_read_callback_fn */
406
407 static int pb_add_socket (pinba_socket_t *s, /* {{{ */
408     const struct addrinfo *ai)
409 {
410   int fd;
411   int tmp;
412   int status;
413
414   if (s->fd_num == PINBA_MAX_SOCKETS)
415   {
416     WARNING ("pinba plugin: Sorry, you have hit the built-in limit of "
417         "%i sockets. Please complain to the collectd developers so we can "
418         "raise the limit.", PINBA_MAX_SOCKETS);
419     return (-1);
420   }
421
422   fd = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol);
423   if (fd < 0)
424   {
425     char errbuf[1024];
426     ERROR ("pinba plugin: socket(2) failed: %s",
427         sstrerror (errno, errbuf, sizeof (errbuf)));
428     return (0);
429   }
430
431   tmp = 1;
432   status = setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof (tmp));
433   if (status != 0)
434   {
435     char errbuf[1024];
436     WARNING ("pinba plugin: setsockopt(SO_REUSEADDR) failed: %s",
437         sstrerror (errno, errbuf, sizeof (errbuf)));
438   }
439
440   status = bind (fd, ai->ai_addr, ai->ai_addrlen);
441   if (status != 0)
442   {
443     char errbuf[1024];
444     ERROR ("pinba plugin: bind(2) failed: %s",
445         sstrerror (errno, errbuf, sizeof (errbuf)));
446     return (0);
447   }
448
449   s->fd[s->fd_num].fd = fd;
450   s->fd[s->fd_num].events = POLLIN | POLLPRI;
451   s->fd[s->fd_num].revents = 0;
452   s->fd_num++;
453
454   return (0);
455 } /* }}} int pb_add_socket */
456
457 static pinba_socket_t *pinba_socket_open (const char *node, /* {{{ */
458     int listen_port)
459 {
460   pinba_socket_t *s;
461   struct addrinfo *ai_list;
462   struct addrinfo *ai_ptr;
463   struct addrinfo  ai_hints;
464   int status;
465
466   char service[NI_MAXSERV]; /* FIXME */
467   snprintf (service, sizeof (service), "%i", listen_port);
468
469   memset (&ai_hints, 0, sizeof (ai_hints));
470   ai_hints.ai_flags = AI_PASSIVE;
471   ai_hints.ai_family = AF_UNSPEC;
472   ai_hints.ai_socktype = SOCK_DGRAM;
473   ai_hints.ai_addr = NULL;
474   ai_hints.ai_canonname = NULL;
475   ai_hints.ai_next = NULL;
476
477   ai_list = NULL;
478   status = getaddrinfo (node, service,
479       &ai_hints, &ai_list);
480   if (status != 0)
481   {
482     ERROR ("pinba plugin: getaddrinfo(3) failed: %s",
483         gai_strerror (status));
484     return (NULL);
485   }
486   assert (ai_list != NULL);
487
488   s = malloc (sizeof (*s));
489   if (s != NULL)
490   {
491     freeaddrinfo (ai_list);
492     ERROR ("pinba plugin: malloc failed.");
493     return (NULL);
494   }
495   memset (s, 0, sizeof (*s));
496
497   for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
498   {
499     status = pb_add_socket (s, ai_ptr);
500     if (status != 0)
501       break;
502   } /* for (ai_list) */
503   
504   freeaddrinfo (ai_list);
505
506   if (s->fd_num < 1)
507   {
508     WARNING ("pinba plugin: Unable to open socket for address %s.", node);
509     sfree (s);
510     s = NULL;
511   }
512
513   return (s);
514 } /* }}} pinba_socket_open */
515
516 static int service_cleanup (void)
517 {
518   DEBUG("closing socket..");
519   if(temp_sock){
520     pthread_mutex_lock(&stat_nodes_lock);
521     pinba_socket_free(temp_sock);
522     pthread_mutex_unlock(&stat_nodes_lock);
523   }
524   
525   DEBUG("shutdowning event..");
526   event_base_free(temp_base);
527   
528   DEBUG("shutting down..");
529
530   return (0);
531 }
532
533 static int service_start(void)
534 {
535   DEBUG("starting up..");
536   
537   DEBUG("initializing event..");
538   temp_base = event_base_new();
539   
540   DEBUG("opening socket..");
541   
542   temp_sock = pinba_socket_open(service_address, service_port);
543   
544   if (!temp_sock) {
545     service_cleanup();
546     return 1;
547   }
548   
549   if (pthread_create(&temp_thrd, NULL, pinba_main, NULL)) {
550     service_cleanup();
551     return 1;
552   }
553   
554   return 0;
555 }
556
557 static int service_stop (void)
558 {
559   pthread_cancel(temp_thrd);
560   pthread_join(temp_thrd, NULL);
561   service_status=0;
562   DEBUG("terminating listen-loop..");
563   
564   service_cleanup();
565   
566   return 0;
567 }
568
569 static void service_config (const char *address, unsigned int port) /* {{{ */
570 {
571   int need_restart = 0;
572
573   if (address && service_address && (strcmp(service_address, address) != 0))
574   {
575     strset (&service_address, address);
576     need_restart++;
577   }
578
579   if ((port > 0) && (port < 65536) && (service_port != port))
580   {
581     service_port=port;
582     need_restart++;
583   }
584
585   if(service_status && need_restart)
586   {
587     service_stop();
588     service_start();
589   }
590 } /* }}} void service_config */
591
592 /*
593  * Plugin declaration section
594  */
595
596 static int config_set (char **var, const char *value)
597 {
598   /* code from nginx plugin for collectd */
599   if (*var != NULL) {
600     free (*var);
601     *var = NULL;
602   }
603   
604   if ((*var = strdup (value)) == NULL) return (1);
605   else return (0);
606 }
607
608 static int plugin_config (oconfig_item_t *ci)
609 {
610   unsigned int i, o;
611   int pinba_port = 0;
612   char *pinba_address = NULL;
613   
614   INFO("Pinba Configure..");
615   
616   service_statnode_begin();
617   
618   /* Set default values */
619   config_set(&pinba_address, PINBA_DEFAULT_ADDRESS);
620   pinba_port = PINBA_DEFAULT_PORT;
621   
622   for (i = 0; i < ci->children_num; i++) {
623     oconfig_item_t *child = ci->children + i;
624     if (strcasecmp ("Address", child->key) == 0) {
625       if ((child->values_num != 1) || (child->values[0].type != OCONFIG_TYPE_STRING)){
626         WARNING ("pinba plugin: `Address' needs exactly one string argument.");
627         return (-1);
628       }
629       config_set(&pinba_address, child->values[0].value.string);
630     } else if (strcasecmp ("Port", child->key) == 0) {
631       if ((child->values_num != 1) || (child->values[0].type != OCONFIG_TYPE_NUMBER)){
632         WARNING ("pinba plugin: `Port' needs exactly one number argument.");
633         return (-1);
634       }
635       pinba_port=child->values[0].value.number;
636     } else if (strcasecmp ("View", child->key) == 0) {
637       const char *name=NULL, *host=NULL, *server=NULL, *script=NULL;
638       if ((child->values_num != 1) || (child->values[0].type != OCONFIG_TYPE_STRING) || strlen(child->values[0].value.string)==0){
639         WARNING ("pinba plugin: `View' needs exactly one non-empty string argument.");
640         return (-1);
641       }
642       name = child->values[0].value.string;
643       for(o=0; o<child->children_num; o++){
644         oconfig_item_t *node = child->children + o;
645         if (strcasecmp ("Host", node->key) == 0) {
646           if ((node->values_num != 1) || (node->values[0].type != OCONFIG_TYPE_STRING) || strlen(node->values[0].value.string)==0){
647             WARNING ("pinba plugin: `View->Host' needs exactly one non-empty string argument.");
648             return (-1);
649           }
650           host = node->values[0].value.string;
651         } else if (strcasecmp ("Server", node->key) == 0) {
652           if ((node->values_num != 1) || (node->values[0].type != OCONFIG_TYPE_STRING) || strlen(node->values[0].value.string)==0){
653             WARNING ("pinba plugin: `View->Server' needs exactly one non-empty string argument.");
654             return (-1);
655           }
656           server = node->values[0].value.string;
657         } else if (strcasecmp ("Script", node->key) == 0) {
658           if ((node->values_num != 1) || (node->values[0].type != OCONFIG_TYPE_STRING) || strlen(node->values[0].value.string)==0){
659             WARNING ("pinba plugin: `View->Script' needs exactly one non-empty string argument.");
660             return (-1);
661           }
662           script = node->values[0].value.string;
663         } else {
664           WARNING ("pinba plugin: In `<View>' context allowed only `Host', `Server' and `Script' options but not the `%s'.", node->key);
665           return (-1);
666         }
667       }
668       /* add new statnode */
669       service_statnode_add(name, host, server, script);
670     } else {
671       WARNING ("pinba plugin: In `<Plugin pinba>' context allowed only `Address', `Port' and `Observe' options but not the `%s'.", child->key);
672       return (-1);
673     }
674   }
675   
676   service_statnode_end();
677   
678   service_config(pinba_address, pinba_port);
679   return (0);
680 } /* int pinba_config */
681
682 static int plugin_init (void)
683 {
684   INFO("Pinba Starting..");
685   service_start();
686   return 0;
687 }
688
689 static int plugin_shutdown (void)
690 {
691   INFO("Pinba Stopping..");
692   service_stop();
693   service_statnode_free();
694   return 0;
695 }
696
697 static int plugin_submit (const char *plugin_instance,
698                const char *type,
699                const pinba_statres *res) {
700   value_t values[6];
701   value_list_t vl = VALUE_LIST_INIT;
702   
703   values[0].gauge = res->req_per_sec;
704   values[1].gauge = res->req_time;
705   values[2].gauge = res->ru_utime;
706   values[3].gauge = res->ru_stime;
707   values[4].gauge = res->doc_size;
708   values[5].gauge = res->mem_peak;
709   
710   vl.values = values;
711   vl.values_len = 6;
712   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
713   sstrncpy (vl.plugin, "pinba", sizeof (vl.plugin));
714   sstrncpy (vl.plugin_instance, plugin_instance,
715             sizeof(vl.plugin_instance));
716   sstrncpy (vl.type, type, sizeof (vl.type));
717   INFO("Pinba Dispatch");
718   plugin_dispatch_values (&vl);
719
720   return (0);
721 }
722
723 static int plugin_read (void)
724 {
725   unsigned int i=0;
726   static pinba_statres res;
727   
728   while ((i = service_statnode_collect (&res, i)) != 0)
729   {
730     plugin_submit(res.name, "pinba_view", &res);
731   }
732   
733   return 0;
734 }
735
736 void module_register (void)
737 {
738   plugin_register_complex_config ("pinba", plugin_config);
739   plugin_register_init ("pinba", plugin_init);
740   plugin_register_read ("pinba", plugin_read);
741   plugin_register_shutdown ("pinba", plugin_shutdown);
742 } /* void module_register */
743
744 /* vim: set sw=2 sts=2 et fdm=marker : */