Merge branch 'collectd-5.8'
[collectd.git] / src / apache.c
1 /**
2  * collectd - src/apache.c
3  * Copyright (C) 2006-2010  Florian octo Forster
4  * Copyright (C) 2007       Florent EppO Monbillard
5  * Copyright (C) 2009       Amit Gupta
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  *   Florian octo Forster <octo at collectd.org>
22  *   Florent EppO Monbillard <eppo at darox.net>
23  *   - connections/lighttpd extension
24  *   Amit Gupta <amit.gupta221 at gmail.com>
25  **/
26
27 #include "collectd.h"
28
29 #include "common.h"
30 #include "plugin.h"
31
32 #include <curl/curl.h>
33
34 enum server_enum { APACHE = 0, LIGHTTPD };
35
36 struct apache_s {
37   int server_type;
38   char *name;
39   char *host;
40   char *url;
41   char *user;
42   char *pass;
43   bool verify_peer;
44   bool verify_host;
45   char *cacert;
46   char *ssl_ciphers;
47   char *server; /* user specific server type */
48   char *apache_buffer;
49   char apache_curl_error[CURL_ERROR_SIZE];
50   size_t apache_buffer_size;
51   size_t apache_buffer_fill;
52   int timeout;
53   CURL *curl;
54 }; /* apache_s */
55
56 typedef struct apache_s apache_t;
57
58 /* TODO: Remove this prototype */
59 static int apache_read_host(user_data_t *user_data);
60
61 static void apache_free(void *arg) {
62   apache_t *st = arg;
63
64   if (st == NULL)
65     return;
66
67   sfree(st->name);
68   sfree(st->host);
69   sfree(st->url);
70   sfree(st->user);
71   sfree(st->pass);
72   sfree(st->cacert);
73   sfree(st->ssl_ciphers);
74   sfree(st->server);
75   sfree(st->apache_buffer);
76   if (st->curl) {
77     curl_easy_cleanup(st->curl);
78     st->curl = NULL;
79   }
80   sfree(st);
81 } /* apache_free */
82
83 static size_t apache_curl_callback(void *buf, size_t size, size_t nmemb,
84                                    void *user_data) {
85   apache_t *st = user_data;
86   if (st == NULL) {
87     ERROR("apache plugin: apache_curl_callback: "
88           "user_data pointer is NULL.");
89     return 0;
90   }
91
92   size_t len = size * nmemb;
93   if (len == 0)
94     return len;
95
96   if ((st->apache_buffer_fill + len) >= st->apache_buffer_size) {
97     char *temp = realloc(st->apache_buffer, st->apache_buffer_fill + len + 1);
98     if (temp == NULL) {
99       ERROR("apache plugin: realloc failed.");
100       return 0;
101     }
102     st->apache_buffer = temp;
103     st->apache_buffer_size = st->apache_buffer_fill + len + 1;
104   }
105
106   memcpy(st->apache_buffer + st->apache_buffer_fill, (char *)buf, len);
107   st->apache_buffer_fill += len;
108   st->apache_buffer[st->apache_buffer_fill] = 0;
109
110   return len;
111 } /* int apache_curl_callback */
112
113 static size_t apache_header_callback(void *buf, size_t size, size_t nmemb,
114                                      void *user_data) {
115   apache_t *st = user_data;
116   if (st == NULL) {
117     ERROR("apache plugin: apache_header_callback: "
118           "user_data pointer is NULL.");
119     return 0;
120   }
121
122   size_t len = size * nmemb;
123   if (len == 0)
124     return len;
125
126   /* look for the Server header */
127   if (strncasecmp(buf, "Server: ", strlen("Server: ")) != 0)
128     return len;
129
130   if (strstr(buf, "Apache") != NULL)
131     st->server_type = APACHE;
132   else if (strstr(buf, "lighttpd") != NULL)
133     st->server_type = LIGHTTPD;
134   else if (strstr(buf, "IBM_HTTP_Server") != NULL)
135     st->server_type = APACHE;
136   else {
137     const char *hdr = buf;
138
139     hdr += strlen("Server: ");
140     NOTICE("apache plugin: Unknown server software: %s", hdr);
141   }
142
143   return len;
144 } /* apache_header_callback */
145
146 /* Configuration handling functiions
147  * <Plugin apache>
148  *   <Instance "instance_name">
149  *     URL ...
150  *   </Instance>
151  *   URL ...
152  * </Plugin>
153  */
154 static int config_add(oconfig_item_t *ci) {
155   apache_t *st = calloc(1, sizeof(*st));
156   if (st == NULL) {
157     ERROR("apache plugin: calloc failed.");
158     return -1;
159   }
160
161   st->timeout = -1;
162
163   int status = cf_util_get_string(ci, &st->name);
164   if (status != 0) {
165     sfree(st);
166     return status;
167   }
168   assert(st->name != NULL);
169
170   for (int i = 0; i < ci->children_num; i++) {
171     oconfig_item_t *child = ci->children + i;
172
173     if (strcasecmp("URL", child->key) == 0)
174       status = cf_util_get_string(child, &st->url);
175     else if (strcasecmp("Host", child->key) == 0)
176       status = cf_util_get_string(child, &st->host);
177     else if (strcasecmp("User", child->key) == 0)
178       status = cf_util_get_string(child, &st->user);
179     else if (strcasecmp("Password", child->key) == 0)
180       status = cf_util_get_string(child, &st->pass);
181     else if (strcasecmp("VerifyPeer", child->key) == 0)
182       status = cf_util_get_boolean(child, &st->verify_peer);
183     else if (strcasecmp("VerifyHost", child->key) == 0)
184       status = cf_util_get_boolean(child, &st->verify_host);
185     else if (strcasecmp("CACert", child->key) == 0)
186       status = cf_util_get_string(child, &st->cacert);
187     else if (strcasecmp("SSLCiphers", child->key) == 0)
188       status = cf_util_get_string(child, &st->ssl_ciphers);
189     else if (strcasecmp("Server", child->key) == 0)
190       status = cf_util_get_string(child, &st->server);
191     else if (strcasecmp("Timeout", child->key) == 0)
192       status = cf_util_get_int(child, &st->timeout);
193     else {
194       WARNING("apache plugin: Option `%s' not allowed here.", child->key);
195       status = -1;
196     }
197
198     if (status != 0)
199       break;
200   }
201
202   /* Check if struct is complete.. */
203   if ((status == 0) && (st->url == NULL)) {
204     ERROR("apache plugin: Instance `%s': "
205           "No URL has been configured.",
206           st->name);
207     status = -1;
208   }
209
210   if (status != 0) {
211     apache_free(st);
212     return -1;
213   }
214
215   char callback_name[3 * DATA_MAX_NAME_LEN];
216
217   snprintf(callback_name, sizeof(callback_name), "apache/%s/%s",
218            (st->host != NULL) ? st->host : hostname_g,
219            (st->name != NULL) ? st->name : "default");
220
221   return plugin_register_complex_read(
222       /* group = */ NULL,
223       /* name      = */ callback_name,
224       /* callback  = */ apache_read_host,
225       /* interval  = */ 0,
226       &(user_data_t){
227           .data = st, .free_func = apache_free,
228       });
229 } /* int config_add */
230
231 static int config(oconfig_item_t *ci) {
232   for (int i = 0; i < ci->children_num; i++) {
233     oconfig_item_t *child = ci->children + i;
234
235     if (strcasecmp("Instance", child->key) == 0)
236       config_add(child);
237     else
238       WARNING("apache plugin: The configuration option "
239               "\"%s\" is not allowed here. Did you "
240               "forget to add an <Instance /> block "
241               "around the configuration?",
242               child->key);
243   } /* for (ci->children) */
244
245   return 0;
246 } /* int config */
247
248 /* initialize curl for each host */
249 static int init_host(apache_t *st) /* {{{ */
250 {
251   assert(st->url != NULL);
252   /* (Assured by `config_add') */
253
254   if (st->curl != NULL) {
255     curl_easy_cleanup(st->curl);
256     st->curl = NULL;
257   }
258
259   if ((st->curl = curl_easy_init()) == NULL) {
260     ERROR("apache plugin: init_host: `curl_easy_init' failed.");
261     return -1;
262   }
263
264   curl_easy_setopt(st->curl, CURLOPT_NOSIGNAL, 1L);
265   curl_easy_setopt(st->curl, CURLOPT_WRITEFUNCTION, apache_curl_callback);
266   curl_easy_setopt(st->curl, CURLOPT_WRITEDATA, st);
267
268   /* not set as yet if the user specified string doesn't match apache or
269    * lighttpd, then ignore it. Headers will be parsed to find out the
270    * server type */
271   st->server_type = -1;
272
273   if (st->server != NULL) {
274     if (strcasecmp(st->server, "apache") == 0)
275       st->server_type = APACHE;
276     else if (strcasecmp(st->server, "lighttpd") == 0)
277       st->server_type = LIGHTTPD;
278     else if (strcasecmp(st->server, "ibm_http_server") == 0)
279       st->server_type = APACHE;
280     else
281       WARNING("apache plugin: Unknown `Server' setting: %s", st->server);
282   }
283
284   /* if not found register a header callback to determine the server_type */
285   if (st->server_type == -1) {
286     curl_easy_setopt(st->curl, CURLOPT_HEADERFUNCTION, apache_header_callback);
287     curl_easy_setopt(st->curl, CURLOPT_WRITEHEADER, st);
288   }
289
290   curl_easy_setopt(st->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
291   curl_easy_setopt(st->curl, CURLOPT_ERRORBUFFER, st->apache_curl_error);
292
293   if (st->user != NULL) {
294 #ifdef HAVE_CURLOPT_USERNAME
295     curl_easy_setopt(st->curl, CURLOPT_USERNAME, st->user);
296     curl_easy_setopt(st->curl, CURLOPT_PASSWORD,
297                      (st->pass == NULL) ? "" : st->pass);
298 #else
299     static char credentials[1024];
300     int status = snprintf(credentials, sizeof(credentials), "%s:%s", st->user,
301                           (st->pass == NULL) ? "" : st->pass);
302     if ((status < 0) || ((size_t)status >= sizeof(credentials))) {
303       ERROR("apache plugin: init_host: Returning an error "
304             "because the credentials have been "
305             "truncated.");
306       curl_easy_cleanup(st->curl);
307       st->curl = NULL;
308       return -1;
309     }
310
311     curl_easy_setopt(st->curl, CURLOPT_USERPWD, credentials);
312 #endif
313   }
314
315   curl_easy_setopt(st->curl, CURLOPT_FOLLOWLOCATION, 1L);
316   curl_easy_setopt(st->curl, CURLOPT_MAXREDIRS, 50L);
317
318   curl_easy_setopt(st->curl, CURLOPT_SSL_VERIFYPEER, (long)st->verify_peer);
319   curl_easy_setopt(st->curl, CURLOPT_SSL_VERIFYHOST, st->verify_host ? 2L : 0L);
320   if (st->cacert != NULL)
321     curl_easy_setopt(st->curl, CURLOPT_CAINFO, st->cacert);
322   if (st->ssl_ciphers != NULL)
323     curl_easy_setopt(st->curl, CURLOPT_SSL_CIPHER_LIST, st->ssl_ciphers);
324
325 #ifdef HAVE_CURLOPT_TIMEOUT_MS
326   if (st->timeout >= 0)
327     curl_easy_setopt(st->curl, CURLOPT_TIMEOUT_MS, (long)st->timeout);
328   else
329     curl_easy_setopt(st->curl, CURLOPT_TIMEOUT_MS,
330                      (long)CDTIME_T_TO_MS(plugin_get_interval()));
331 #endif
332
333   return 0;
334 } /* }}} int init_host */
335
336 static void submit_value(const char *type, const char *type_instance,
337                          value_t value, apache_t *st) {
338   value_list_t vl = VALUE_LIST_INIT;
339
340   vl.values = &value;
341   vl.values_len = 1;
342
343   if (st->host != NULL)
344     sstrncpy(vl.host, st->host, sizeof(vl.host));
345
346   sstrncpy(vl.plugin, "apache", sizeof(vl.plugin));
347   if (st->name != NULL)
348     sstrncpy(vl.plugin_instance, st->name, sizeof(vl.plugin_instance));
349
350   sstrncpy(vl.type, type, sizeof(vl.type));
351   if (type_instance != NULL)
352     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
353
354   plugin_dispatch_values(&vl);
355 } /* void submit_value */
356
357 static void submit_derive(const char *type, const char *type_instance,
358                           derive_t d, apache_t *st) {
359   submit_value(type, type_instance, (value_t){.derive = d}, st);
360 } /* void submit_derive */
361
362 static void submit_gauge(const char *type, const char *type_instance, gauge_t g,
363                          apache_t *st) {
364   submit_value(type, type_instance, (value_t){.gauge = g}, st);
365 } /* void submit_gauge */
366
367 static void submit_scoreboard(char *buf, apache_t *st) {
368   /*
369    * Scoreboard Key:
370    * "_" Waiting for Connection, "S" Starting up,
371    * "R" Reading Request for apache and read-POST for lighttpd,
372    * "W" Sending Reply, "K" Keepalive (read), "D" DNS Lookup,
373    * "C" Closing connection, "L" Logging, "G" Gracefully finishing,
374    * "I" Idle cleanup of worker, "." Open slot with no current process
375    * Lighttpd specific legends -
376    * "E" hard error, "." connect, "h" handle-request,
377    * "q" request-start, "Q" request-end, "s" response-start
378    * "S" response-end, "r" read
379    */
380   long long open = 0LL;
381   long long waiting = 0LL;
382   long long starting = 0LL;
383   long long reading = 0LL;
384   long long sending = 0LL;
385   long long keepalive = 0LL;
386   long long dnslookup = 0LL;
387   long long closing = 0LL;
388   long long logging = 0LL;
389   long long finishing = 0LL;
390   long long idle_cleanup = 0LL;
391
392   /* lighttpd specific */
393   long long hard_error = 0LL;
394   long long lighttpd_read = 0LL;
395   long long handle_request = 0LL;
396   long long request_start = 0LL;
397   long long request_end = 0LL;
398   long long response_start = 0LL;
399   long long response_end = 0LL;
400
401   for (int i = 0; buf[i] != '\0'; i++) {
402     if (buf[i] == '.')
403       open++;
404     else if (buf[i] == '_')
405       waiting++;
406     else if (buf[i] == 'S')
407       starting++;
408     else if (buf[i] == 'R')
409       reading++;
410     else if (buf[i] == 'W')
411       sending++;
412     else if (buf[i] == 'K')
413       keepalive++;
414     else if (buf[i] == 'D')
415       dnslookup++;
416     else if (buf[i] == 'C')
417       closing++;
418     else if (buf[i] == 'L')
419       logging++;
420     else if (buf[i] == 'G')
421       finishing++;
422     else if (buf[i] == 'I')
423       idle_cleanup++;
424     else if (buf[i] == 'r')
425       lighttpd_read++;
426     else if (buf[i] == 'h')
427       handle_request++;
428     else if (buf[i] == 'E')
429       hard_error++;
430     else if (buf[i] == 'q')
431       request_start++;
432     else if (buf[i] == 'Q')
433       request_end++;
434     else if (buf[i] == 's')
435       response_start++;
436     else if (buf[i] == 'S')
437       response_end++;
438   }
439
440   if (st->server_type == APACHE) {
441     submit_gauge("apache_scoreboard", "open", open, st);
442     submit_gauge("apache_scoreboard", "waiting", waiting, st);
443     submit_gauge("apache_scoreboard", "starting", starting, st);
444     submit_gauge("apache_scoreboard", "reading", reading, st);
445     submit_gauge("apache_scoreboard", "sending", sending, st);
446     submit_gauge("apache_scoreboard", "keepalive", keepalive, st);
447     submit_gauge("apache_scoreboard", "dnslookup", dnslookup, st);
448     submit_gauge("apache_scoreboard", "closing", closing, st);
449     submit_gauge("apache_scoreboard", "logging", logging, st);
450     submit_gauge("apache_scoreboard", "finishing", finishing, st);
451     submit_gauge("apache_scoreboard", "idle_cleanup", idle_cleanup, st);
452   } else {
453     submit_gauge("apache_scoreboard", "connect", open, st);
454     submit_gauge("apache_scoreboard", "close", closing, st);
455     submit_gauge("apache_scoreboard", "hard_error", hard_error, st);
456     submit_gauge("apache_scoreboard", "read", lighttpd_read, st);
457     submit_gauge("apache_scoreboard", "read_post", reading, st);
458     submit_gauge("apache_scoreboard", "write", sending, st);
459     submit_gauge("apache_scoreboard", "handle_request", handle_request, st);
460     submit_gauge("apache_scoreboard", "request_start", request_start, st);
461     submit_gauge("apache_scoreboard", "request_end", request_end, st);
462     submit_gauge("apache_scoreboard", "response_start", response_start, st);
463     submit_gauge("apache_scoreboard", "response_end", response_end, st);
464   }
465 }
466
467 static int apache_read_host(user_data_t *user_data) /* {{{ */
468 {
469   apache_t *st = user_data->data;
470
471   assert(st->url != NULL);
472   /* (Assured by `config_add') */
473
474   if (st->curl == NULL) {
475     if (init_host(st) != 0)
476       return -1;
477   }
478   assert(st->curl != NULL);
479
480   st->apache_buffer_fill = 0;
481
482   curl_easy_setopt(st->curl, CURLOPT_URL, st->url);
483
484   if (curl_easy_perform(st->curl) != CURLE_OK) {
485     ERROR("apache: curl_easy_perform failed: %s", st->apache_curl_error);
486     return -1;
487   }
488
489   /* fallback - server_type to apache if not set at this time */
490   if (st->server_type == -1) {
491     WARNING("apache plugin: Unable to determine server software "
492             "automatically. Will assume Apache.");
493     st->server_type = APACHE;
494   }
495
496   char *content_type;
497   static const char *text_plain = "text/plain";
498   int status =
499       curl_easy_getinfo(st->curl, CURLINFO_CONTENT_TYPE, &content_type);
500   if ((status == CURLE_OK) && (content_type != NULL) &&
501       (strncasecmp(content_type, text_plain, strlen(text_plain)) != 0)) {
502     WARNING("apache plugin: `Content-Type' response header is not `%s' "
503             "(received: `%s'). Expecting unparseable data. Please check `URL' "
504             "parameter (missing `?auto' suffix ?)",
505             text_plain, content_type);
506   }
507
508   char *ptr = st->apache_buffer;
509   char *saveptr = NULL;
510   char *line;
511   while ((line = strtok_r(ptr, "\n\r", &saveptr)) != NULL) {
512     ptr = NULL;
513     char *fields[4];
514
515     int fields_num = strsplit(line, fields, STATIC_ARRAY_SIZE(fields));
516
517     if (fields_num == 3) {
518       if ((strcmp(fields[0], "Total") == 0) &&
519           (strcmp(fields[1], "Accesses:") == 0))
520         submit_derive("apache_requests", "", atoll(fields[2]), st);
521       else if ((strcmp(fields[0], "Total") == 0) &&
522                (strcmp(fields[1], "kBytes:") == 0))
523         submit_derive("apache_bytes", "", 1024LL * atoll(fields[2]), st);
524     } else if (fields_num == 2) {
525       if (strcmp(fields[0], "Scoreboard:") == 0)
526         submit_scoreboard(fields[1], st);
527       else if ((strcmp(fields[0], "BusyServers:") == 0) /* Apache 1.* */
528                || (strcmp(fields[0], "BusyWorkers:") == 0) /* Apache 2.* */)
529         submit_gauge("apache_connections", NULL, atol(fields[1]), st);
530       else if ((strcmp(fields[0], "IdleServers:") == 0) /* Apache 1.x */
531                || (strcmp(fields[0], "IdleWorkers:") == 0) /* Apache 2.x */)
532         submit_gauge("apache_idle_workers", NULL, atol(fields[1]), st);
533     }
534   }
535
536   st->apache_buffer_fill = 0;
537
538   return 0;
539 } /* }}} int apache_read_host */
540
541 static int apache_init(void) /* {{{ */
542 {
543   /* Call this while collectd is still single-threaded to avoid
544    * initialization issues in libgcrypt. */
545   curl_global_init(CURL_GLOBAL_SSL);
546   return 0;
547 } /* }}} int apache_init */
548
549 void module_register(void) {
550   plugin_register_complex_config("apache", config);
551   plugin_register_init("apache", apache_init);
552 } /* void module_register */