Pinba plugin: Picked some low-hanging fruit.
[collectd.git] / src / pinba.c
1 /**
2  * collectd - src/pinba.c
3  * Copyright (C) 2010       Phoenix Kayo
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Phoenix Kayo <kayo.k11.4 at gmail.com>
20  **/
21
22 #define _XOPEN_SOURCE 500
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 <netinet/in.h>
32 #include <arpa/inet.h>
33
34 #include "pinba.pb-c.h"
35
36 #include <event.h>
37
38 /*
39  *  Service declaration section
40  */
41 #ifndef PINBA_UDP_BUFFER_SIZE
42 # define PINBA_UDP_BUFFER_SIZE 65536
43 #endif
44
45 typedef struct _pinba_statres_ pinba_statres;
46 struct _pinba_statres_ {
47   const char *name;
48   double req_per_sec;
49   double req_time;
50   double ru_utime;
51   double ru_stime;
52   double doc_size;
53   double mem_peak;
54 };
55
56 typedef struct _pinba_socket_ pinba_socket;
57 struct _pinba_socket_ {
58   int listen_sock;
59   struct event *accept_event;
60 };
61
62 typedef double pinba_time;
63 typedef uint32_t pinba_size;
64
65 static pinba_time now(){
66   static struct timeval tv;
67   
68   gettimeofday (&tv, /* tz = */ NULL);
69   
70   return (double)tv.tv_sec+((double)tv.tv_usec/(double)1000000);
71 }
72
73 static pthread_rwlock_t temp_lock;
74
75 static struct event_base *temp_base = NULL;
76
77 static pinba_socket *temp_sock = NULL;
78
79 static pthread_t temp_thrd;
80
81 typedef struct _pinba_statnode_ pinba_statnode;
82 struct _pinba_statnode_{
83   /* collector name */
84   char* name;
85   /* query data */
86   char *host;
87   char *server;
88   char *script;
89   /* collected data */
90   pinba_time last_coll;
91   pinba_size req_count;
92   pinba_time req_time;
93   pinba_time ru_utime;
94   pinba_time ru_stime;
95   pinba_size doc_size;
96   pinba_size mem_peak;
97 };
98
99 static unsigned int stat_nodes_count=0;
100
101 static pinba_statnode *stat_nodes = NULL;
102
103 char service_status=0;
104 char *service_address = PINBA_DEFAULT_ADDRESS;
105 unsigned int service_port=PINBA_DEFAULT_PORT;
106
107 static void
108 service_statnode_reset(pinba_statnode *node){
109   node->last_coll=now();
110   node->req_count=0;
111   node->req_time=0.0;
112   node->ru_utime=0.0;
113   node->ru_stime=0.0;
114   node->doc_size=0;
115   node->mem_peak=0;
116 }
117
118 static void strset (char **str, const char *new)
119 {
120   char *tmp;
121
122   if (!str || !new)
123     return;
124
125   tmp = strdup (new);
126   if (tmp == NULL)
127     return;
128
129   sfree (*str);
130   *str = tmp;
131 } /* void strset */
132
133 static void
134 service_statnode_add(const char *name,
135                      const char *host,
136                      const char *server,
137                      const char *script){
138   pinba_statnode *node;
139   DEBUG("adding node `%s' to collector { %s, %s, %s }", name, host?host:"", server?server:"", script?script:"");
140   
141   stat_nodes=realloc(stat_nodes, sizeof(pinba_statnode)*(stat_nodes_count+1));
142   if(!stat_nodes){
143     ERROR("Realloc failed!");
144     exit(-1);
145   }
146   
147   node=&stat_nodes[stat_nodes_count];
148   
149   /* reset stat data */
150   service_statnode_reset(node);
151   
152   /* reset strings */
153   node->name=NULL;
154   node->host=NULL;
155   node->server=NULL;
156   node->script=NULL;
157   
158   /* fill query data */
159   strset(&node->name, name);
160   strset(&node->host, host);
161   strset(&node->server, server);
162   strset(&node->script, script);
163   
164   /* increment counter */
165   stat_nodes_count++;
166 }
167
168 static void service_statnode_free (void)
169 {
170   unsigned int i;
171
172   if(stat_nodes_count < 1)
173     return;
174
175   for (i = 0; i < stat_nodes_count; i++)
176   {
177     sfree (stat_nodes[i].name);
178     sfree (stat_nodes[i].host);
179     sfree (stat_nodes[i].server);
180     sfree (stat_nodes[i].script);
181   }
182
183   sfree (stat_nodes);
184   stat_nodes_count = 0;
185
186   pthread_rwlock_destroy (&temp_lock);
187 }
188
189 static void
190 service_statnode_init(){
191   /* only total info collect by default */
192   service_statnode_free();
193   
194   DEBUG("initializing collector..");
195   pthread_rwlock_init(&temp_lock, 0);
196 }
197
198 static void
199 service_statnode_begin(){
200   service_statnode_init();
201   pthread_rwlock_wrlock(&temp_lock);
202   
203   service_statnode_add("total", NULL, NULL, NULL);
204 }
205
206 static void
207 service_statnode_end(){
208   pthread_rwlock_unlock(&temp_lock);
209 }
210
211 static unsigned int
212 service_statnode_collect(pinba_statres *res, unsigned int i){
213   pinba_statnode* node;
214   
215   if(stat_nodes_count==0) return 0;
216   
217   /* begin collecting */
218   if(i==0){
219     pthread_rwlock_wrlock(&temp_lock);
220   }
221   
222   /* find non-empty node */
223   //for(node=stat_nodes+i; node->req_count==0 && ++i<stat_nodes_count; node=stat_nodes+i);
224   
225   /* end collecting */
226   if(i>=stat_nodes_count){
227     pthread_rwlock_unlock(&temp_lock);
228     return 0;
229   }
230   
231   node=stat_nodes+i;
232   
233   pinba_time delta=now()-node->last_coll;
234   
235   res->name=node->name;
236   
237   res->req_per_sec=node->req_count/delta;
238   
239   if(node->req_count==0)node->req_count=1;
240   res->req_time=node->req_time/node->req_count;
241   res->ru_utime=node->ru_utime/node->req_count;
242   res->ru_stime=node->ru_stime/node->req_count;
243   res->ru_stime=node->ru_stime/node->req_count;
244   res->doc_size=node->doc_size/node->req_count;
245   res->mem_peak=node->mem_peak/node->req_count;
246   
247   service_statnode_reset(node);
248   return ++i;
249 }
250
251 static void
252 service_statnode_process(pinba_statnode *node,
253                          Pinba__Request* request){
254   node->req_count++;
255   node->req_time+=request->request_time;
256   node->ru_utime+=request->ru_utime;
257   node->ru_stime+=request->ru_stime;
258   node->doc_size+=request->document_size;
259   node->mem_peak+=request->memory_peak;
260 }
261
262 static void service_process_request(Pinba__Request *request)
263 {
264   unsigned int i;
265
266   pthread_rwlock_wrlock (&temp_lock);
267   
268   for (i = 0; i < stat_nodes_count; i++)
269   {
270     if(stat_nodes[i].host && strcmp(request->hostname, stat_nodes[i].host))
271       continue;
272     if(stat_nodes[i].server && strcmp(request->server_name, stat_nodes[i].server))
273       continue;
274     if(stat_nodes[i].script && strcmp(request->script_name, stat_nodes[i].script))
275       continue;
276
277     service_statnode_process(&stat_nodes[i], request);
278   }
279   
280   pthread_rwlock_unlock(&temp_lock);
281 }
282
283 static void
284 service_config(const char* address,
285                unsigned int port){
286   char need_restart=0;
287   
288   if(address && (service_address && strcmp(service_address, address))){
289     strset(&service_address, address);
290     need_restart++;
291   }
292   
293   if(port>0 && port<65536 && service_port!=port){
294     service_port=port;
295     need_restart++;
296   }
297   
298   if(service_status && need_restart){
299     service_stop();
300     service_start();
301   }
302 }
303
304 static void
305 pinba_socket_free (pinba_socket *socket);
306
307 static pinba_socket *
308 pinba_socket_open (const char *ip,
309                    int listen_port);
310
311 static void *
312 pinba_main(void *arg){
313   DEBUG("entering listen-loop..");
314   
315   service_status=1;
316   event_base_dispatch(temp_base);
317   
318   /* unreachable */
319   return NULL;
320 }
321
322 static int
323 service_cleanup(){
324   DEBUG("closing socket..");
325   if(temp_sock){
326     pthread_rwlock_wrlock(&temp_lock);
327     pinba_socket_free(temp_sock);
328     pthread_rwlock_unlock(&temp_lock);
329   }
330   
331   DEBUG("shutdowning event..");
332   event_base_free(temp_base);
333   
334   DEBUG("shutting down..");
335 }
336
337 static int
338 service_start(){
339   DEBUG("starting up..");
340   
341   DEBUG("initializing event..");
342   temp_base = event_base_new();
343   
344   DEBUG("opening socket..");
345   
346   temp_sock = pinba_socket_open(service_address, service_port);
347   
348   if (!temp_sock) {
349     service_cleanup();
350     return 1;
351   }
352   
353   if (pthread_create(&temp_thrd, NULL, pinba_main, NULL)) {
354     service_cleanup();
355     return 1;
356   }
357   
358   return 0;
359 }
360
361 static int
362 service_stop(){
363   pthread_cancel(temp_thrd);
364   pthread_join(temp_thrd, NULL);
365   service_status=0;
366   DEBUG("terminating listen-loop..");
367   
368   service_cleanup();
369   
370   return 0;
371 }
372
373 static int
374 pinba_process_stats_packet (const unsigned char *buf,
375                             int buf_len) {
376   Pinba__Request *request;  
377   
378   request = pinba__request__unpack(NULL, buf_len, buf);
379   
380   if (!request) {
381     return P_FAILURE;
382   } else {
383     service_process_request(request);
384     
385     pinba__request__free_unpacked(request, NULL);
386     
387     return P_SUCCESS;
388   }
389 }
390
391 static void
392 pinba_udp_read_callback_fn (int sock,
393                             short event,
394                             void *arg) {
395   if (event & EV_READ) {
396     int ret;
397     unsigned char buf[PINBA_UDP_BUFFER_SIZE];
398     struct sockaddr_in from;
399     socklen_t fromlen = sizeof(struct sockaddr_in);
400     
401     ret = recvfrom(sock, buf, PINBA_UDP_BUFFER_SIZE-1, MSG_DONTWAIT, (struct sockaddr *)&from, &fromlen);
402     if (ret > 0) {
403       if (pinba_process_stats_packet(buf, ret) != P_SUCCESS) {
404         DEBUG("failed to parse data received from %s", inet_ntoa(from.sin_addr));
405       }
406     } else if (ret < 0) {
407       if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
408         return;
409       }
410       WARNING("recv() failed: %s (%d)", strerror(errno), errno);
411     } else {
412       WARNING("recv() returned 0");
413     }
414   }
415 }
416
417 static void
418 pinba_socket_free (pinba_socket *socket) {
419   if (!socket) return;
420   
421   if (socket->listen_sock >= 0) {
422     close(socket->listen_sock);
423     socket->listen_sock = -1;
424   }
425   
426   if (socket->accept_event) {
427     event_del(socket->accept_event);
428     free(socket->accept_event);
429     socket->accept_event = NULL;
430   }
431   
432   free(socket);
433 }
434
435 static pinba_socket *
436 pinba_socket_open (const char *ip,
437                    int listen_port) {
438   struct sockaddr_in addr;
439   pinba_socket *s;
440   int sfd, flags, yes = 1;
441   
442   if ((sfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
443     ERROR("socket() failed: %s (%d)", strerror(errno), errno);
444     return NULL;
445   }
446   
447   if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
448     close(sfd);
449     return NULL;
450   }
451   
452   if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
453     close(sfd);
454     return NULL;
455   }
456   
457   s = (pinba_socket *)calloc(1, sizeof(pinba_socket));
458   if (!s) {
459     return NULL;
460   }
461   s->listen_sock = sfd;
462   
463   memset(&addr, 0, sizeof(addr));
464   
465   addr.sin_family = AF_INET;
466   addr.sin_port = htons(listen_port);
467   addr.sin_addr.s_addr = htonl(INADDR_ANY);
468   
469   if (ip && *ip) {
470     struct in_addr tmp;
471     
472     if (inet_aton(ip, &tmp)) {
473       addr.sin_addr.s_addr = tmp.s_addr;
474     } else {
475       WARNING("inet_aton(%s) failed, listening on ANY IP-address", ip);
476     }
477   }
478   
479   if (bind(s->listen_sock, (struct sockaddr *)&addr, sizeof(addr))) {
480     pinba_socket_free(s);
481     ERROR("bind() failed: %s (%d)", strerror(errno), errno);
482     return NULL;
483   }
484   
485   s->accept_event = (struct event *)calloc(1, sizeof(struct event));
486   if (!s->accept_event) {
487     ERROR("calloc() failed: %s (%d)", strerror(errno), errno);
488     pinba_socket_free(s);
489     return NULL;
490   }
491   
492   event_set(s->accept_event, s->listen_sock, EV_READ | EV_PERSIST, pinba_udp_read_callback_fn, s);
493   event_base_set(temp_base, s->accept_event);
494   event_add(s->accept_event, NULL);
495   
496   return s;
497 }
498
499 /*
500  * Plugin declaration section
501  */
502
503 #include<stdint.h>
504
505 static int
506 config_set (char **var, const char *value) {
507   /* code from nginx plugin for collectd */
508   if (*var != NULL) {
509     free (*var);
510     *var = NULL;
511   }
512   
513   if ((*var = strdup (value)) == NULL) return (1);
514   else return (0);
515 }
516
517 static int
518 plugin_config (oconfig_item_t *ci) {
519   unsigned int i, o;
520   int pinba_port = 0;
521   char *pinba_address = NULL;
522   
523   INFO("Pinba Configure..");
524   
525   service_statnode_begin();
526   
527   /* Set default values */
528   config_set(&pinba_address, PINBA_DEFAULT_ADDRESS);
529   pinba_port = PINBA_DEFAULT_PORT;
530   
531   for (i = 0; i < ci->children_num; i++) {
532     oconfig_item_t *child = ci->children + i;
533     if (strcasecmp ("Address", child->key) == 0) {
534       if ((child->values_num != 1) || (child->values[0].type != OCONFIG_TYPE_STRING)){
535         WARNING ("pinba plugin: `Address' needs exactly one string argument.");
536         return (-1);
537       }
538       config_set(&pinba_address, child->values[0].value.string);
539     } else if (strcasecmp ("Port", child->key) == 0) {
540       if ((child->values_num != 1) || (child->values[0].type != OCONFIG_TYPE_NUMBER)){
541         WARNING ("pinba plugin: `Port' needs exactly one number argument.");
542         return (-1);
543       }
544       pinba_port=child->values[0].value.number;
545     } else if (strcasecmp ("View", child->key) == 0) {
546       const char *name=NULL, *host=NULL, *server=NULL, *script=NULL;
547       if ((child->values_num != 1) || (child->values[0].type != OCONFIG_TYPE_STRING) || strlen(child->values[0].value.string)==0){
548         WARNING ("pinba plugin: `View' needs exactly one non-empty string argument.");
549         return (-1);
550       }
551       name = child->values[0].value.string;
552       for(o=0; o<child->children_num; o++){
553         oconfig_item_t *node = child->children + o;
554         if (strcasecmp ("Host", node->key) == 0) {
555           if ((node->values_num != 1) || (node->values[0].type != OCONFIG_TYPE_STRING) || strlen(node->values[0].value.string)==0){
556             WARNING ("pinba plugin: `View->Host' needs exactly one non-empty string argument.");
557             return (-1);
558           }
559           host = node->values[0].value.string;
560         } else if (strcasecmp ("Server", node->key) == 0) {
561           if ((node->values_num != 1) || (node->values[0].type != OCONFIG_TYPE_STRING) || strlen(node->values[0].value.string)==0){
562             WARNING ("pinba plugin: `View->Server' needs exactly one non-empty string argument.");
563             return (-1);
564           }
565           server = node->values[0].value.string;
566         } else if (strcasecmp ("Script", node->key) == 0) {
567           if ((node->values_num != 1) || (node->values[0].type != OCONFIG_TYPE_STRING) || strlen(node->values[0].value.string)==0){
568             WARNING ("pinba plugin: `View->Script' needs exactly one non-empty string argument.");
569             return (-1);
570           }
571           script = node->values[0].value.string;
572         } else {
573           WARNING ("pinba plugin: In `<View>' context allowed only `Host', `Server' and `Script' options but not the `%s'.", node->key);
574           return (-1);
575         }
576       }
577       /* add new statnode */
578       service_statnode_add(name, host, server, script);
579     } else {
580       WARNING ("pinba plugin: In `<Plugin pinba>' context allowed only `Address', `Port' and `Observe' options but not the `%s'.", child->key);
581       return (-1);
582     }
583   }
584   
585   service_statnode_end();
586   
587   service_config(pinba_address, pinba_port);
588 } /* int pinba_config */
589
590 static int
591 plugin_init (void) {
592   INFO("Pinba Starting..");
593   service_start();
594   return 0;
595 }
596
597 static int
598 plugin_shutdown (void) {
599   INFO("Pinba Stopping..");
600   service_stop();
601   service_statnode_free();
602   return 0;
603 }
604
605 static int
606 plugin_submit (const char *plugin_instance,
607                const char *type,
608                const pinba_statres *res) {
609   value_t values[6];
610   value_list_t vl = VALUE_LIST_INIT;
611   
612   values[0].gauge = res->req_per_sec;
613   values[1].gauge = res->req_time;
614   values[2].gauge = res->ru_utime;
615   values[3].gauge = res->ru_stime;
616   values[4].gauge = res->doc_size;
617   values[5].gauge = res->mem_peak;
618   
619   vl.values = values;
620   vl.values_len = 6;
621   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
622   sstrncpy (vl.plugin, "pinba", sizeof (vl.plugin));
623   sstrncpy (vl.plugin_instance, plugin_instance,
624             sizeof(vl.plugin_instance));
625   sstrncpy (vl.type, type, sizeof (vl.type));
626   INFO("Pinba Dispatch");
627   plugin_dispatch_values (&vl);
628
629   return (0);
630 }
631
632 static int plugin_read (void)
633 {
634   unsigned int i=0;
635   static pinba_statres res;
636   
637   while ((i = service_statnode_collect (&res, i)) != 0)
638   {
639     plugin_submit(res.name, "pinba_view", &res);
640   }
641   
642   return 0;
643 }
644
645 void module_register (void) {
646   plugin_register_complex_config ("pinba", plugin_config);
647   plugin_register_init ("pinba", plugin_init);
648   plugin_register_read ("pinba", plugin_read);
649   plugin_register_shutdown ("pinba", plugin_shutdown);
650 } /* void module_register */
651
652 /* vim: set sw=2 sts=2 et : */