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