root/src/stratcon_realtime_http.c

Revision d9050a442ce49ffad4040ba933511197fe71390f, 16.3 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 5 years ago)

this will break realtime streaming.... need to fix the javascript in the web ui now, refs #229

  • Property mode set to 100644
Line 
1 /*
2  * Copyright (c) 2007, OmniTI Computer Consulting, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  *       notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  *       copyright notice, this list of conditions and the following
13  *       disclaimer in the documentation and/or other materials provided
14  *       with the distribution.
15  *     * Neither the name OmniTI Computer Consulting, Inc. nor the names
16  *       of its contributors may be used to endorse or promote products
17  *       derived from this software without specific prior written
18  *       permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "noit_defines.h"
34 #include "eventer/eventer.h"
35 #include "noit_conf.h"
36 #include "utils/noit_hash.h"
37 #include "utils/noit_log.h"
38 #include "utils/noit_str.h"
39 #include "jlog/jlog.h"
40 #include "noit_jlog_listener.h"
41 #include "noit_listener.h"
42 #include "noit_http.h"
43 #include "noit_rest.h"
44 #include "noit_livestream_listener.h"
45 #include "stratcon_realtime_http.h"
46 #include "stratcon_jlog_streamer.h"
47 #include "stratcon_datastore.h"
48
49 #include <unistd.h>
50 #include <assert.h>
51 #include <errno.h>
52 #include <sys/types.h>
53 #include <sys/socket.h>
54 #ifdef HAVE_SYS_FILIO_H
55 #include <sys/filio.h>
56 #endif
57 #include <netinet/in.h>
58 #include <sys/un.h>
59 #include <arpa/inet.h>
60
61
62 typedef struct realtime_recv_ctx_t {
63   int bytes_expected;
64   int bytes_read;
65   int bytes_written;
66   int body_len;
67   char *buffer;         /* These guys are for doing partial reads */
68
69   enum {
70     REALTIME_HTTP_WANT_INITIATE = 0,
71     REALTIME_HTTP_WANT_SEND_INTERVAL = 1,
72     REALTIME_HTTP_WANT_SEND_UUID = 2,
73     REALTIME_HTTP_WANT_HEADER = 3,
74     REALTIME_HTTP_WANT_BODY = 4,
75   } state;
76   int count;            /* Number of jlog messages we need to read */
77   noit_http_session_ctx *ctx;
78   struct realtime_tracker *rt;
79 } realtime_recv_ctx_t;
80
81 typedef struct realtime_context {
82   enum { RC_INITIAL = 0, RC_REQ_RECV, RC_INTERESTS_RESOLVED, RC_FEEDING } setup;
83   struct realtime_tracker *checklist;
84   char *document_domain;
85 } realtime_context;
86
87 static realtime_context *alloc_realtime_context(const char *domain) {
88   realtime_context *ctx;
89   ctx = calloc(sizeof(*ctx), 1);
90   ctx->document_domain = strdup(domain);
91   return ctx;
92 }
93 static void free_realtime_tracker(struct realtime_tracker *rt) {
94   if(rt->noit) free(rt->noit);
95   free(rt);
96 }
97 static void clear_realtime_context(realtime_context *rc) {
98  rc->setup = RC_INITIAL;
99   while(rc->checklist) {
100     struct realtime_tracker *tofree;
101     tofree = rc->checklist;
102     rc->checklist = tofree->next;
103     free_realtime_tracker(tofree);
104   }
105   if(rc->document_domain) free(rc->document_domain);
106   rc->document_domain = NULL;
107 }
108 int
109 stratcon_line_to_javascript(noit_http_session_ctx *ctx, char *buff) {
110   char buffer[1024];
111   char *scp, *ecp, *token;
112   int len;
113   void *vcb;
114   const char *v, *cb = NULL;
115   noit_hash_table json = NOIT_HASH_EMPTY;
116
117   if(noit_hash_retrieve(&ctx->req.querystring, "cb", strlen("cb"), &vcb))
118     cb = vcb;
119   for(v = cb; v && *v; v++)
120     if(!((*v >= '0' && *v <= '9') ||
121          (*v >= 'a' && *v <= 'z') ||
122          (*v >= 'A' && *v <= 'Z') ||
123          (*v == '_'))) {
124       cb = NULL;
125       break;
126     }
127   if(!cb) cb = "window.parent.plot_iframe_data";
128
129 #define BAIL_HTTP_WRITE do { \
130   noit_hash_destroy(&json, NULL, free); \
131   noitL(noit_error, "javascript emit failed: %s:%s:%d\n", \
132         __FILE__, __FUNCTION__, __LINE__); \
133   return -1; \
134 } while(0)
135
136 #define PROCESS_NEXT_FIELD(t,l) do { \
137   if(!*scp) goto bad_row; \
138   ecp = strchr(scp, '\t'); \
139   if(!ecp) goto bad_row; \
140   t = scp; \
141   l = (ecp-scp); \
142   scp = ecp + 1; \
143 } while(0)
144 #define PROCESS_LAST_FIELD(t,l) do { \
145   if(!*scp) ecp = scp; \
146   else { \
147     ecp = scp + strlen(scp); /* Puts us at the '\0' */ \
148     if(*(ecp-1) == '\n') ecp--; /* We back up on letter if we ended in \n */ \
149   } \
150   t = scp; \
151   l = (ecp-scp); \
152 } while(0)
153
154   scp = buff;
155   PROCESS_NEXT_FIELD(token,len); /* Skip the leader */
156   if(buff[0] == 'M') {
157     noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
158     const char *key;
159     int klen, i=0;
160     void *vval;
161
162 #define ra_write(a,b) if(noit_http_response_append(ctx, a, b) == noit_false) BAIL_HTTP_WRITE
163
164     snprintf(buffer, sizeof(buffer), "<script>%s({", cb);
165     ra_write(buffer, strlen(buffer));
166
167     while(noit_hash_next(&ctx->req.querystring, &iter, &key, &klen, &vval)) {
168       if(!strcmp(key, "cb")) continue;
169       noit_hash_store(&json, key, klen, strdup(vval ?(char *)vval : "true"));
170     }
171     /* Time */
172     noit_hash_store(&json, "type", 4, strdup("M"));
173     PROCESS_NEXT_FIELD(token,len);
174     noit_hash_store(&json, "time", 4, noit__strndup(token, len));
175     /* UUID */
176     PROCESS_NEXT_FIELD(token,len);
177     noit_hash_store(&json, "id", 2, noit__strndup(token, len));
178     /* name */
179     PROCESS_NEXT_FIELD(token,len);
180     noit_hash_store(&json, "metric_name", 11, noit__strndup(token, len));
181     /* type */
182     PROCESS_NEXT_FIELD(token,len);
183     noit_hash_store(&json, "metric_type", 11, noit__strndup(token, len));
184     /* value */
185     PROCESS_LAST_FIELD(token,len); /* value */
186     noit_hash_store(&json, "value", 5, noit__strndup(token, len));
187
188     memset(&iter, 0, sizeof(iter));
189     while(noit_hash_next(&json, &iter, &key, &klen, &vval)) {
190       if(i++) ra_write(",", 1);
191       ra_write("'", 1);
192       ra_write(key, klen);
193       ra_write("':'", 3);
194       ra_write((char *)vval, strlen((char *)vval));
195       ra_write("'", 1);
196     }
197     snprintf(buffer, sizeof(buffer), "});</script>\n");
198     ra_write(buffer, strlen(buffer));
199
200     if(noit_http_response_flush(ctx, noit_false) == noit_false) BAIL_HTTP_WRITE;
201   }
202
203   noit_hash_destroy(&json, NULL, free);
204   return 0;
205
206  bad_row:
207   BAIL_HTTP_WRITE;
208 }
209 int
210 stratcon_realtime_uri_parse(realtime_context *rc, char *uri) {
211   int len, cnt = 0;
212   char *cp, *copy, *interest, *brk;
213   if(strncmp(uri, "/data/", 6)) return 0;
214   cp = uri + 6;
215   len = strlen(cp);
216   copy = alloca(len + 1);
217   if(!copy) return 0;
218   memcpy(copy, cp, len);
219   copy[len] = '\0';
220
221   for (interest = strtok_r(copy, "/", &brk);
222        interest;
223        interest = strtok_r(NULL, "/", &brk)) {
224     uuid_t in_uuid;
225     struct realtime_tracker *node;
226     char *interval;
227
228     interval = strchr(interest, '@');
229     if(!interval)
230       interval = "5000";
231     else
232       *interval++ = '\0';
233     if(uuid_parse(interest, in_uuid)) continue;
234     node = calloc(1, sizeof(*node));
235     node->rc = rc;
236     uuid_copy(node->checkid, in_uuid);
237     node->interval = atoi(interval);
238     node->next = rc->checklist;
239     rc->checklist = node;
240     cnt++;
241   }
242   return cnt;
243 }
244 static void
245 free_realtime_recv_ctx(void *vctx) {
246   realtime_recv_ctx_t *rrctx = vctx;
247   noit_atomic_dec32(&rrctx->ctx->ref_cnt);
248   free(rrctx);
249 }
250 #define Eread(a,b) e->opset->read(e->fd, (a), (b), &mask, e)
251 static int
252 __read_on_ctx(eventer_t e, realtime_recv_ctx_t *ctx, int *newmask) {
253   int len, mask;
254   while(ctx->bytes_read < ctx->bytes_expected) {
255     len = Eread(ctx->buffer + ctx->bytes_read,
256                 ctx->bytes_expected - ctx->bytes_read);
257     if(len < 0) {
258       *newmask = mask;
259       return -1;
260     }
261     /* if we get 0 inside SSL, and there was a real error, we
262      * will actually get a -1 here.
263      * if(len == 0) return ctx->bytes_read;
264      */
265     ctx->bytes_read += len;
266   }
267   assert(ctx->bytes_read == ctx->bytes_expected);
268   return ctx->bytes_read;
269 }
270 #define FULLREAD(e,ctx,size) do { \
271   int mask, len; \
272   if(!ctx->bytes_expected) { \
273     ctx->bytes_expected = size; \
274     if(ctx->buffer) free(ctx->buffer); \
275     ctx->buffer = malloc(size + 1); \
276     if(ctx->buffer == NULL) { \
277       noitL(noit_error, "malloc(%lu) failed.\n", (unsigned long)size + 1); \
278       goto socket_error; \
279     } \
280     ctx->buffer[size] = '\0'; \
281   } \
282   len = __read_on_ctx(e, ctx, &mask); \
283   if(len < 0) { \
284     if(errno == EAGAIN) return mask | EVENTER_EXCEPTION; \
285     noitL(noit_error, "SSL read error: %s\n", strerror(errno)); \
286     goto socket_error; \
287   } \
288   ctx->bytes_read = 0; \
289   ctx->bytes_expected = 0; \
290   if(len != size) { \
291     noitL(noit_error, "SSL short read [%d] (%d/%lu).  Reseting connection.\n", \
292           ctx->state, len, (unsigned long)size); \
293     goto socket_error; \
294   } \
295 } while(0)
296
297 int
298 stratcon_realtime_recv_handler(eventer_t e, int mask, void *closure,
299                                struct timeval *now) {
300   static u_int32_t livestream_cmd = 0;
301   noit_connection_ctx_t *nctx = closure;
302   realtime_recv_ctx_t *ctx = nctx->consumer_ctx;
303   int len;
304   u_int32_t nint;
305   char uuid_str[37];
306
307   if(!livestream_cmd) livestream_cmd = htonl(NOIT_LIVESTREAM_DATA_FEED);
308
309   if(mask & EVENTER_EXCEPTION || nctx->wants_shutdown) {
310  socket_error:
311     ctx->state = REALTIME_HTTP_WANT_INITIATE;
312     ctx->count = 0;
313     ctx->bytes_read = 0;
314     ctx->bytes_written = 0;
315     ctx->bytes_expected = 0;
316     if(ctx->buffer) free(ctx->buffer);
317     ctx->buffer = NULL;
318     noit_connection_ctx_dealloc(nctx);
319     eventer_remove_fd(e->fd);
320     e->opset->close(e->fd, &mask, e);
321     return 0;
322   }
323
324 #define full_nb_write(data, wlen) do { \
325   if(!ctx->bytes_expected) { \
326     ctx->bytes_written = 0; \
327     ctx->bytes_expected = wlen; \
328   } \
329   while(ctx->bytes_written < ctx->bytes_expected) { \
330     while(-1 == (len = e->opset->write(e->fd, ((char *)data) + ctx->bytes_written, \
331                                        ctx->bytes_expected - ctx->bytes_written, \
332                                        &mask, e)) && errno == EINTR); \
333     if(len < 0) { \
334       if(errno == EAGAIN) return mask | EVENTER_EXCEPTION; \
335       goto socket_error; \
336     } \
337     ctx->bytes_written += len; \
338   } \
339   if(ctx->bytes_written != ctx->bytes_expected) { \
340     noitL(noit_error, "short write on initiating stream [%d != %d].\n", \
341           ctx->bytes_written, ctx->bytes_expected); \
342     goto socket_error; \
343   } \
344   ctx->bytes_expected = 0; \
345 } while(0)
346
347   while(1) {
348     u_int32_t net_body_len;
349
350     switch(ctx->state) {
351       case REALTIME_HTTP_WANT_INITIATE:
352         full_nb_write(&livestream_cmd, sizeof(livestream_cmd));
353         ctx->state = REALTIME_HTTP_WANT_SEND_INTERVAL;
354       case REALTIME_HTTP_WANT_SEND_INTERVAL:
355         nint = htonl(ctx->rt->interval);
356         full_nb_write(&nint, sizeof(nint));
357         ctx->state = REALTIME_HTTP_WANT_SEND_UUID;
358       case REALTIME_HTTP_WANT_SEND_UUID:
359         uuid_unparse_lower(ctx->rt->checkid, uuid_str);
360         full_nb_write(uuid_str, 36);
361         ctx->state = REALTIME_HTTP_WANT_HEADER;
362       case REALTIME_HTTP_WANT_HEADER:
363         FULLREAD(e, ctx, sizeof(u_int32_t));
364         memcpy(&net_body_len, ctx->buffer, sizeof(u_int32_t));
365         ctx->body_len = ntohl(net_body_len);
366         free(ctx->buffer); ctx->buffer = NULL;
367         ctx->state = REALTIME_HTTP_WANT_BODY;
368         break;
369       case REALTIME_HTTP_WANT_BODY:
370         FULLREAD(e, ctx, ctx->body_len);
371         if(stratcon_line_to_javascript(ctx->ctx, ctx->buffer)) goto socket_error;
372         free(ctx->buffer); ctx->buffer = NULL;
373         ctx->state = REALTIME_HTTP_WANT_HEADER;
374         break;
375     }
376   }
377
378 }
379
380 int
381 stratcon_realtime_http_postresolve(eventer_t e, int mask, void *closure,
382                                    struct timeval *now) {
383   noit_http_session_ctx *ctx = closure;
384   realtime_context *rc = ctx->dispatcher_closure;
385   struct realtime_tracker *node;
386
387   for(node = rc->checklist; node; node = node->next) {
388     if(node->noit) {
389       realtime_recv_ctx_t *rrctx;
390       rrctx = calloc(1, sizeof(*rrctx));
391       rrctx->ctx = ctx;
392       rrctx->rt = node;
393       stratcon_streamer_connection(NULL, node->noit,
394                                    stratcon_realtime_recv_handler,
395                                    NULL, rrctx,
396                                    free_realtime_recv_ctx);
397     }
398     else
399       noit_atomic_dec32(&ctx->ref_cnt);
400   }
401   if(ctx->ref_cnt == 1) {
402     noit_http_response_end(ctx);
403     clear_realtime_context(rc);
404     if(ctx->conn.e) eventer_trigger(ctx->conn.e, EVENTER_WRITE);
405   }
406   return 0;
407 }
408 int
409 stratcon_request_dispatcher(noit_http_session_ctx *ctx) {
410   const char *key, *value;
411   realtime_context *rc = ctx->dispatcher_closure;
412   int klen;
413   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
414   noit_http_request *req = &ctx->req;
415
416   if(rc->setup == RC_INITIAL) {
417     eventer_t completion;
418     struct realtime_tracker *node;
419     char c[1024];
420     int num_interests;
421
422     num_interests = stratcon_realtime_uri_parse(rc, ctx->req.uri_str);
423     if(num_interests == 0) {
424       noit_http_response_status_set(ctx, 404, "OK");
425       noit_http_response_option_set(ctx, NOIT_HTTP_CLOSE);
426       noit_http_response_end(ctx);
427       return 0;
428     }
429
430     noitL(noit_error, "http: %s %s %s\n",
431           req->method_str, req->uri_str, req->protocol_str);
432     while(noit_hash_next_str(&req->headers, &iter, &key, &klen, &value)) {
433       noitL(noit_error, "http: [%s: %s]\n", key, value);
434     }
435     noit_http_response_status_set(ctx, 200, "OK");
436     noit_http_response_option_set(ctx, NOIT_HTTP_CHUNKED);
437     /*noit_http_response_option_set(ctx, NOIT_HTTP_GZIP);*/
438     /*noit_http_response_option_set(ctx, NOIT_HTTP_DEFLATE);*/
439     noit_http_response_header_set(ctx, "Content-Type", "text/html");
440
441     snprintf(c, sizeof(c),
442              "<html><head><script>document.domain='%s';</script></head><body>\n",
443              rc->document_domain);
444     noit_http_response_append(ctx, c, strlen(c));
445
446     /* this dumb crap is to make some browsers happy (Safari) */
447     memset(c, ' ', sizeof(c));
448     noit_http_response_append(ctx, c, sizeof(c));
449     noit_http_response_flush(ctx, noit_false);
450
451     rc->setup = RC_REQ_RECV;
452     /* Each interest references the ctx */
453     for(node = rc->checklist; node; node = node->next) {
454       char uuid_str[UUID_STR_LEN+1];
455       noit_atomic_inc32(&ctx->ref_cnt);
456       uuid_unparse_lower(node->checkid, uuid_str);
457       noitL(noit_error, "Resolving uuid: %s\n", uuid_str);
458     }
459     completion = eventer_alloc();
460     completion->mask = EVENTER_TIMER;
461     completion->callback = stratcon_realtime_http_postresolve;
462     completion->closure = ctx;
463     gettimeofday(&completion->whence, NULL);
464     stratcon_datastore_push(DS_OP_FIND_COMPLETE, NULL, NULL,
465                             rc->checklist, completion);
466   }
467   return EVENTER_EXCEPTION;
468 }
469 int
470 stratcon_realtime_http_handler(eventer_t e, int mask, void *closure,
471                                struct timeval *now) {
472   acceptor_closure_t *ac = closure;
473   noit_http_session_ctx *http_ctx = ac->service_ctx;
474   return http_ctx->drive(e, mask, http_ctx, now);
475 }
476 static int
477 rest_stream_data(noit_http_rest_closure_t *restc,
478                  int npats, char **pats) {
479   /* We're here and want to subvert the rest system */
480   const char *document_domain = NULL;
481   noit_http_session_ctx *ctx = restc->http_ctx;
482
483   /* Rewire the handler */
484   restc->ac->service_ctx = ctx;
485
486   if(!noit_hash_retr_str(restc->ac->config,
487                          "document_domain", strlen("document_domain"),
488                          &document_domain)) {
489     noitL(noit_error, "Document domain not set!  Realtime streaming will be broken\n");
490     document_domain = "";
491   }
492   noit_http_rest_closure_free(restc);
493
494   noit_http_process_querystring(&ctx->req);
495   /* Rewire the http context */
496   ctx->conn.e->callback = stratcon_realtime_http_handler;
497   ctx->dispatcher = stratcon_request_dispatcher;
498   ctx->dispatcher_closure = alloc_realtime_context(document_domain);
499   //ctx->drive = stratcon_realtime_http_handler;
500   return stratcon_request_dispatcher(ctx);
501 }
502
503 void
504 stratcon_realtime_http_init(const char *toplevel) {
505   eventer_name_callback("stratcon_realtime_http",
506                         stratcon_realtime_http_handler);
507   assert(noit_http_rest_register(
508     "GET", "/data/",
509            "^((?:" UUID_REGEX "(?:@\\d+)?)(?:/" UUID_REGEX "(?:@\\d+)?)*)$",
510     rest_stream_data
511   ) == 0);
512 }
Note: See TracBrowser for help on using the browser.