root/src/stratcon_realtime_http.c

Revision 3c56016c44ec467d9baa6ed0d667e21bf44f81cb, 15.6 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 8 years ago)

insert the new rest API as a shim between the http listener and the realtime streamer -- for future extensibility

  • 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 "jlog/jlog.h"
39 #include "noit_jlog_listener.h"
40 #include "noit_listener.h"
41 #include "noit_http.h"
42 #include "noit_rest.h"
43 #include "noit_livestream_listener.h"
44 #include "stratcon_realtime_http.h"
45 #include "stratcon_jlog_streamer.h"
46 #include "stratcon_datastore.h"
47
48 #include <unistd.h>
49 #include <assert.h>
50 #include <errno.h>
51 #include <sys/types.h>
52 #include <sys/socket.h>
53 #ifdef HAVE_SYS_FILIO_H
54 #include <sys/filio.h>
55 #endif
56 #include <netinet/in.h>
57 #include <sys/un.h>
58 #include <arpa/inet.h>
59
60
61 typedef struct realtime_recv_ctx_t {
62   int bytes_expected;
63   int bytes_read;
64   int bytes_written;
65   int body_len;
66   char *buffer;         /* These guys are for doing partial reads */
67
68   enum {
69     REALTIME_HTTP_WANT_INITIATE = 0,
70     REALTIME_HTTP_WANT_SEND_INTERVAL = 1,
71     REALTIME_HTTP_WANT_SEND_UUID = 2,
72     REALTIME_HTTP_WANT_HEADER = 3,
73     REALTIME_HTTP_WANT_BODY = 4,
74   } state;
75   int count;            /* Number of jlog messages we need to read */
76   noit_http_session_ctx *ctx;
77   struct realtime_tracker *rt;
78 } realtime_recv_ctx_t;
79
80 typedef struct realtime_context {
81   enum { RC_INITIAL = 0, RC_REQ_RECV, RC_INTERESTS_RESOLVED, RC_FEEDING } setup;
82   struct realtime_tracker *checklist;
83   char *document_domain;
84 } realtime_context;
85
86 static realtime_context *alloc_realtime_context(const char *domain) {
87   realtime_context *ctx;
88   ctx = calloc(sizeof(*ctx), 1);
89   ctx->document_domain = strdup(domain);
90   return ctx;
91 }
92 static void free_realtime_tracker(struct realtime_tracker *rt) {
93   if(rt->noit) free(rt->noit);
94   free(rt);
95 }
96 static void clear_realtime_context(realtime_context *rc) {
97  rc->setup = RC_INITIAL;
98   while(rc->checklist) {
99     struct realtime_tracker *tofree;
100     tofree = rc->checklist;
101     rc->checklist = tofree->next;
102     free_realtime_tracker(tofree);
103   }
104   if(rc->document_domain) free(rc->document_domain);
105   rc->document_domain = NULL;
106 }
107 int
108 stratcon_line_to_javascript(noit_http_session_ctx *ctx, char *buff) {
109   char buffer[1024];
110   char *scp, *ecp, *token;
111   int len;
112
113 #define BAIL_HTTP_WRITE do { \
114   noitL(noit_error, "javascript emit failed: %s:%s:%d\n", \
115         __FILE__, __FUNCTION__, __LINE__); \
116   return -1; \
117 } while(0)
118
119 #define PROCESS_NEXT_FIELD(t,l) do { \
120   if(!*scp) goto bad_row; \
121   ecp = strchr(scp, '\t'); \
122   if(!ecp) goto bad_row; \
123   t = scp; \
124   l = (ecp-scp); \
125   scp = ecp + 1; \
126 } while(0)
127 #define PROCESS_LAST_FIELD(t,l) do { \
128   if(!*scp) ecp = scp; \
129   else { \
130     ecp = scp + strlen(scp); /* Puts us at the '\0' */ \
131     if(*(ecp-1) == '\n') ecp--; /* We back up on letter if we ended in \n */ \
132   } \
133   t = scp; \
134   l = (ecp-scp); \
135 } while(0)
136
137   scp = buff;
138   PROCESS_NEXT_FIELD(token,len); /* Skip the leader */
139   if(buff[0] == 'M') {
140     snprintf(buffer, sizeof(buffer), "<script>window.parent.plot_iframe_data('");
141     if(noit_http_response_append(ctx, buffer, strlen(buffer)) == noit_false) BAIL_HTTP_WRITE;
142
143     /* Time */
144     PROCESS_NEXT_FIELD(token,len);
145     if(noit_http_response_append(ctx, token, len) == noit_false) BAIL_HTTP_WRITE;
146
147     snprintf(buffer, sizeof(buffer), "', '");
148     if(noit_http_response_append(ctx, buffer, strlen(buffer)) == noit_false) BAIL_HTTP_WRITE;
149
150     /* UUID */
151     PROCESS_NEXT_FIELD(token,len);
152     if(noit_http_response_append(ctx, token, len) == noit_false) BAIL_HTTP_WRITE;
153
154     snprintf(buffer, sizeof(buffer), "', '");
155     if(noit_http_response_append(ctx, buffer, strlen(buffer)) == noit_false) BAIL_HTTP_WRITE;
156
157     /* name */
158     PROCESS_NEXT_FIELD(token,len);
159     if(noit_http_response_append(ctx, token, len) == noit_false) BAIL_HTTP_WRITE;
160
161     snprintf(buffer, sizeof(buffer), "', '");
162     if(noit_http_response_append(ctx, buffer, strlen(buffer)) == noit_false) BAIL_HTTP_WRITE;
163
164     PROCESS_NEXT_FIELD(token,len); /* skip type */
165     PROCESS_LAST_FIELD(token,len); /* value */
166     if(noit_http_response_append(ctx, token, len) == noit_false) BAIL_HTTP_WRITE;
167
168     snprintf(buffer, sizeof(buffer), "');</script>\n");
169     if(noit_http_response_append(ctx, buffer, strlen(buffer)) == noit_false) BAIL_HTTP_WRITE;
170
171     if(noit_http_response_flush(ctx, noit_false) == noit_false) BAIL_HTTP_WRITE;
172   }
173
174   return 0;
175
176  bad_row:
177   BAIL_HTTP_WRITE;
178   if(0) {
179     noit_http_response_end(ctx);
180     clear_realtime_context(ctx->dispatcher_closure);
181     if(ctx->conn.e) eventer_trigger(ctx->conn.e, EVENTER_WRITE);
182     return 0;
183   }
184 }
185 int
186 stratcon_realtime_uri_parse(realtime_context *rc, char *uri) {
187   int len, cnt = 0;
188   char *cp, *copy, *interest, *brk;
189   if(strncmp(uri, "/data/", 6)) return 0;
190   cp = uri + 6;
191   len = strlen(cp);
192   copy = alloca(len + 1);
193   if(!copy) return 0;
194   memcpy(copy, cp, len);
195   copy[len] = '\0';
196
197   for (interest = strtok_r(copy, "/", &brk);
198        interest;
199        interest = strtok_r(NULL, "/", &brk)) {
200     struct realtime_tracker *node;
201     char *interval;
202
203     interval = strchr(interest, '@');
204     if(!interval)
205       interval = "5000";
206     else
207       *interval++ = '\0';
208     node = calloc(1, sizeof(*node));
209     node->rc = rc;
210     node->sid = atoi(interest);
211     node->interval = atoi(interval);
212     node->next = rc->checklist;
213     rc->checklist = node;
214     cnt++;
215   }
216   return cnt;
217 }
218 static void
219 free_realtime_recv_ctx(void *vctx) {
220   realtime_recv_ctx_t *rrctx = vctx;
221   noit_atomic_dec32(&rrctx->ctx->ref_cnt);
222   free(rrctx);
223 }
224 #define Eread(a,b) e->opset->read(e->fd, (a), (b), &mask, e)
225 static int
226 __read_on_ctx(eventer_t e, realtime_recv_ctx_t *ctx, int *newmask) {
227   int len, mask;
228   while(ctx->bytes_read < ctx->bytes_expected) {
229     len = Eread(ctx->buffer + ctx->bytes_read,
230                 ctx->bytes_expected - ctx->bytes_read);
231     if(len < 0) {
232       *newmask = mask;
233       return -1;
234     }
235     /* if we get 0 inside SSL, and there was a real error, we
236      * will actually get a -1 here.
237      * if(len == 0) return ctx->bytes_read;
238      */
239     ctx->bytes_read += len;
240   }
241   assert(ctx->bytes_read == ctx->bytes_expected);
242   return ctx->bytes_read;
243 }
244 #define FULLREAD(e,ctx,size) do { \
245   int mask, len; \
246   if(!ctx->bytes_expected) { \
247     ctx->bytes_expected = size; \
248     if(ctx->buffer) free(ctx->buffer); \
249     ctx->buffer = malloc(size + 1); \
250     if(ctx->buffer == NULL) { \
251       noitL(noit_error, "malloc(%lu) failed.\n", (unsigned long)size + 1); \
252       goto socket_error; \
253     } \
254     ctx->buffer[size] = '\0'; \
255   } \
256   len = __read_on_ctx(e, ctx, &mask); \
257   if(len < 0) { \
258     if(errno == EAGAIN) return mask | EVENTER_EXCEPTION; \
259     noitL(noit_error, "SSL read error: %s\n", strerror(errno)); \
260     goto socket_error; \
261   } \
262   ctx->bytes_read = 0; \
263   ctx->bytes_expected = 0; \
264   if(len != size) { \
265     noitL(noit_error, "SSL short read [%d] (%d/%lu).  Reseting connection.\n", \
266           ctx->state, len, (unsigned long)size); \
267     goto socket_error; \
268   } \
269 } while(0)
270
271 int
272 stratcon_realtime_recv_handler(eventer_t e, int mask, void *closure,
273                                struct timeval *now) {
274   static u_int32_t livestream_cmd = 0;
275   noit_connection_ctx_t *nctx = closure;
276   realtime_recv_ctx_t *ctx = nctx->consumer_ctx;
277   int len;
278   u_int32_t nint;
279   char uuid_str[37];
280
281   if(!livestream_cmd) livestream_cmd = htonl(NOIT_LIVESTREAM_DATA_FEED);
282
283   if(mask & EVENTER_EXCEPTION || nctx->wants_shutdown) {
284  socket_error:
285     ctx->state = REALTIME_HTTP_WANT_INITIATE;
286     ctx->count = 0;
287     ctx->bytes_read = 0;
288     ctx->bytes_written = 0;
289     ctx->bytes_expected = 0;
290     if(ctx->buffer) free(ctx->buffer);
291     ctx->buffer = NULL;
292     noit_connection_ctx_dealloc(nctx);
293     eventer_remove_fd(e->fd);
294     e->opset->close(e->fd, &mask, e);
295     return 0;
296   }
297
298 #define full_nb_write(data, wlen) do { \
299   if(!ctx->bytes_expected) { \
300     ctx->bytes_written = 0; \
301     ctx->bytes_expected = wlen; \
302   } \
303   while(ctx->bytes_written < ctx->bytes_expected) { \
304     while(-1 == (len = e->opset->write(e->fd, ((char *)data) + ctx->bytes_written, \
305                                        ctx->bytes_expected - ctx->bytes_written, \
306                                        &mask, e)) && errno == EINTR); \
307     if(len < 0) { \
308       if(errno == EAGAIN) return mask | EVENTER_EXCEPTION; \
309       goto socket_error; \
310     } \
311     ctx->bytes_written += len; \
312   } \
313   if(ctx->bytes_written != ctx->bytes_expected) { \
314     noitL(noit_error, "short write on initiating stream [%d != %d].\n", \
315           ctx->bytes_written, ctx->bytes_expected); \
316     goto socket_error; \
317   } \
318   ctx->bytes_expected = 0; \
319 } while(0)
320
321   while(1) {
322     u_int32_t net_body_len;
323
324     switch(ctx->state) {
325       case REALTIME_HTTP_WANT_INITIATE:
326         full_nb_write(&livestream_cmd, sizeof(livestream_cmd));
327         ctx->state = REALTIME_HTTP_WANT_SEND_INTERVAL;
328       case REALTIME_HTTP_WANT_SEND_INTERVAL:
329         nint = htonl(ctx->rt->interval);
330         full_nb_write(&nint, sizeof(nint));
331         ctx->state = REALTIME_HTTP_WANT_SEND_UUID;
332       case REALTIME_HTTP_WANT_SEND_UUID:
333         uuid_unparse_lower(ctx->rt->checkid, uuid_str);
334         full_nb_write(uuid_str, 36);
335         ctx->state = REALTIME_HTTP_WANT_HEADER;
336       case REALTIME_HTTP_WANT_HEADER:
337         FULLREAD(e, ctx, sizeof(u_int32_t));
338         memcpy(&net_body_len, ctx->buffer, sizeof(u_int32_t));
339         ctx->body_len = ntohl(net_body_len);
340         free(ctx->buffer); ctx->buffer = NULL;
341         ctx->state = REALTIME_HTTP_WANT_BODY;
342         break;
343       case REALTIME_HTTP_WANT_BODY:
344         FULLREAD(e, ctx, ctx->body_len);
345         if(stratcon_line_to_javascript(ctx->ctx, ctx->buffer)) goto socket_error;
346         free(ctx->buffer); ctx->buffer = NULL;
347         ctx->state = REALTIME_HTTP_WANT_HEADER;
348         break;
349     }
350   }
351
352 }
353
354 int
355 stratcon_realtime_http_postresolve(eventer_t e, int mask, void *closure,
356                                    struct timeval *now) {
357   noit_http_session_ctx *ctx = closure;
358   realtime_context *rc = ctx->dispatcher_closure;
359   struct realtime_tracker *node;
360
361   for(node = rc->checklist; node; node = node->next) {
362     if(node->noit) {
363       realtime_recv_ctx_t *rrctx;
364       rrctx = calloc(1, sizeof(*rrctx));
365       rrctx->ctx = ctx;
366       rrctx->rt = node;
367       stratcon_streamer_connection(NULL, node->noit,
368                                    stratcon_realtime_recv_handler,
369                                    NULL, rrctx,
370                                    free_realtime_recv_ctx);
371     }
372     else
373       noit_atomic_dec32(&ctx->ref_cnt);
374   }
375   if(ctx->ref_cnt == 1) {
376     noit_http_response_end(ctx);
377     clear_realtime_context(rc);
378     if(ctx->conn.e) eventer_trigger(ctx->conn.e, EVENTER_WRITE);
379   }
380   return 0;
381 }
382 int
383 stratcon_request_dispatcher(noit_http_session_ctx *ctx) {
384   const char *key, *value;
385   realtime_context *rc = ctx->dispatcher_closure;
386   int klen;
387   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
388   noit_http_request *req = &ctx->req;
389
390   if(rc->setup == RC_INITIAL) {
391     eventer_t completion;
392     struct realtime_tracker *node;
393     char c[1024];
394     int num_interests;
395
396     num_interests = stratcon_realtime_uri_parse(rc, ctx->req.uri_str);
397     if(num_interests == 0) {
398       noit_http_response_status_set(ctx, 404, "OK");
399       noit_http_response_option_set(ctx, NOIT_HTTP_CLOSE);
400       noit_http_response_end(ctx);
401       return 0;
402     }
403
404     noitL(noit_error, "http: %s %s %s\n",
405           req->method_str, req->uri_str, req->protocol_str);
406     while(noit_hash_next_str(&req->headers, &iter, &key, &klen, &value)) {
407       noitL(noit_error, "http: [%s: %s]\n", key, value);
408     }
409     noit_http_response_status_set(ctx, 200, "OK");
410     noit_http_response_option_set(ctx, NOIT_HTTP_CHUNKED);
411     /*noit_http_response_option_set(ctx, NOIT_HTTP_GZIP);*/
412     /*noit_http_response_option_set(ctx, NOIT_HTTP_DEFLATE);*/
413     noit_http_response_header_set(ctx, "Content-Type", "text/html");
414
415     snprintf(c, sizeof(c),
416              "<html><head><script>document.domain='%s';</script></head><body>\n",
417              rc->document_domain);
418     noit_http_response_append(ctx, c, strlen(c));
419
420     /* this dumb crap is to make some browsers happy (Safari) */
421     memset(c, ' ', sizeof(c));
422     noit_http_response_append(ctx, c, sizeof(c));
423     noit_http_response_flush(ctx, noit_false);
424
425     rc->setup = RC_REQ_RECV;
426     /* Each interest references the ctx */
427     for(node = rc->checklist; node; node = node->next) {
428       noit_atomic_inc32(&ctx->ref_cnt);
429       stratcon_datastore_push(DS_OP_FIND, NULL, node);
430       noitL(noit_error, "Resolving sid: %d\n", node->sid);
431     }
432     completion = eventer_alloc();
433     completion->mask = EVENTER_TIMER;
434     completion->callback = stratcon_realtime_http_postresolve;
435     completion->closure = ctx;
436     gettimeofday(&completion->whence, NULL);
437     stratcon_datastore_push(DS_OP_FIND_COMPLETE, NULL, completion);
438   }
439   return EVENTER_EXCEPTION;
440 }
441 int
442 stratcon_realtime_http_handler(eventer_t e, int mask, void *closure,
443                                struct timeval *now) {
444   acceptor_closure_t *ac = closure;
445   noit_http_session_ctx *http_ctx = ac->service_ctx;
446   return http_ctx->drive(e, mask, http_ctx, now);
447 }
448 static int
449 rest_stream_data(noit_http_rest_closure_t *restc,
450                  int npats, char **pats) {
451   /* We're here and want to subvert the rest system */
452   const char *document_domain = NULL;
453   noit_http_session_ctx *ctx = restc->http_ctx;
454
455   /* Rewire the handler */
456   restc->ac->service_ctx = ctx;
457
458   if(!noit_hash_retr_str(restc->ac->config,
459                          "document_domain", strlen("document_domain"),
460                          &document_domain)) {
461     noitL(noit_error, "Document domain not set!  Realtime streaming will be broken\n");
462     document_domain = "";
463   }
464   noit_http_rest_closure_free(restc);
465
466   /* Rewire the http context */
467   ctx->conn.e->callback = stratcon_realtime_http_handler;
468   ctx->dispatcher = stratcon_request_dispatcher;
469   ctx->dispatcher_closure = alloc_realtime_context(document_domain);
470   //ctx->drive = stratcon_realtime_http_handler;
471   return stratcon_request_dispatcher(ctx);
472 }
473
474 void
475 stratcon_realtime_http_init(const char *toplevel) {
476   eventer_name_callback("stratcon_realtime_http",
477                         stratcon_realtime_http_handler);
478   assert(noit_http_rest_register(
479     "GET", "/data/", "^((?:\\d+(?:@\\d+)?)(?:/\\d+(?:@\\d+)?)*)$",
480     rest_stream_data
481   ) == 0);
482 }
Note: See TracBrowser for help on using the browser.