root/src/stratcon_jlog_streamer.c

Revision 21b0c6c1011f78327925b8a1914d98cdd5cd43d5, 16.1 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 6 years ago)

first whack at feeding actual data. refs #71

  • 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 #include "eventer/eventer.h"
8 #include "noit_conf.h"
9 #include "utils/noit_hash.h"
10 #include "utils/noit_log.h"
11 #include "jlog/jlog.h"
12 #include "noit_jlog_listener.h"
13 #include "stratcon_datastore.h"
14 #include "stratcon_jlog_streamer.h"
15
16 #include <unistd.h>
17 #include <assert.h>
18 #include <errno.h>
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #ifdef HAVE_SYS_FILIO_H
22 #include <sys/filio.h>
23 #endif
24 #include <netinet/in.h>
25 #include <sys/un.h>
26 #include <arpa/inet.h>
27
28 noit_hash_table noits = NOIT_HASH_EMPTY;
29
30 typedef struct jlog_streamer_ctx_t {
31   int bytes_expected;
32   int bytes_read;
33   char *buffer;         /* These guys are for doing partial reads */
34
35   enum {
36     WANT_INITIATE = 0,
37     WANT_COUNT = 1,
38     WANT_HEADER = 2,
39     WANT_BODY = 3,
40     WANT_CHKPT = 4,
41   } state;
42   int count;            /* Number of jlog messages we need to read */
43   struct {
44     jlog_id   chkpt;
45     u_int32_t tv_sec;
46     u_int32_t tv_usec;
47     u_int32_t message_len;
48   } header;
49 } jlog_streamer_ctx_t;
50
51 static void noit_connection_initiate_connection(noit_connection_ctx_t *ctx);
52
53 jlog_streamer_ctx_t *
54 jlog_streamer_ctx_alloc(void) {
55   jlog_streamer_ctx_t *ctx;
56   ctx = calloc(1, sizeof(*ctx));
57   return ctx;
58 }
59 noit_connection_ctx_t *
60 noit_connection_ctx_alloc(void) {
61   noit_connection_ctx_t *ctx;
62   ctx = calloc(1, sizeof(*ctx));
63   return ctx;
64 }
65 int
66 noit_connection_reinitiate(eventer_t e, int mask, void *closure,
67                          struct timeval *now) {
68   noit_connection_ctx_t *ctx = closure;
69   ctx->timeout_event = NULL;
70   noit_connection_initiate_connection(closure);
71   return 0;
72 }
73 void
74 noit_connection_schedule_reattempt(noit_connection_ctx_t *ctx,
75                                    struct timeval *now) {
76   struct timeval __now, interval;
77   const char *v;
78   u_int32_t min_interval = 1000, max_interval = 60000;
79   if(noit_hash_retrieve(ctx->config,
80                         "reconnect_initial_interval",
81                         strlen("reconnect_initial_interval"),
82                         (void **)&v)) {
83     min_interval = MAX(atoi(v), 100); /* .1 second minimum */
84   }
85   if(noit_hash_retrieve(ctx->config,
86                         "reconnect_maximum_interval",
87                         strlen("reconnect_maximum_interval"),
88                         (void **)&v)) {
89     max_interval = MIN(atoi(v), 3600*1000); /* 1 hour maximum */
90   }
91   if(ctx->current_backoff == 0) ctx->current_backoff = min_interval;
92   else {
93     ctx->current_backoff *= 2;
94     ctx->current_backoff = MAX(min_interval, ctx->current_backoff);
95     ctx->current_backoff = MIN(max_interval, ctx->current_backoff);
96   }
97   if(!now) {
98     gettimeofday(&__now, NULL);
99     now = &__now;
100   }
101   interval.tv_sec = ctx->current_backoff / 1000;
102   interval.tv_usec = (ctx->current_backoff % 1000) * 1000;
103   noitL(noit_debug, "Next jlog_streamer attempt in %ums\n",
104         ctx->current_backoff);
105   if(ctx->timeout_event)
106     eventer_remove(ctx->timeout_event);
107   else
108     ctx->timeout_event = eventer_alloc();
109   ctx->timeout_event->callback = noit_connection_reinitiate;
110   ctx->timeout_event->closure = ctx;
111   ctx->timeout_event->mask = EVENTER_TIMER;
112   add_timeval(*now, interval, &ctx->timeout_event->whence);
113   eventer_add(ctx->timeout_event);
114 }
115 void
116 noit_connection_ctx_free(noit_connection_ctx_t *ctx) {
117   if(ctx->remote_cn) free(ctx->remote_cn);
118   if(ctx->timeout_event) {
119     eventer_remove(ctx->timeout_event);
120     eventer_free(ctx->timeout_event);
121   }
122   ctx->consumer_free(ctx->consumer_ctx);
123   free(ctx);
124 }
125 void
126 jlog_streamer_ctx_free(void *cl) {
127   jlog_streamer_ctx_t *ctx = cl;
128   if(ctx->buffer) free(ctx->buffer);
129   free(ctx);
130 }
131
132 #define Eread(a,b) e->opset->read(e->fd, (a), (b), &mask, e)
133 static int
134 __read_on_ctx(eventer_t e, jlog_streamer_ctx_t *ctx, int *newmask) {
135   int len, mask;
136   while(ctx->bytes_read < ctx->bytes_expected) {
137     len = Eread(ctx->buffer + ctx->bytes_read,
138                 ctx->bytes_expected - ctx->bytes_read);
139     if(len < 0) {
140       *newmask = mask;
141       return -1;
142     }
143     /* if we get 0 inside SSL, and there was a real error, we
144      * will actually get a -1 here.
145      * if(len == 0) return ctx->bytes_read;
146      */
147     ctx->bytes_read += len;
148   }
149   assert(ctx->bytes_read == ctx->bytes_expected);
150   return ctx->bytes_read;
151 }
152 #define FULLREAD(e,ctx,size) do { \
153   int mask, len; \
154   if(!ctx->bytes_expected) { \
155     ctx->bytes_expected = size; \
156     if(ctx->buffer) free(ctx->buffer); \
157     ctx->buffer = malloc(size + 1); \
158     if(ctx->buffer == NULL) { \
159       noitL(noit_error, "malloc(%lu) failed.\n", size + 1); \
160       goto socket_error; \
161     } \
162     ctx->buffer[size] = '\0'; \
163   } \
164   len = __read_on_ctx(e, ctx, &mask); \
165   if(len < 0) { \
166     if(errno == EAGAIN) return mask | EVENTER_EXCEPTION; \
167     noitL(noit_error, "SSL read error: %s\n", strerror(errno)); \
168     goto socket_error; \
169   } \
170   ctx->bytes_read = 0; \
171   ctx->bytes_expected = 0; \
172   if(len != size) { \
173     noitL(noit_error, "SSL short read [%d] (%d/%lu).  Reseting connection.\n", \
174           ctx->state, len, size); \
175     goto socket_error; \
176   } \
177 } while(0)
178
179 int
180 stratcon_jlog_recv_handler(eventer_t e, int mask, void *closure,
181                            struct timeval *now) {
182   static u_int32_t jlog_feed_cmd = 0;
183   noit_connection_ctx_t *nctx = closure;
184   jlog_streamer_ctx_t *ctx = nctx->consumer_ctx;
185   int len;
186   jlog_id n_chkpt;
187
188   if(!jlog_feed_cmd) jlog_feed_cmd = htonl(NOIT_JLOG_DATA_FEED);
189
190   if(mask & EVENTER_EXCEPTION || nctx->wants_shutdown) {
191  socket_error:
192     ctx->state = WANT_INITIATE;
193     ctx->count = 0;
194     ctx->bytes_read = 0;
195     ctx->bytes_expected = 0;
196     if(ctx->buffer) free(ctx->buffer);
197     ctx->buffer = NULL;
198     noit_connection_schedule_reattempt(nctx, now);
199     eventer_remove_fd(e->fd);
200     e->opset->close(e->fd, &mask, e);
201     return 0;
202   }
203
204   while(1) {
205     switch(ctx->state) {
206       case WANT_INITIATE:
207         len = e->opset->write(e->fd, &jlog_feed_cmd, sizeof(&jlog_feed_cmd),
208                               &mask, e);
209         if(len < 0) {
210           if(errno == EAGAIN) return mask | EVENTER_EXCEPTION;
211           goto socket_error;
212         }
213         if(len != sizeof(jlog_feed_cmd)) {
214           noitL(noit_error, "short write on initiating stream.\n");
215           goto socket_error;
216         }
217         ctx->state = WANT_COUNT;
218         break;
219
220       case WANT_COUNT:
221         FULLREAD(e, ctx, sizeof(u_int32_t));
222         memcpy(&ctx->count, ctx->buffer, sizeof(u_int32_t));
223         ctx->count = ntohl(ctx->count);
224         free(ctx->buffer); ctx->buffer = NULL;
225         ctx->state = WANT_HEADER;
226         break;
227
228       case WANT_HEADER:
229         if(ctx->count == 0) {
230           ctx->state = WANT_COUNT;
231           break;
232         }
233         FULLREAD(e, ctx, sizeof(ctx->header));
234         memcpy(&ctx->header, ctx->buffer, sizeof(ctx->header));
235         ctx->header.chkpt.log = ntohl(ctx->header.chkpt.log);
236         ctx->header.chkpt.marker = ntohl(ctx->header.chkpt.marker);
237         ctx->header.tv_sec = ntohl(ctx->header.tv_sec);
238         ctx->header.tv_usec = ntohl(ctx->header.tv_usec);
239         ctx->header.message_len = ntohl(ctx->header.message_len);
240         free(ctx->buffer); ctx->buffer = NULL;
241         ctx->state = WANT_BODY;
242         break;
243
244       case WANT_BODY:
245         FULLREAD(e, ctx, (unsigned long)ctx->header.message_len);
246         stratcon_datastore_push(DS_OP_INSERT, &nctx->r.remote, ctx->buffer);
247         /* Don't free the buffer, it's used by the datastore process. */
248         ctx->buffer = NULL;
249         ctx->count--;
250         if(ctx->count == 0) {
251           eventer_t completion_e;
252           eventer_remove_fd(e->fd);
253           completion_e = eventer_alloc();
254           memcpy(completion_e, e, sizeof(*e));
255           completion_e->mask = EVENTER_WRITE | EVENTER_EXCEPTION;
256           ctx->state = WANT_CHKPT;
257           stratcon_datastore_push(DS_OP_CHKPT, &nctx->r.remote, completion_e);
258           noitL(noit_debug, "Pushing batch asynch...\n");
259           return 0;
260         } else
261           ctx->state = WANT_HEADER;
262         break;
263
264       case WANT_CHKPT:
265         noitL(noit_debug, "Pushing checkpoint: [%u/%u]\n",
266               ctx->header.chkpt.log, ctx->header.chkpt.marker);
267         n_chkpt.log = htonl(ctx->header.chkpt.log);
268         n_chkpt.marker = htonl(ctx->header.chkpt.marker);
269
270         /* screw short writes.  I'd rather die than not write my data! */
271         len = e->opset->write(e->fd, &n_chkpt, sizeof(jlog_id),
272                               &mask, e);
273         if(len < 0) {
274           if(errno == EAGAIN) return mask | EVENTER_EXCEPTION;
275           goto socket_error;
276         }
277         if(len != sizeof(jlog_id)) {
278           noitL(noit_error, "short write on checkpointing stream.\n");
279           goto socket_error;
280         }
281         ctx->state = WANT_COUNT;
282         break;
283     }
284   }
285   /* never get here */
286 }
287
288 int
289 noit_connection_ssl_upgrade(eventer_t e, int mask, void *closure,
290                             struct timeval *now) {
291   noit_connection_ctx_t *nctx = closure;
292   int rv;
293
294   rv = eventer_SSL_connect(e, &mask);
295   if(rv > 0) {
296     eventer_ssl_ctx_t *sslctx;
297     e->callback = nctx->consumer_callback;
298     /* We must make a copy of the acceptor_closure_t for each new
299      * connection.
300      */
301     if((sslctx = eventer_get_eventer_ssl_ctx(e)) != NULL) {
302       char *cn, *end;
303       cn = eventer_ssl_get_peer_subject(sslctx);
304       if(cn && (cn = strstr(cn, "CN=")) != NULL) {
305         cn += 3;
306         end = cn;
307         while(*end && *end != '/') end++;
308         nctx->remote_cn = malloc(end - cn + 1);
309         memcpy(nctx->remote_cn, cn, end - cn);
310         nctx->remote_cn[end-cn] = '\0';
311       }
312     }
313     return e->callback(e, mask, e->closure, now);
314   }
315   if(errno == EAGAIN) return mask | EVENTER_EXCEPTION;
316
317   eventer_remove_fd(e->fd);
318   e->opset->close(e->fd, &mask, e);
319   noit_connection_schedule_reattempt(nctx, now);
320   return 0;
321 }
322 int
323 noit_connection_complete_connect(eventer_t e, int mask, void *closure,
324                                  struct timeval *now) {
325   noit_connection_ctx_t *nctx = closure;
326   char *cert, *key, *ca, *ciphers;
327   eventer_ssl_ctx_t *sslctx;
328
329   if(mask & EVENTER_EXCEPTION) {
330  connect_error:
331     eventer_remove_fd(e->fd);
332     e->opset->close(e->fd, &mask, e);
333     noit_connection_schedule_reattempt(nctx, now);
334     return 0;
335   }
336
337 #define SSLCONFGET(var,name) do { \
338   if(!noit_hash_retrieve(nctx->sslconfig, name, strlen(name), \
339                          (void **)&var)) var = NULL; } while(0)
340   SSLCONFGET(cert, "certificate_file");
341   SSLCONFGET(key, "key_file");
342   SSLCONFGET(ca, "ca_chain");
343   SSLCONFGET(ciphers, "ciphers");
344   sslctx = eventer_ssl_ctx_new(SSL_CLIENT, cert, key, ca, ciphers);
345   if(!sslctx) goto connect_error;
346
347   eventer_ssl_ctx_set_verify(sslctx, eventer_ssl_verify_cert,
348                              nctx->sslconfig);
349   EVENTER_ATTACH_SSL(e, sslctx);
350   e->callback = noit_connection_ssl_upgrade;
351   return e->callback(e, mask, closure, now);
352 }
353 static void
354 noit_connection_initiate_connection(noit_connection_ctx_t *nctx) {
355   struct timeval __now;
356   eventer_t e;
357   int rv, fd = -1;
358   long on;
359
360   /* Open a socket */
361   fd = socket(nctx->r.remote.sa_family, SOCK_STREAM, 0);
362   if(fd < 0) goto reschedule;
363
364   /* Make it non-blocking */
365   on = 1;
366   if(ioctl(fd, FIONBIO, &on)) goto reschedule;
367
368   /* Initiate a connection */
369   rv = connect(fd, &nctx->r.remote, nctx->remote_len);
370   if(rv == -1 && errno != EINPROGRESS) goto reschedule;
371
372   /* Register a handler for connection completion */
373   e = eventer_alloc();
374   e->fd = fd;
375   e->mask = EVENTER_READ | EVENTER_WRITE | EVENTER_EXCEPTION;
376   e->callback = noit_connection_complete_connect;
377   e->closure = nctx;
378   eventer_add(e);
379   return;
380
381  reschedule:
382   if(fd >= 0) close(fd);
383   gettimeofday(&__now, NULL);
384   noit_connection_schedule_reattempt(nctx, &__now);
385   return;
386 }
387
388 int
389 initiate_noit_connection(const char *host, unsigned short port,
390                          noit_hash_table *sslconfig, noit_hash_table *config,
391                          eventer_func_t handler, void *closure,
392                          void (*freefunc)(void *)) {
393   noit_connection_ctx_t *ctx;
394
395   int8_t family;
396   int rv;
397   union {
398     struct in_addr addr4;
399     struct in6_addr addr6;
400   } a;
401
402   if(host[0] == '/') {
403     family = AF_UNIX;
404   }
405   else {
406     family = AF_INET;
407     rv = inet_pton(family, host, &a);
408     if(rv != 1) {
409       family = AF_INET6;
410       rv = inet_pton(family, host, &a);
411       if(rv != 1) {
412         noitL(noit_stderr, "Cannot translate '%s' to IP\n", host);
413         return -1;
414       }
415     }
416   }
417
418   ctx = noit_connection_ctx_alloc();
419  
420   memset(&ctx->r, 0, sizeof(ctx->r));
421   if(family == AF_UNIX) {
422     struct sockaddr_un *s = &ctx->r.remote_un;
423     s->sun_family = AF_UNIX;
424     strncpy(s->sun_path, host, sizeof(s->sun_path)-1);
425     ctx->remote_len = sizeof(*s);
426   }
427   else if(family == AF_INET) {
428     struct sockaddr_in *s = &ctx->r.remote_in;
429     s->sin_family = family;
430     s->sin_port = htons(port);
431     memcpy(&s->sin_addr, &a, sizeof(struct in_addr));
432     ctx->remote_len = sizeof(*s);
433   }
434   else {
435     struct sockaddr_in6 *s = &ctx->r.remote_in6;
436     s->sin6_family = family;
437     s->sin6_port = htons(port);
438     memcpy(&s->sin6_addr, &a, sizeof(a));
439     ctx->remote_len = sizeof(*s);
440   }
441
442   if(ctx->sslconfig)
443     noit_hash_delete_all(ctx->sslconfig, free, free);
444   else
445     ctx->sslconfig = calloc(1, sizeof(noit_hash_table));
446   noit_hash_merge_as_dict(ctx->sslconfig, sslconfig);
447   if(ctx->config)
448     noit_hash_delete_all(ctx->config, free, free);
449   else
450     ctx->config = calloc(1, sizeof(noit_hash_table));
451   noit_hash_merge_as_dict(ctx->config, config);
452
453   ctx->consumer_callback = handler;
454   ctx->consumer_free = freefunc;
455   ctx->consumer_ctx = closure;
456   noit_connection_initiate_connection(ctx);
457   return 0;
458 }
459
460 void
461 stratcon_streamer_connection(const char *toplevel, const char *destination,
462                              eventer_func_t handler,
463                              void *(*handler_alloc)(void), void *handler_ctx,
464                              void (*handler_free)(void *)) {
465   int i, cnt = 0;
466   noit_conf_section_t *noit_configs;
467   char path[256];
468
469   snprintf(path, sizeof(path), "/%s/noits//noit", toplevel ? toplevel : "*");
470   noit_configs = noit_conf_get_sections(NULL, path, &cnt);
471   noitL(noit_error, "Found %d %s stanzas\n", cnt, path);
472   for(i=0; i<cnt; i++) {
473     char address[256];
474     unsigned short port;
475     int portint;
476     noit_hash_table *sslconfig, *config;
477
478     if(!noit_conf_get_stringbuf(noit_configs[i],
479                                 "ancestor-or-self::node()/@address",
480                                 address, sizeof(address))) {
481       noitL(noit_error, "address attribute missing in noit %d\n", i+1);
482       continue;
483     }
484     /* if destination is specified, exact match it */
485     if(destination && strcmp(address, destination)) continue;
486
487     if(!noit_conf_get_int(noit_configs[i],
488                           "ancestor-or-self::node()/@port", &portint))
489       portint = 0;
490     port = (unsigned short) portint;
491     if(address[0] != '/' && (portint == 0 || (port != portint))) {
492       /* UNIX sockets don't require a port (they'll ignore it if specified */
493       noitL(noit_stderr,
494             "Invalid port [%d] specified in stanza %d\n", port, i+1);
495       continue;
496     }
497     sslconfig = noit_conf_get_hash(noit_configs[i], "sslconfig");
498     config = noit_conf_get_hash(noit_configs[i], "config");
499
500     initiate_noit_connection(address, port, sslconfig, config,
501                              handler,
502                              handler_alloc ? handler_alloc() : handler_ctx,
503                              handler_free);
504   }
505 }
506 void
507 stratcon_jlog_streamer_reload(const char *toplevel) {
508   stratcon_streamer_connection(toplevel, NULL,
509                                stratcon_jlog_recv_handler,
510                                (void *(*)())jlog_streamer_ctx_alloc, NULL,
511                                jlog_streamer_ctx_free);
512 }
513
514 void
515 stratcon_jlog_streamer_init(const char *toplevel) {
516   eventer_name_callback("noit_connection_reinitiate",
517                         noit_connection_reinitiate);
518   eventer_name_callback("stratcon_jlog_recv_handler",
519                         stratcon_jlog_recv_handler);
520   eventer_name_callback("noit_connection_ssl_upgrade",
521                         noit_connection_ssl_upgrade);
522   eventer_name_callback("noit_connection_complete_connect",
523                         noit_connection_complete_connect);
524   stratcon_jlog_streamer_reload(toplevel);
525 }
Note: See TracBrowser for help on using the browser.