root/src/stratcon_jlog_streamer.c

Revision 0c17b8ad7cf0f3be6cc19bb8def4f75a52757fb6, 13.9 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 6 years ago)

Don't forget to close the filedescriptor

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