root/src/modules/http.c

Revision 6e90b3f8072e3e74ee6b01f01b9b1be2e207738f, 28.3 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 10 years ago)

support 'no check' on console to delete checks as well as 'reload' on console (currently only reloads checks)

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