root/src/modules/http.c

Revision c39dbcdedc357e87352f7eb1438aa96afdcbd09e, 28.7 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 7 years ago)

make the loading mechanism generic so that we can load something other than checkers. refs #28

  • Property mode set to 100644
Line 
1 /*
2  * Copyright (c) 2007, OmniTI Computer Consulting, Inc.
3  * All rights reserved.
4  */
5
6 #include "noit_defines.h"
7
8 #include <stdio.h>
9 #include <unistd.h>
10 #include <errno.h>
11 #include <assert.h>
12 #include <math.h>
13
14 #include <libxml/parser.h>
15 #include <libxml/tree.h>
16 #include <libxml/xpath.h>
17
18 #include "noit_module.h"
19 #include "noit_check.h"
20 #include "noit_check_tools.h"
21 #include "utils/noit_log.h"
22 #include "utils/noit_hash.h"
23
24 #include <apr_uri.h>
25 #include <apr_atomic.h>
26 #include <apr_strings.h>
27 #include "serf.h"
28
29 #define NOIT_HTTP_VERSION_STRING "0.1"
30
31 typedef struct {
32   noit_hash_table *options;
33   void (*results)(noit_module_t *, noit_check_t *);
34 } serf_module_conf_t;
35
36 typedef struct {
37   int using_ssl;
38   const char *ca_chain_file;
39   const char *certificate_file;
40   serf_ssl_context_t *ssl_ctx;
41   serf_bucket_alloc_t *bkt_alloc;
42 } app_baton_t;
43
44 typedef struct {
45   serf_response_acceptor_t acceptor;
46   app_baton_t *acceptor_baton;
47
48   serf_response_handler_t handler;
49   const char *host;
50   const char *method;
51   const char *path;
52   const char *authn;
53
54   noit_module_t *self;
55   noit_check_t *check;
56 } handler_baton_t;
57
58 typedef struct buf_t {
59   char *b;
60   int32_t l;
61 } buf_t;
62
63 typedef struct {
64   apr_pool_t *pool;
65   apr_sockaddr_t *address;
66   serf_context_t *context;
67   serf_connection_t *connection;
68   serf_request_t *request;
69   app_baton_t app_ctx;
70   handler_baton_t handler_ctx;
71   apr_uri_t url;
72   int timed_out;
73
74   serf_status_line status;
75   buf_t headers;
76   buf_t body;
77
78   struct timeval finish_time;
79   eventer_t fd_event;
80   eventer_t timeout_event;
81 } serf_check_info_t;
82
83 typedef struct {
84   serf_check_info_t serf;
85   struct timeval xml_doc_time;
86   char *xpathexpr;
87   xmlDocPtr xml_doc;
88   char *resmod;
89   char *resserv;
90 } resmon_check_info_t;
91
92 typedef struct {
93   noit_module_t *self;
94   noit_check_t *check;
95   void *serf_baton;
96   apr_socket_t *skt;
97 } serf_closure_t;
98
99 static noit_log_stream_t nlerr = NULL;
100 static noit_log_stream_t nldeb = NULL;
101 static int serf_handler(eventer_t e, int mask, void *closure,
102                         struct timeval *now);
103 static void serf_log_results(noit_module_t *self, noit_check_t *check);
104 static void resmon_log_results(noit_module_t *self, noit_check_t *check);
105 static void resmon_part_log_results(noit_module_t *self, noit_check_t *check,
106                                     noit_check_t *parent);
107
108 static int serf_config(noit_module_t *self, noit_hash_table *options) {
109   serf_module_conf_t *conf;
110   conf = noit_module_get_userdata(self);
111   if(conf) {
112     if(conf->options) {
113       noit_hash_destroy(conf->options, free, free);
114       free(conf->options);
115     }
116   }
117   else
118     conf = calloc(1, sizeof(*conf));
119   conf->options = options;
120   conf->results = serf_log_results;
121   noit_module_set_userdata(self, conf);
122   return 1;
123 }
124 static int resmon_config(noit_module_t *self, noit_hash_table *options) {
125   serf_module_conf_t *conf;
126   conf = noit_module_get_userdata(self);
127   if(conf) {
128     if(conf->options) {
129       noit_hash_destroy(conf->options, free, free);
130       free(conf->options);
131     }
132   }
133   else
134     conf = calloc(1, sizeof(*conf));
135   conf->options = options;
136   if(!conf->options) conf->options = calloc(1, sizeof(*conf->options));
137   noit_hash_store(conf->options, strdup("url"), strlen("url"),
138                   strdup("http://localhost:81/"));
139   conf->results = resmon_log_results;
140   noit_module_set_userdata(self, conf);
141   return 1;
142 }
143 static void generic_log_results(noit_module_t *self, noit_check_t *check) {
144   serf_module_conf_t *module_conf;
145   module_conf = noit_module_get_userdata(self);
146   module_conf->results(self, check);
147 }
148 static void serf_log_results(noit_module_t *self, noit_check_t *check) {
149   serf_check_info_t *ci = check->closure;
150   struct timeval duration;
151   stats_t current;
152   int expect_code = 200;
153   u_int32_t duration_ms;
154   void *code_str; /* void * for use with hash */
155   char human_buffer[256], code[4], rt[14];
156
157   noit_check_stats_clear(&current);
158
159   if(noit_hash_retrieve(check->config, "code", strlen("code"), &code_str))
160     expect_code = atoi((const char *)code_str);
161
162   sub_timeval(ci->finish_time, check->last_fire_time, &duration);
163
164   snprintf(code, sizeof(code), "%3d", ci->status.code);
165   snprintf(rt, sizeof(rt), "%.3fs",
166            (float)duration.tv_sec + (float)duration.tv_usec / 1000000.0);
167   snprintf(human_buffer, sizeof(human_buffer),
168            "code=%s,rt=%s,bytes=%d",
169            ci->status.code ? code : "undefined",
170            ci->timed_out ? "timeout" : rt,
171            ci->body.l);
172   noitL(nldeb, "http(%s) [%s]\n", check->target, human_buffer);
173
174   memcpy(&current.whence, &ci->finish_time, sizeof(current.whence));
175   current.duration = duration.tv_sec * 1000 + duration.tv_usec / 1000;
176   duration_ms = current.duration;
177   current.available = (ci->timed_out || !ci->status.code) ? NP_UNAVAILABLE : NP_AVAILABLE;
178   current.state = (ci->status.code != 200) ? NP_BAD : NP_GOOD;
179   current.status = human_buffer;
180   if(current.available == NP_AVAILABLE) {
181     noit_stats_set_metric(&current, "code",
182                           METRIC_STRING, ci->status.code?code:NULL);
183     noit_stats_set_metric(&current, "bytes",
184                           METRIC_INT32, &ci->body.l);
185     noit_stats_set_metric(&current, "duration",
186                           METRIC_UINT32, &duration_ms);
187   }
188   else {
189     noit_stats_set_metric(&current, "code", METRIC_STRING, NULL);
190     noit_stats_set_metric(&current, "bytes", METRIC_INT32, NULL);
191     noit_stats_set_metric(&current, "duration", METRIC_UINT32, NULL);
192   }
193   noit_check_set_stats(self, check, &current);
194 }
195 static void resmon_part_log_results_xml(noit_module_t *self,
196                                         noit_check_t *check,
197                                         xmlDocPtr xml) {
198   serf_check_info_t *ci = check->closure;
199   resmon_check_info_t *rci = check->closure;
200   xmlXPathContextPtr xpath_ctxt = NULL;
201   stats_t current;
202
203   noit_check_stats_clear(&current);
204   memcpy(&current.whence, &ci->finish_time, sizeof(current.whence));
205   current.available = NP_UNAVAILABLE;
206   current.state = NP_BAD;
207
208   if(xml && rci->xpathexpr) {
209     current.available = NP_AVAILABLE;
210     xpath_ctxt = xmlXPathNewContext(xml);
211     if(xpath_ctxt) {
212       xmlXPathObjectPtr pobj;
213       pobj = xmlXPathEval((xmlChar *)rci->xpathexpr, xpath_ctxt);
214       if(pobj) {
215         int i, cnt;
216         cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
217         for(i=0; i<cnt; i++) {
218           xmlNodePtr node;
219           char *value;
220           node = xmlXPathNodeSetItem(pobj->nodesetval, i);
221           value = (char *)xmlXPathCastNodeToString(node);
222           if(!strcmp((char *)node->name,"last_runtime_seconds")) {
223             float duration = atof(value) * 1000;
224             current.duration = (int) duration;
225           }
226           else if(!strcmp((char *)node->name, "message")) {
227             current.status = strdup(value);
228           }
229           else if(!strcmp((char *)node->name, "state")) {
230             current.state = strcmp(value,"OK") ? NP_BAD : NP_GOOD;
231           }
232           xmlFree(value);
233         }
234         xmlXPathFreeObject(pobj);
235       }
236       xmlXPathFreeContext(xpath_ctxt);
237     }
238   }
239   memcpy(&current.whence, &rci->serf.finish_time, sizeof(current.whence));
240   current.status = current.status ? current.status : strdup("unknown");
241   noitL(nldeb, "resmon_part(%s/%s/%s) [%s]\n", check->target,
242         rci->resmod, rci->resserv, current.status);
243   noit_check_set_stats(self, check, &current);
244   free(current.status);
245 }
246 static void resmon_part_log_results(noit_module_t *self, noit_check_t *check,
247                                     noit_check_t *parent) {
248   resmon_check_info_t *rci = parent->closure;
249   resmon_part_log_results_xml(self, check, rci->xml_doc);
250 }
251 static void resmon_log_results(noit_module_t *self, noit_check_t *check) {
252   serf_check_info_t *ci = check->closure;
253   resmon_check_info_t *rci = check->closure;
254   struct timeval duration;
255   stats_t current;
256   int32_t services = 0;
257   char human_buffer[256], rt[14];
258   xmlDocPtr resmon_results = NULL;
259   xmlXPathContextPtr xpath_ctxt = NULL;
260   xmlXPathObjectPtr pobj = NULL;
261
262   noit_check_stats_clear(&current);
263
264   if(ci->body.b) resmon_results = xmlParseMemory(ci->body.b, ci->body.l);
265   if(resmon_results) {
266     xpath_ctxt = xmlXPathNewContext(resmon_results);
267     pobj = xmlXPathEval((xmlChar *)"/ResmonResults/ResmonResult", xpath_ctxt);
268     if(pobj)
269       if(pobj->type == XPATH_NODESET)
270         services = xmlXPathNodeSetGetLength(pobj->nodesetval);
271   } else {
272     if(ci->body.l)
273       noitL(nlerr, "Error in resmon doc: %s\n", ci->body.b);
274   }
275
276   /* Save our results for future dependent checks */
277   memcpy(&current.whence, &ci->finish_time, sizeof(current.whence));
278   memcpy(&rci->xml_doc_time, &ci->finish_time, sizeof(ci->finish_time));
279   if(rci->xml_doc) xmlFreeDoc(rci->xml_doc);
280   rci->xml_doc = resmon_results;
281
282   if(rci->xpathexpr) {
283     /* This is actually a part check... we had to do all the work as
284      * it isn't being used as a causal firing from a generic resmon check
285      */
286     resmon_part_log_results_xml(self, check, rci->xml_doc);
287     goto out;
288   }
289
290   sub_timeval(ci->finish_time, check->last_fire_time, &duration);
291   snprintf(rt, sizeof(rt), "%.3fs",
292            (float)duration.tv_sec + (float)duration.tv_usec / 1000000.0);
293   snprintf(human_buffer, sizeof(human_buffer),
294            "services=%d,rt=%s",
295            services,
296            ci->timed_out ? "timeout" : rt);
297   noitL(nldeb, "resmon(%s) [%s]\n", check->target, human_buffer);
298
299   current.duration = duration.tv_sec * 1000 + duration.tv_usec / 1000;
300   current.available = (ci->timed_out || ci->status.code != 200) ?
301                           NP_UNAVAILABLE : NP_AVAILABLE;
302   current.state = services ? NP_GOOD : NP_BAD;
303   current.status = human_buffer;
304
305   noit_stats_set_metric(&current, "services", METRIC_INT32, &services);
306   if(services) {
307     int i;
308     for(i=0; i<services; i++) {
309       xmlNodePtr node, attrnode;
310       node = xmlXPathNodeSetItem(pobj->nodesetval, i);
311       if(node) {
312         int a;
313         char *attrs[3] = { "last_runtime_seconds", "state", "message" };
314         char *resmod = NULL, *resserv = NULL, *value = NULL;
315         char attr[1024];
316         xmlXPathObjectPtr sobj;
317
318         xpath_ctxt->node = node;
319         sobj = xmlXPathEval((xmlChar *)"@module", xpath_ctxt);
320         if(sobj) {
321           resmod = (char *)xmlXPathCastNodeSetToString(sobj->nodesetval);
322           xmlXPathFreeObject(sobj);
323         }
324         sobj = xmlXPathEval((xmlChar *)"@service", xpath_ctxt);
325         if(sobj) {
326           resserv = (char *)xmlXPathCastNodeSetToString(sobj->nodesetval);
327           xmlXPathFreeObject(sobj);
328         }
329         if(!resmod && !resserv) continue;
330
331         for(a=0; a<3; a++) {
332           int32_t intval;
333           sobj = xmlXPathEval((xmlChar *)attrs[a], xpath_ctxt);
334           attrnode = xmlXPathNodeSetItem(sobj->nodesetval, 0);
335           value = (char *)xmlXPathCastNodeToString(attrnode);
336           xmlXPathFreeObject(sobj);
337           snprintf(attr, sizeof(attr), "%s`%s`%s",
338                    resmod, resserv, (char *)attrnode->name);
339           switch(a) {
340             case 0:
341               /* The first is integer */
342               intval = (int)(atof(value) * 1000.0);
343               noit_stats_set_metric(&current, attr, METRIC_INT32, &intval);
344               break;
345             case 1:
346               noit_stats_set_metric(&current, attr, METRIC_STRING, value);
347               break;
348             case 2:
349               noit_stats_set_metric(&current, attr, METRIC_GUESS, value);
350               break;
351           }
352           xmlFree(value);
353         }
354         if(resmod) xmlFree(resmod);
355         if(resserv) xmlFree(resserv);
356       }
357     }
358   }
359
360   noit_check_set_stats(self, check, &current);
361
362  out:
363   if(pobj) xmlXPathFreeObject(pobj);
364   if(xpath_ctxt) xmlXPathFreeContext(xpath_ctxt);
365 }
366 static void serf_cleanup(noit_module_t *self, noit_check_t *check) {
367   serf_check_info_t *ci;
368   ci = check->closure;
369   if(ci->connection) {
370     serf_connection_close(ci->connection);
371     ci->connection = NULL;
372   }
373   if(ci->fd_event) {
374     eventer_remove_fd(ci->fd_event->fd);
375     eventer_free(ci->fd_event);
376     ci->fd_event = NULL;
377   }
378   ci->timeout_event = NULL;
379   if(ci->pool) apr_pool_destroy(ci->pool);
380   memset(ci, 0, sizeof(*ci));
381 }
382 static int serf_complete(eventer_t e, int mask,
383                          void *closure, struct timeval *now) {
384   serf_closure_t *ccl = (serf_closure_t *)closure;
385
386   noitLT(nldeb, now, "serf_complete(%s)\n", ccl->check->target);
387   if(!NOIT_CHECK_DISABLED(ccl->check) && !NOIT_CHECK_KILLED(ccl->check)) {
388     serf_check_info_t *ci = ccl->check->closure;
389     memcpy(&ci->finish_time, now, sizeof(*now));
390     generic_log_results(ccl->self, ccl->check);
391   }
392   serf_cleanup(ccl->self, ccl->check);
393   ccl->check->flags &= ~NP_RUNNING;
394   free(ccl);
395   return 0;
396 }
397
398 static int serf_handler(eventer_t e, int mask,
399                         void *closure, struct timeval *now) {
400   apr_pollfd_t desc = { 0 };
401   serf_closure_t *sct = closure;
402   serf_check_info_t *ci = sct->check->closure;
403
404   desc.desc_type = APR_POLL_SOCKET;
405   desc.desc.s = sct->skt;
406
407   desc.rtnevents = 0;
408   if(mask & EVENTER_READ) desc.rtnevents |= APR_POLLIN;
409   if(mask & EVENTER_WRITE) desc.rtnevents |= APR_POLLOUT;
410   if(mask & EVENTER_EXCEPTION) desc.rtnevents |= APR_POLLERR;
411   serf_event_trigger(ci->context, sct->serf_baton, &desc);
412   serf_context_prerun(ci->context);
413
414   /* We're about to deschedule and free the event, drop our reference */
415   if(!e->mask)
416     ci->fd_event = NULL;
417
418   return e->mask;
419 }
420
421 static int serf_init(noit_module_t *self) {
422   return 0;
423 }
424 static void closed_connection(serf_connection_t *conn,
425                               void *closed_baton,
426                               apr_status_t why,
427                               apr_pool_t *pool) {
428 }
429 static apr_status_t need_client_cert(void *data,
430                                      const char **path) {
431   app_baton_t *ctx = data;
432   *path = ctx->certificate_file;
433   return APR_SUCCESS;
434 }
435 static apr_status_t need_server_cert(void *data,
436                                      int failures,
437                                      const serf_ssl_certificate_t *cert) {
438   return APR_SUCCESS;
439 }
440 static serf_bucket_t* conn_setup(apr_socket_t *skt,
441                                 void *setup_baton,
442                                 apr_pool_t *pool) {
443   serf_bucket_t *c;
444   app_baton_t *ctx = setup_baton;
445
446   c = serf_bucket_socket_create(skt, ctx->bkt_alloc);
447   if (ctx->using_ssl) {
448     c = serf_bucket_ssl_decrypt_create(c, ctx->ssl_ctx, ctx->bkt_alloc);
449     if (!ctx->ssl_ctx) {
450       serf_ssl_certificate_t *cert;
451       ctx->ssl_ctx = serf_bucket_ssl_decrypt_context_get(c);
452
453       /* Setup CA chain */
454       if(ctx->ca_chain_file &&
455          serf_ssl_load_cert_file(&cert, ctx->ca_chain_file,
456                                  pool) != APR_SUCCESS)
457         serf_ssl_trust_cert(ctx->ssl_ctx, cert);
458       else
459         serf_ssl_use_default_certificates(ctx->ssl_ctx);
460       serf_ssl_server_cert_callback_set(ctx->ssl_ctx, need_server_cert,
461                                         ctx);
462
463       /* Setup client cert */
464       serf_ssl_client_cert_provider_set(ctx->ssl_ctx, need_client_cert,
465                                         ctx, pool);
466     }
467   }
468
469   return c;
470 }
471
472 static serf_bucket_t* accept_response(serf_request_t *request,
473                                       serf_bucket_t *stream,
474                                       void *acceptor_baton,
475                                       apr_pool_t *pool) {
476   serf_bucket_t *c;
477   serf_bucket_alloc_t *bkt_alloc;
478
479   /* get the per-request bucket allocator */
480   bkt_alloc = serf_request_get_alloc(request);
481
482   /* Create a barrier so the response doesn't eat us! */
483   c = serf_bucket_barrier_create(stream, bkt_alloc);
484
485   return serf_bucket_response_create(c, bkt_alloc);
486 }
487
488 static void append_buf(apr_pool_t *p, buf_t *b,
489                        const char *data, int len) {
490   char *n;
491   n = apr_palloc(p, b->l + len + 1);
492   if(b->l == 0)
493     b->b = n;
494   else {
495     memcpy(n, b->b, b->l);
496     b->b = n;
497   }
498   memcpy(b->b + b->l, data, len);
499   b->l += len;
500   b->b[b->l] = '\0';
501 }
502
503 static apr_status_t handle_response(serf_request_t *request,
504                                     serf_bucket_t *response,
505                                     void *handler_baton,
506                                     apr_pool_t *pool) {
507   const char *data;
508   apr_size_t len;
509   apr_status_t status;
510   handler_baton_t *ctx = handler_baton;
511   serf_check_info_t *ci = ctx->check->closure;
512
513   if(response == NULL) {
514     /* We were cancelled. */
515     goto finish;
516   }
517   status = serf_bucket_response_status(response, &ci->status);
518   if (status) {
519     if (APR_STATUS_IS_EAGAIN(status)) {
520       return status;
521     }
522     goto finish;
523   }
524
525   while (1) {
526     status = serf_bucket_read(response, 1024*32, &data, &len);
527     if (SERF_BUCKET_READ_ERROR(status))
528       return status;
529
530     append_buf(ci->pool, &ci->body, data, len);
531
532     /* are we done yet? */
533     if (APR_STATUS_IS_EOF(status)) {
534       serf_bucket_t *hdrs;
535       hdrs = serf_bucket_response_get_headers(response);
536       while (1) {
537         status = serf_bucket_read(hdrs, 2048, &data, &len);
538         if (SERF_BUCKET_READ_ERROR(status))
539           return status;
540
541         append_buf(ci->pool, &ci->headers, data, len);
542         if (APR_STATUS_IS_EOF(status)) {
543           break;
544         }
545       }
546
547       goto finish;
548     }
549
550     /* have we drained the response so far? */
551     if (APR_STATUS_IS_EAGAIN(status))
552       return status;
553
554     /* loop to read some more. */
555   }
556  finish:
557   gettimeofday(&ci->finish_time, NULL);
558   if(ci->timeout_event) {
559     eventer_remove(ci->timeout_event);
560     ci->timed_out = 0;
561     memcpy(&ci->timeout_event->whence, &ci->finish_time,
562            sizeof(&ci->finish_time));
563     eventer_add(ci->timeout_event);
564   }
565   return APR_EOF;
566 }
567
568 static apr_status_t setup_request(serf_request_t *request,
569                                   void *setup_baton,
570                                   serf_bucket_t **req_bkt,
571                                   serf_response_acceptor_t *acceptor,                                             void **acceptor_baton,
572                                   serf_response_handler_t *handler,
573                                   void **handler_baton,
574                                   apr_pool_t *pool) {
575   handler_baton_t *ctx = setup_baton;
576   serf_bucket_t *hdrs_bkt;
577   serf_bucket_t *body_bkt;
578
579   body_bkt = NULL;
580
581   *req_bkt = serf_bucket_request_create(ctx->method, ctx->path, body_bkt,
582                                         serf_request_get_alloc(request));
583
584   hdrs_bkt = serf_bucket_request_get_headers(*req_bkt);
585
586   serf_bucket_headers_setn(hdrs_bkt, "Host", ctx->host);
587   serf_bucket_headers_setn(hdrs_bkt, "User-Agent",
588                            "Noit/" NOIT_HTTP_VERSION_STRING);
589   /* Shouldn't serf do this for us? */
590   serf_bucket_headers_setn(hdrs_bkt, "Accept-Encoding", "gzip");
591
592   if (ctx->authn != NULL) {
593     serf_bucket_headers_setn(hdrs_bkt, "Authorization", ctx->authn);
594   }
595
596   if (ctx->acceptor_baton->using_ssl) {
597     serf_bucket_alloc_t *req_alloc;
598     app_baton_t *app_ctx = ctx->acceptor_baton;
599
600     req_alloc = serf_request_get_alloc(request);
601
602     if (app_ctx->ssl_ctx == NULL) {
603       *req_bkt =
604         serf_bucket_ssl_encrypt_create(*req_bkt, NULL,
605                                        app_ctx->bkt_alloc);
606       app_ctx->ssl_ctx =
607         serf_bucket_ssl_encrypt_context_get(*req_bkt);
608     }
609     else {
610       *req_bkt =
611         serf_bucket_ssl_encrypt_create(*req_bkt, app_ctx->ssl_ctx,
612                                        app_ctx->bkt_alloc);
613     }
614   }
615
616   *acceptor = ctx->acceptor;
617   *acceptor_baton = ctx->acceptor_baton;
618   *handler = ctx->handler;
619   *handler_baton = ctx;
620
621   return APR_SUCCESS;
622 }
623
624 struct __unix_apr_socket_t {
625   apr_pool_t *pool;
626   int socketdes;
627 };
628
629 static apr_status_t serf_eventer_add(void *user_baton,
630                                      apr_pollfd_t *pfd,
631                                      void *serf_baton) {
632   eventer_t e, newe = NULL;
633   serf_closure_t *sct = user_baton, *newsct;
634   assert(pfd->desc_type == APR_POLL_SOCKET);
635   struct __unix_apr_socket_t *hack = (struct __unix_apr_socket_t *)pfd->desc.s;
636
637   noitL(nldeb, "serf_eventer_add() => %d\n", hack->socketdes);
638   e = eventer_find_fd(hack->socketdes);
639   if(!e) {
640     newe = e = eventer_alloc();
641     e->fd = hack->socketdes;
642     e->callback = serf_handler;
643   }
644   if(!e->closure)
645     e->closure = calloc(1, sizeof(serf_closure_t));
646   newsct = e->closure;
647   newsct->self = sct->self;
648   newsct->check = sct->check;
649   newsct->serf_baton = serf_baton;
650   newsct->skt = pfd->desc.s;
651   e->mask = 0;
652   if(pfd->reqevents & APR_POLLIN) e->mask |= EVENTER_READ;
653   if(pfd->reqevents & APR_POLLOUT) e->mask |= EVENTER_WRITE;
654   if(pfd->reqevents & APR_POLLERR) e->mask |= EVENTER_EXCEPTION;
655   if(newe) {
656     serf_check_info_t *ci = sct->check->closure;
657     eventer_add(newe);
658     ci->fd_event = newe;
659   }
660 /* ** Unneeded as this is called recursively **
661   else
662     eventer_update(e);
663 */
664   return APR_SUCCESS;
665 }
666 static apr_status_t serf_eventer_remove(void *user_baton,
667                                         apr_pollfd_t *pfd,
668                                         void *serf_baton) {
669   serf_closure_t *sct = user_baton;
670   serf_check_info_t *ci;
671   eventer_t e;
672
673   ci = sct->check->closure;
674   assert(pfd->desc_type == APR_POLL_SOCKET);
675   struct __unix_apr_socket_t *hack = (struct __unix_apr_socket_t *)pfd->desc.s;
676
677   noitL(nldeb, "serf_eventer_remove() => %d\n", hack->socketdes);
678   e = eventer_find_fd(hack->socketdes);
679   if(e) {
680     free(e->closure);
681     e->closure = NULL;
682     e->mask = 0;
683   }
684   return 0;
685 }
686
687 static int serf_initiate(noit_module_t *self, noit_check_t *check) {
688   serf_closure_t *ccl;
689   serf_check_info_t *ci;
690   struct timeval when, p_int;
691   apr_status_t status;
692   eventer_t newe;
693   serf_module_conf_t *mod_config;
694   void *config_url;
695
696   mod_config = noit_module_get_userdata(self);
697   ci = (serf_check_info_t *)check->closure;
698   /* We cannot be running */
699   assert(!(check->flags & NP_RUNNING));
700   check->flags |= NP_RUNNING;
701   noitL(nldeb, "serf_initiate(%p,%s)\n",
702         self, check->target);
703
704   /* remove a timeout if we still have one -- we should unless someone
705    * has set a lower timeout than the period.
706    */
707   ci->timed_out = 1;
708   if(ci->timeout_event) {
709     eventer_remove(ci->timeout_event);
710     free(ci->timeout_event->closure);
711     eventer_free(ci->timeout_event);
712     ci->timeout_event = NULL;
713   }
714   assert(!ci->pool);
715   apr_pool_create(&ci->pool, NULL);
716   apr_atomic_init(ci->pool);
717
718   gettimeofday(&when, NULL);
719   memcpy(&check->last_fire_time, &when, sizeof(when));
720
721   ccl = apr_pcalloc(ci->pool, sizeof(*ccl));
722   ccl->self = self;
723   ccl->check = check;
724
725   if(!noit_hash_retrieve(check->config, "url", strlen("url"), &config_url))
726     if(!mod_config->options ||
727        !noit_hash_retrieve(mod_config->options, "url", strlen("url"),
728                            &config_url))
729       config_url = "http://localhost/";
730   apr_uri_parse(ci->pool, config_url, &ci->url);
731
732   if (!ci->url.port) {
733     ci->url.port = apr_uri_port_of_scheme(ci->url.scheme);
734   }
735   if (!ci->url.path) {
736     ci->url.path = "/";
737   }
738
739   if (strcasecmp(ci->url.scheme, "https") == 0) {
740     void *vstr;
741     serf_module_conf_t *conf;
742     conf = noit_module_get_userdata(self);
743
744     ci->app_ctx.using_ssl = 1;
745
746     if(noit_hash_retrieve(check->config, "ca_chain",
747                           strlen("ca_chain"), &vstr))
748       ci->app_ctx.ca_chain_file = apr_pstrdup(ci->pool, vstr);
749     else if(noit_hash_retrieve(conf->options, "ca_chain",
750                                strlen("ca_chain"), &vstr))
751       ci->app_ctx.ca_chain_file = apr_pstrdup(ci->pool, vstr);
752
753     if(noit_hash_retrieve(check->config, "certificate_file",
754                           strlen("certificate_file"), &vstr))
755       ci->app_ctx.certificate_file = apr_pstrdup(ci->pool, vstr);
756     else if(noit_hash_retrieve(conf->options, "certificate_file",
757                                strlen("certificate_file"), &vstr))
758       ci->app_ctx.certificate_file = apr_pstrdup(ci->pool, vstr);
759   }
760   else {
761     ci->app_ctx.using_ssl = 0;
762   }
763
764   status = apr_sockaddr_info_get(&ci->address,
765                                  check->target, APR_UNSPEC, ci->url.port, 0,
766                                  ci->pool);
767   if (status) {
768     /* Handle error -- log failure */
769     apr_pool_destroy(ci->pool);
770     memset(ci, 0, sizeof(*ci));
771     check->flags &= ~NP_RUNNING;
772     return 0;
773   }
774
775   ci->context = serf_context_create_ex(ccl, serf_eventer_add,
776                                        serf_eventer_remove, ci->pool);
777
778   ci->app_ctx.bkt_alloc = serf_bucket_allocator_create(ci->pool, NULL, NULL);
779   ci->app_ctx.ssl_ctx = NULL;
780
781   ci->connection = serf_connection_create(ci->context, ci->address,
782                                           conn_setup, &ci->app_ctx,
783                                           closed_connection, &ci->app_ctx,
784                                           ci->pool);
785
786   ci->handler_ctx.method = apr_pstrdup(ci->pool, "GET");
787   ci->handler_ctx.host = apr_pstrdup(ci->pool, ci->url.hostname);
788   ci->handler_ctx.path = ci->url.path;
789   ci->handler_ctx.authn = NULL;
790
791   ci->handler_ctx.acceptor = accept_response;
792   ci->handler_ctx.acceptor_baton = &ci->app_ctx;
793   ci->handler_ctx.handler = handle_response;
794   ci->handler_ctx.self = self;
795   ci->handler_ctx.check = check;
796
797   ci->request = serf_connection_request_create(ci->connection, setup_request,
798                                                &ci->handler_ctx);
799   serf_context_prerun(ci->context);
800
801   newe = eventer_alloc();
802   newe->mask = EVENTER_TIMER;
803   gettimeofday(&when, NULL);
804   p_int.tv_sec = check->timeout / 1000;
805   p_int.tv_usec = (check->timeout % 1000) * 1000;
806   add_timeval(when, p_int, &newe->whence);
807   ccl = calloc(1, sizeof(*ccl));
808   ccl->self = self;
809   ccl->check = check;
810   newe->closure = ccl;
811   newe->callback = serf_complete;
812   eventer_add(newe);
813   ci->timeout_event = newe;
814   return 0;
815 }
816 static int serf_initiate_check(noit_module_t *self, noit_check_t *check,
817                                int once, noit_check_t *cause) {
818   if(!check->closure) check->closure = calloc(1, sizeof(serf_check_info_t));
819   INITIATE_CHECK(serf_initiate, self, check);
820   return 0;
821 }
822 static int resmon_initiate_check(noit_module_t *self, noit_check_t *check,
823                                  int once, noit_check_t *parent) {
824   /* resmon_check_info_t gives us a bit more space */
825   if(!check->closure) check->closure = calloc(1, sizeof(resmon_check_info_t));
826   INITIATE_CHECK(serf_initiate, self, check);
827   return 0;
828 }
829
830 static void resmon_cleanup(noit_module_t *self, noit_check_t *check) {
831   resmon_check_info_t *rci;
832   rci = check->closure;
833   if(rci) {
834     if(rci->xpathexpr) free(rci->xpathexpr);
835     if(rci->resmod) free(rci->resmod);
836     if(rci->resserv) free(rci->resserv);
837     if(rci->xml_doc) xmlFreeDoc(rci->xml_doc);
838     serf_cleanup(self, check);
839     memset(rci, 0, sizeof(*rci));
840   }
841 }
842 static int resmon_part_initiate_check(noit_module_t *self, noit_check_t *check,
843                                       int once, noit_check_t *parent) {
844   char xpathexpr[1024];
845   void *resmod, *resserv;
846   resmon_check_info_t *rci;
847
848   if(NOIT_CHECK_DISABLED(check) || NOIT_CHECK_KILLED(check)) return 0;
849
850   if(!check->closure) check->closure = calloc(1, sizeof(resmon_check_info_t));
851   rci = check->closure;
852   if(!rci->xpathexpr) {
853     if(!noit_hash_retrieve(check->config,
854                            "resmon_module", strlen("resmon_module"),
855                            &resmod)) {
856       resmod = "DUMMY_MODULE";
857     }
858     if(!noit_hash_retrieve(check->config,
859                            "resmon_service", strlen("resmon_service"),
860                            &resserv)) {
861       resserv = "DUMMY_SERVICE";
862     }
863     snprintf(xpathexpr, sizeof(xpathexpr),
864              "//ResmonResult[@module=\"%s\" and @service=\"%s\"]/*",
865              (const char *)resmod, (const char *)resserv);
866     rci->xpathexpr = strdup(xpathexpr);
867     rci->resmod = strdup(resmod);
868     rci->resserv = strdup(resserv);
869   }
870
871   if(parent && !strcmp(parent->module, "resmon")) {
872     /* Content is cached in the parent */
873     serf_check_info_t *ci = (serf_check_info_t *)rci;
874     gettimeofday(&ci->finish_time, NULL);
875     resmon_part_log_results(self, check, parent);
876     return 0;
877   }
878   INITIATE_CHECK(serf_initiate, self, check);
879   return 0;
880 }
881
882 static int serf_onload(noit_image_t *self) {
883   apr_initialize();
884   atexit(apr_terminate);
885
886   nlerr = noit_log_stream_find("error/serf");
887   nldeb = noit_log_stream_find("debug/serf");
888   if(!nlerr) nlerr = noit_stderr;
889   if(!nldeb) nldeb = noit_debug;
890
891   eventer_name_callback("http/serf_handler", serf_handler);
892   eventer_name_callback("http/serf_complete", serf_complete);
893   return 0;
894 }
895 noit_module_t http = {
896   {
897     NOIT_MODULE_MAGIC,
898     NOIT_MODULE_ABI_VERSION,
899     "http",
900     "libserf-based HTTP and HTTPS resource checker",
901     serf_onload
902   },
903   serf_config,
904   serf_init,
905   serf_initiate_check,
906   serf_cleanup
907 };
908
909 noit_module_t resmon = {
910   {
911     NOIT_MODULE_MAGIC,
912     NOIT_MODULE_ABI_VERSION,
913     "resmon",
914     "libserf-based resmon resource checker",
915     serf_onload
916   },
917   resmon_config,
918   serf_init,
919   resmon_initiate_check,
920   resmon_cleanup
921 };
922
923 noit_module_t resmon_part = {
924   {
925     NOIT_MODULE_MAGIC,
926     NOIT_MODULE_ABI_VERSION,
927     "resmon_part",
928     "resmon part resource checker",
929     serf_onload
930   },
931   resmon_config,
932   serf_init,
933   resmon_part_initiate_check,
934   resmon_cleanup
935 };
936
Note: See TracBrowser for help on using the browser.