root/src/modules/http.c

Revision 37cf7d8f9e336376dc0ecdb1b80e4776721a950b, 27.1 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 6 years ago)

A 'simple' tokenizer to help us with the console

  • 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), "%.3fms",
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), "%.3fms",
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 int serf_complete(eventer_t e, int mask,
342                          void *closure, struct timeval *now) {
343   serf_closure_t *ccl = (serf_closure_t *)closure;
344   serf_check_info_t *ci = (serf_check_info_t *)ccl->check->closure;
345
346   noitLT(nldeb, now, "serf_complete(%s)\n", ccl->check->target);
347   generic_log_results(ccl->self, ccl->check);
348   if(ci->connection) {
349     serf_connection_close(ci->connection);
350     ci->connection = NULL;
351   }
352   if(ci->fd_event) {
353     eventer_remove_fd(ci->fd_event->fd);
354     eventer_free(ci->fd_event);
355     ci->fd_event = NULL;
356   }
357   ci->timeout_event = NULL;
358   apr_pool_destroy(ci->pool);
359   memset(ci, 0, sizeof(*ci));
360   ccl->check->flags &= ~NP_RUNNING;
361   free(ccl);
362   return 0;
363 }
364
365 static int serf_handler(eventer_t e, int mask,
366                         void *closure, struct timeval *now) {
367   apr_pollfd_t desc = { 0 };
368   serf_closure_t *sct = closure;
369   serf_check_info_t *ci = sct->check->closure;
370
371   desc.desc_type = APR_POLL_SOCKET;
372   desc.desc.s = sct->skt;
373
374   desc.rtnevents = 0;
375   if(mask & EVENTER_READ) desc.rtnevents |= APR_POLLIN;
376   if(mask & EVENTER_WRITE) desc.rtnevents |= APR_POLLOUT;
377   if(mask & EVENTER_EXCEPTION) desc.rtnevents |= APR_POLLERR;
378   serf_event_trigger(ci->context, sct->serf_baton, &desc);
379   serf_context_prerun(ci->context);
380
381   /* We're about to deschedule and free the event, drop our reference */
382   if(!e->mask)
383     ci->fd_event = NULL;
384
385   return e->mask;
386 }
387
388 static int serf_init(noit_module_t *self) {
389   return 0;
390 }
391 static void closed_connection(serf_connection_t *conn,
392                               void *closed_baton,
393                               apr_status_t why,
394                               apr_pool_t *pool) {
395 }
396
397 static serf_bucket_t* conn_setup(apr_socket_t *skt,
398                                 void *setup_baton,
399                                 apr_pool_t *pool) {
400   serf_bucket_t *c;
401   app_baton_t *ctx = setup_baton;
402
403   c = serf_bucket_socket_create(skt, ctx->bkt_alloc);
404   if (ctx->using_ssl) {
405       c = serf_bucket_ssl_decrypt_create(c, ctx->ssl_ctx, ctx->bkt_alloc);
406       if (!ctx->ssl_ctx) {
407           ctx->ssl_ctx = serf_bucket_ssl_decrypt_context_get(c);
408       }
409   }
410
411   return c;
412 }
413
414 static serf_bucket_t* accept_response(serf_request_t *request,
415                                       serf_bucket_t *stream,
416                                       void *acceptor_baton,
417                                       apr_pool_t *pool) {
418   serf_bucket_t *c;
419   serf_bucket_alloc_t *bkt_alloc;
420
421   /* get the per-request bucket allocator */
422   bkt_alloc = serf_request_get_alloc(request);
423
424   /* Create a barrier so the response doesn't eat us! */
425   c = serf_bucket_barrier_create(stream, bkt_alloc);
426
427   return serf_bucket_response_create(c, bkt_alloc);
428 }
429
430 static void append_buf(apr_pool_t *p, buf_t *b,
431                        const char *data, int len) {
432   char *n;
433   n = apr_palloc(p, b->l + len + 1);
434   if(b->l == 0)
435     b->b = n;
436   else {
437     memcpy(n, b->b, b->l);
438     b->b = n;
439   }
440   memcpy(b->b + b->l, data, len);
441   b->l += len;
442   b->b[b->l] = '\0';
443 }
444
445 static apr_status_t handle_response(serf_request_t *request,
446                                     serf_bucket_t *response,
447                                     void *handler_baton,
448                                     apr_pool_t *pool) {
449   const char *data;
450   apr_size_t len;
451   apr_status_t status;
452   handler_baton_t *ctx = handler_baton;
453   serf_check_info_t *ci = ctx->check->closure;
454
455   if(response == NULL) {
456     /* We were cancelled. */
457     goto finish;
458   }
459   status = serf_bucket_response_status(response, &ci->status);
460   if (status) {
461     if (APR_STATUS_IS_EAGAIN(status)) {
462       return status;
463     }
464     goto finish;
465   }
466
467   while (1) {
468     status = serf_bucket_read(response, 1024*32, &data, &len);
469     if (SERF_BUCKET_READ_ERROR(status))
470       return status;
471
472     append_buf(ci->pool, &ci->body, data, len);
473
474     /* are we done yet? */
475     if (APR_STATUS_IS_EOF(status)) {
476       serf_bucket_t *hdrs;
477       hdrs = serf_bucket_response_get_headers(response);
478       while (1) {
479         status = serf_bucket_read(hdrs, 2048, &data, &len);
480         if (SERF_BUCKET_READ_ERROR(status))
481           return status;
482
483         append_buf(ci->pool, &ci->headers, data, len);
484         if (APR_STATUS_IS_EOF(status)) {
485           break;
486         }
487       }
488
489       goto finish;
490     }
491
492     /* have we drained the response so far? */
493     if (APR_STATUS_IS_EAGAIN(status))
494       return status;
495
496     /* loop to read some more. */
497   }
498  finish:
499   gettimeofday(&ci->finish_time, NULL);
500   if(ci->timeout_event) {
501     eventer_remove(ci->timeout_event);
502     ci->timed_out = 0;
503     memcpy(&ci->timeout_event->whence, &ci->finish_time,
504            sizeof(&ci->finish_time));
505     eventer_add(ci->timeout_event);
506   }
507   return APR_EOF;
508 }
509
510 static apr_status_t setup_request(serf_request_t *request,
511                                   void *setup_baton,
512                                   serf_bucket_t **req_bkt,
513                                   serf_response_acceptor_t *acceptor,                                             void **acceptor_baton,
514                                   serf_response_handler_t *handler,
515                                   void **handler_baton,
516                                   apr_pool_t *pool) {
517   handler_baton_t *ctx = setup_baton;
518   serf_bucket_t *hdrs_bkt;
519   serf_bucket_t *body_bkt;
520
521   body_bkt = NULL;
522
523   *req_bkt = serf_bucket_request_create(ctx->method, ctx->path, body_bkt,
524                                         serf_request_get_alloc(request));
525
526   hdrs_bkt = serf_bucket_request_get_headers(*req_bkt);
527
528   serf_bucket_headers_setn(hdrs_bkt, "Host", ctx->host);
529   serf_bucket_headers_setn(hdrs_bkt, "User-Agent",
530                            "Noit/" NOIT_HTTP_VERSION_STRING);
531   /* Shouldn't serf do this for us? */
532   serf_bucket_headers_setn(hdrs_bkt, "Accept-Encoding", "gzip");
533
534   if (ctx->authn != NULL) {
535     serf_bucket_headers_setn(hdrs_bkt, "Authorization", ctx->authn);
536   }
537
538   if (ctx->acceptor_baton->using_ssl) {
539     serf_bucket_alloc_t *req_alloc;
540     app_baton_t *app_ctx = ctx->acceptor_baton;
541
542     req_alloc = serf_request_get_alloc(request);
543
544     if (app_ctx->ssl_ctx == NULL) {
545       *req_bkt =
546         serf_bucket_ssl_encrypt_create(*req_bkt, NULL,
547                                        app_ctx->bkt_alloc);
548       app_ctx->ssl_ctx =
549         serf_bucket_ssl_encrypt_context_get(*req_bkt);
550     }
551     else {
552       *req_bkt =
553         serf_bucket_ssl_encrypt_create(*req_bkt, app_ctx->ssl_ctx,
554                                        app_ctx->bkt_alloc);
555     }
556   }
557
558   *acceptor = ctx->acceptor;
559   *acceptor_baton = ctx->acceptor_baton;
560   *handler = ctx->handler;
561   *handler_baton = ctx;
562
563   return APR_SUCCESS;
564 }
565
566 struct __unix_apr_socket_t {
567   apr_pool_t *pool;
568   int socketdes;
569 };
570
571 static apr_status_t serf_eventer_add(void *user_baton,
572                                      apr_pollfd_t *pfd,
573                                      void *serf_baton) {
574   eventer_t e, newe = NULL;
575   serf_closure_t *sct = user_baton, *newsct;
576   assert(pfd->desc_type == APR_POLL_SOCKET);
577   struct __unix_apr_socket_t *hack = (struct __unix_apr_socket_t *)pfd->desc.s;
578
579   noitL(nldeb, "serf_eventer_add() => %d\n", hack->socketdes);
580   e = eventer_find_fd(hack->socketdes);
581   if(!e) {
582     newe = e = eventer_alloc();
583     e->fd = hack->socketdes;
584     e->callback = serf_handler;
585     e->closure = calloc(1, sizeof(serf_closure_t));
586   }
587   newsct = e->closure;
588   newsct->self = sct->self;
589   newsct->check = sct->check;
590   newsct->serf_baton = serf_baton;
591   newsct->skt = pfd->desc.s;
592   e->mask = 0;
593   if(pfd->reqevents & APR_POLLIN) e->mask |= EVENTER_READ;
594   if(pfd->reqevents & APR_POLLOUT) e->mask |= EVENTER_WRITE;
595   if(pfd->reqevents & APR_POLLERR) e->mask |= EVENTER_EXCEPTION;
596   if(newe) {
597     serf_check_info_t *ci = sct->check->closure;
598     eventer_add(newe);
599     ci->fd_event = newe;
600   }
601 /* ** Unneeded as this is called recursively **
602   else
603     eventer_update(e);
604 */
605   return APR_SUCCESS;
606 }
607 static apr_status_t serf_eventer_remove(void *user_baton,
608                                         apr_pollfd_t *pfd,
609                                         void *serf_baton) {
610   serf_closure_t *sct = user_baton;
611   serf_check_info_t *ci;
612   eventer_t e;
613
614   ci = sct->check->closure;
615   assert(pfd->desc_type == APR_POLL_SOCKET);
616   struct __unix_apr_socket_t *hack = (struct __unix_apr_socket_t *)pfd->desc.s;
617
618   noitL(nldeb, "serf_eventer_remove() => %d\n", hack->socketdes);
619   e = eventer_find_fd(hack->socketdes);
620   if(e) e->mask = 0;
621   return 0;
622 }
623
624 static int serf_initiate(noit_module_t *self, noit_check_t *check) {
625   serf_closure_t *ccl;
626   serf_check_info_t *ci;
627   struct timeval when, p_int;
628   apr_status_t status;
629   eventer_t newe;
630   serf_module_conf_t *mod_config;
631   char *config_url;
632
633   mod_config = noit_module_get_userdata(self);
634   ci = (serf_check_info_t *)check->closure;
635   /* We cannot be running */
636   assert(!(check->flags & NP_RUNNING));
637   check->flags |= NP_RUNNING;
638   noitL(nldeb, "serf_initiate(%p,%s)\n",
639         self, check->target);
640
641   /* remove a timeout if we still have one -- we should unless someone
642    * has set a lower timeout than the period.
643    */
644   ci->timed_out = 1;
645   if(ci->timeout_event) {
646     eventer_remove(ci->timeout_event);
647     free(ci->timeout_event->closure);
648     eventer_free(ci->timeout_event);
649     ci->timeout_event = NULL;
650   }
651   assert(!ci->pool);
652   apr_pool_create(&ci->pool, NULL);
653   apr_atomic_init(ci->pool);
654
655   gettimeofday(&when, NULL);
656   memcpy(&check->last_fire_time, &when, sizeof(when));
657
658   ccl = apr_pcalloc(ci->pool, sizeof(*ccl));
659   ccl->self = self;
660   ccl->check = check;
661
662   if(!noit_hash_retrieve(check->config, "url", strlen("url"),
663                         (void **)&config_url))
664     if(!mod_config->options ||
665        !noit_hash_retrieve(mod_config->options, "url", strlen("url"),
666                            (void **)&config_url))
667       config_url = "http://localhost/";
668   apr_uri_parse(ci->pool, config_url, &ci->url);
669
670   if (!ci->url.port) {
671     ci->url.port = apr_uri_port_of_scheme(ci->url.scheme);
672   }
673   if (!ci->url.path) {
674     ci->url.path = "/";
675   }
676
677   if (strcasecmp(ci->url.scheme, "https") == 0) {
678     ci->app_ctx.using_ssl = 1;
679   }
680   else {
681     ci->app_ctx.using_ssl = 0;
682   }
683
684   status = apr_sockaddr_info_get(&ci->address,
685                                  check->target, APR_UNSPEC, ci->url.port, 0,
686                                  ci->pool);
687   if (status) {
688     /* Handle error -- log failure */
689     apr_pool_destroy(ci->pool);
690     memset(ci, 0, sizeof(*ci));
691     check->flags &= ~NP_RUNNING;
692     return 0;
693   }
694
695   ci->context = serf_context_create_ex(ccl, serf_eventer_add,
696                                        serf_eventer_remove, ci->pool);
697
698   ci->app_ctx.bkt_alloc = serf_bucket_allocator_create(ci->pool, NULL, NULL);
699   ci->app_ctx.ssl_ctx = NULL;
700
701   ci->connection = serf_connection_create(ci->context, ci->address,
702                                           conn_setup, &ci->app_ctx,
703                                           closed_connection, &ci->app_ctx,
704                                           ci->pool);
705
706   ci->handler_ctx.method = apr_pstrdup(ci->pool, "GET");
707   ci->handler_ctx.host = apr_pstrdup(ci->pool, ci->url.hostname);
708   ci->handler_ctx.path = ci->url.path;
709   ci->handler_ctx.authn = NULL;
710
711   ci->handler_ctx.acceptor = accept_response;
712   ci->handler_ctx.acceptor_baton = &ci->app_ctx;
713   ci->handler_ctx.handler = handle_response;
714   ci->handler_ctx.self = self;
715   ci->handler_ctx.check = check;
716
717   ci->request = serf_connection_request_create(ci->connection, setup_request,
718                                                &ci->handler_ctx);
719   serf_context_prerun(ci->context);
720
721   newe = eventer_alloc();
722   newe->mask = EVENTER_TIMER;
723   gettimeofday(&when, NULL);
724   p_int.tv_sec = check->timeout / 1000;
725   p_int.tv_usec = (check->timeout % 1000) * 1000;
726   add_timeval(when, p_int, &newe->whence);
727   ccl = calloc(1, sizeof(*ccl));
728   ccl->self = self;
729   ccl->check = check;
730   newe->closure = ccl;
731   newe->callback = serf_complete;
732   eventer_add(newe);
733   ci->timeout_event = newe;
734   return 0;
735 }
736 static int serf_schedule_next(noit_module_t *self,
737                               struct timeval *last_check, noit_check_t *check,
738                               struct timeval *now) {
739   eventer_t newe;
740   struct timeval period, earliest;
741   serf_closure_t *ccl;
742
743   if(check->period == 0) return 0;
744
745   /* If we have an event, we know when we intended it to fire.  This means
746    * we should schedule that point + period.
747    */
748   if(now)
749     memcpy(&earliest, now, sizeof(earliest));
750   else
751     gettimeofday(&earliest, NULL);
752   period.tv_sec = check->period / 1000;
753   period.tv_usec = (check->period % 1000) * 1000;
754
755   newe = eventer_alloc();
756   memcpy(&newe->whence, last_check, sizeof(*last_check));
757   add_timeval(newe->whence, period, &newe->whence);
758   if(compare_timeval(newe->whence, earliest) < 0)
759     memcpy(&newe->whence, &earliest, sizeof(earliest));
760   newe->mask = EVENTER_TIMER;
761   newe->callback = serf_recur_handler;
762   ccl = calloc(1, sizeof(*ccl));
763   ccl->self = self;
764   ccl->check = check;
765   newe->closure = ccl;
766
767   eventer_add(newe);
768   check->fire_event = newe;
769   return 0;
770 }
771 static int serf_recur_handler(eventer_t e, int mask, void *closure,
772                               struct timeval *now) {
773   serf_closure_t *cl = (serf_closure_t *)closure;
774   serf_schedule_next(cl->self, &e->whence, cl->check, now);
775   serf_initiate(cl->self, cl->check);
776   free(cl);
777   return 0;
778 }
779 static int serf_initiate_check(noit_module_t *self, noit_check_t *check,
780                                int once, noit_check_t *cause) {
781   if(!check->closure) check->closure = calloc(1, sizeof(serf_check_info_t));
782   if(once) {
783     serf_initiate(self, check);
784     return 0;
785   }
786   /* If check->fire_event, we're already scheduled... */
787   if(!check->fire_event) {
788     struct timeval epoch = { 0L, 0L };
789     noit_check_fake_last_check(check, &epoch, NULL);
790     serf_schedule_next(self, &epoch, check, NULL);
791   }
792   return 0;
793 }
794 static int resmon_initiate_check(noit_module_t *self, noit_check_t *check,
795                                  int once, noit_check_t *parent) {
796   /* resmon_check_info_t gives us a bit more space */
797   if(!check->closure) check->closure = calloc(1, sizeof(resmon_check_info_t));
798   if(once) {
799     serf_initiate(self, check);
800     return 0;
801   }
802   if(!check->fire_event) {
803     struct timeval epoch = { 0L, 0L };
804     noit_check_fake_last_check(check, &epoch, NULL);
805     serf_schedule_next(self, &epoch, check, NULL);
806   }
807   return 0;
808 }
809
810 static int resmon_part_initiate_check(noit_module_t *self, noit_check_t *check,
811                                       int once, noit_check_t *parent) {
812   char xpathexpr[1024];
813   const char *resmod, *resserv;
814   resmon_check_info_t *rci;
815
816   if(!check->closure) check->closure = calloc(1, sizeof(resmon_check_info_t));
817   rci = check->closure;
818   if(!rci->xpathexpr) {
819     if(!noit_hash_retrieve(check->config,
820                            "resmon_module", strlen("resmon_module"),
821                            (void **)&resmod)) {
822       resmod = "DUMMY_MODULE";
823     }
824     if(!noit_hash_retrieve(check->config,
825                            "resmon_service", strlen("resmon_service"),
826                            (void **)&resserv)) {
827       resserv = "DUMMY_SERVICE";
828     }
829     snprintf(xpathexpr, sizeof(xpathexpr),
830              "//ResmonResult[@module=\"%s\" and @service=\"%s\"]/*",
831              resmod, resserv);
832     rci->xpathexpr = strdup(xpathexpr);
833     rci->resmod = strdup(resmod);
834     rci->resserv = strdup(resserv);
835   }
836
837   if(parent && !strcmp(parent->module, "resmon")) {
838     /* Content is cached in the parent */
839     resmon_part_log_results(self, check, parent);
840     return 0;
841   }
842   if(once) {
843     serf_initiate(self, check);
844     return 0;
845   }
846   if(!check->fire_event)
847     serf_schedule_next(self, NULL, check, NULL);
848   return 0;
849 }
850
851
852
853 static int serf_onload(noit_module_t *self) {
854   apr_initialize();
855   atexit(apr_terminate);
856
857   nlerr = noit_log_stream_find("error/serf");
858   nldeb = noit_log_stream_find("debug/serf");
859   if(!nlerr) nlerr = noit_stderr;
860   if(!nldeb) nldeb = noit_debug;
861
862   eventer_name_callback("http/serf_handler", serf_handler);
863   eventer_name_callback("http/serf_complete", serf_complete);
864   eventer_name_callback("http/serf_recur_handler", serf_recur_handler);
865   return 0;
866 }
867 noit_module_t http = {
868   NOIT_MODULE_MAGIC,
869   NOIT_MODULE_ABI_VERSION,
870   "http",
871   "libserf-based HTTP and HTTPS resource checker",
872   serf_onload,
873   serf_config,
874   serf_init,
875   serf_initiate_check
876 };
877
878 noit_module_t resmon = {
879   NOIT_MODULE_MAGIC,
880   NOIT_MODULE_ABI_VERSION,
881   "resmon",
882   "libserf-based resmon resource checker",
883   serf_onload,
884   resmon_config,
885   serf_init,
886   resmon_initiate_check
887 };
888
889 noit_module_t resmon_part = {
890   NOIT_MODULE_MAGIC,
891   NOIT_MODULE_ABI_VERSION,
892   "resmon_part",
893   "resmon part resource checker",
894   serf_onload,
895   resmon_config,
896   serf_init,
897   resmon_part_initiate_check
898 };
899
Note: See TracBrowser for help on using the browser.