root/src/stratcon_jlog_streamer.c

Revision 9ae46347d8ade4004022aa28bfe4dc8ed04689d7, 13.9 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 11 years ago)

handle closed sessions

  • 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     return 0;
180   }
181
182   while(1) {
183     switch(ctx->state) {
184       case WANT_COUNT:
185         FULLREAD(e, ctx, sizeof(u_int32_t));
186         memcpy(&ctx->count, ctx->buffer, sizeof(u_int32_t));
187         ctx->count = ntohl(ctx->count);
188         free(ctx->buffer); ctx->buffer = NULL;
189         ctx->state = WANT_HEADER;
190         break;
191
192       case WANT_HEADER:
193         if(ctx->count == 0) {
194           ctx->state = WANT_COUNT;
195           break;
196         }
197         FULLREAD(e, ctx, sizeof(ctx->header));
198         memcpy(&ctx->header, ctx->buffer, sizeof(ctx->header));
199         ctx->header.chkpt.log = ntohl(ctx->header.chkpt.log);
200         ctx->header.chkpt.marker = ntohl(ctx->header.chkpt.marker);
201         ctx->header.tv_sec = ntohl(ctx->header.tv_sec);
202         ctx->header.tv_usec = ntohl(ctx->header.tv_usec);
203         ctx->header.message_len = ntohl(ctx->header.message_len);
204         free(ctx->buffer); ctx->buffer = NULL;
205         ctx->state = WANT_BODY;
206         break;
207
208       case WANT_BODY:
209         FULLREAD(e, ctx, ctx->header.message_len);
210         stratcon_datastore_push(DS_OP_INSERT, &ctx->r.remote, ctx->buffer);
211         /* Don't free the buffer, it's used by the datastore process. */
212         ctx->buffer = NULL;
213         ctx->count--;
214         if(ctx->count == 0) {
215           eventer_t completion_e;
216           eventer_remove_fd(e->fd);
217           completion_e = eventer_alloc();
218           memcpy(completion_e, e, sizeof(*e));
219           completion_e->mask = EVENTER_WRITE | EVENTER_EXCEPTION;
220           ctx->state = WANT_CHKPT;
221           stratcon_datastore_push(DS_OP_CHKPT, &ctx->r.remote, completion_e);
222           noitL(noit_debug, "Pushing batch asynch...\n");
223           return 0;
224         } else
225           ctx->state = WANT_HEADER;
226         break;
227
228       case WANT_CHKPT:
229         noitL(noit_debug, "Pushing checkpoint: [%u/%u]\n",
230               ctx->header.chkpt.log, ctx->header.chkpt.marker);
231         n_chkpt.log = htonl(ctx->header.chkpt.log);
232         n_chkpt.marker = htonl(ctx->header.chkpt.marker);
233
234         /* screw short writes.  I'd rather die than not write my data! */
235         len = e->opset->write(e->fd, &n_chkpt, sizeof(jlog_id),
236                               &mask, e);
237         if(len < 0) {
238           if(errno == EAGAIN) return mask | EVENTER_EXCEPTION;
239           goto socket_error;
240         }
241         if(len != sizeof(jlog_id)) {
242           noitL(noit_error, "short write on checkpointing stream.\n");
243           goto socket_error;
244         }
245         ctx->state = WANT_COUNT;
246         break;
247     }
248   }
249   /* never get here */
250 }
251
252 int
253 jlog_streamer_ssl_upgrade(eventer_t e, int mask, void *closure,
254                           struct timeval *now) {
255   jlog_streamer_ctx_t *ctx = closure;
256   int rv;
257
258   rv = eventer_SSL_connect(e, &mask);
259   if(rv > 0) {
260     eventer_ssl_ctx_t *sslctx;
261     e->callback = stratcon_jlog_recv_handler;
262     /* We must make a copy of the acceptor_closure_t for each new
263      * connection.
264      */
265     if((sslctx = eventer_get_eventer_ssl_ctx(e)) != NULL) {
266       char *cn, *end;
267       cn = eventer_ssl_get_peer_subject(sslctx);
268       if(cn && (cn = strstr(cn, "CN=")) != NULL) {
269         cn += 3;
270         end = cn;
271         while(*end && *end != '/') end++;
272         ctx->remote_cn = malloc(end - cn + 1);
273         memcpy(ctx->remote_cn, cn, end - cn);
274         ctx->remote_cn[end-cn] = '\0';
275       }
276     }
277     return e->callback(e, mask, e->closure, now);
278   }
279   if(errno == EAGAIN) return mask | EVENTER_EXCEPTION;
280
281   eventer_remove_fd(e->fd);
282   e->opset->close(e->fd, &mask, e);
283   jlog_streamer_schedule_reattempt(ctx, now);
284   return 0;
285 }
286 int
287 jlog_streamer_complete_connect(eventer_t e, int mask, void *closure,
288                                struct timeval *now) {
289   jlog_streamer_ctx_t *ctx = closure;
290   char *cert, *key, *ca, *ciphers;
291   eventer_ssl_ctx_t *sslctx;
292
293   if(mask & EVENTER_EXCEPTION) {
294  connect_error:
295     eventer_remove_fd(e->fd);
296     e->opset->close(e->fd, &mask, e);
297     jlog_streamer_schedule_reattempt(ctx, now);
298     return 0;
299   }
300
301 #define SSLCONFGET(var,name) do { \
302   if(!noit_hash_retrieve(ctx->sslconfig, name, strlen(name), \
303                          (void **)&var)) var = NULL; } while(0)
304   SSLCONFGET(cert, "certificate_file");
305   SSLCONFGET(key, "key_file");
306   SSLCONFGET(ca, "ca_chain");
307   SSLCONFGET(ciphers, "ciphers");
308   sslctx = eventer_ssl_ctx_new(SSL_CLIENT, cert, key, ca, ciphers);
309   if(!sslctx) goto connect_error;
310
311   eventer_ssl_ctx_set_verify(sslctx, eventer_ssl_verify_cert,
312                              ctx->sslconfig);
313   EVENTER_ATTACH_SSL(e, sslctx);
314   e->callback = jlog_streamer_ssl_upgrade;
315   return e->callback(e, mask, closure, now);
316 }
317 static void
318 jlog_streamer_initiate_connection(jlog_streamer_ctx_t *ctx) {
319   struct timeval __now;
320   eventer_t e;
321   int rv, fd = -1;
322   long on;
323
324   /* Open a socket */
325   fd = socket(ctx->r.remote.sa_family, SOCK_STREAM, 0);
326   if(fd < 0) goto reschedule;
327
328   /* Make it non-blocking */
329   on = 1;
330   if(ioctl(fd, FIONBIO, &on)) goto reschedule;
331
332   /* Initiate a connection */
333   ctx->r.remote.sa_len = ctx->remote_len;
334   rv = connect(fd, &ctx->r.remote, ctx->remote_len);
335   if(rv == -1 && errno != EINPROGRESS) goto reschedule;
336
337   /* Register a handler for connection completion */
338   e = eventer_alloc();
339   e->fd = fd;
340   e->mask = EVENTER_READ | EVENTER_WRITE | EVENTER_EXCEPTION;
341   e->callback = jlog_streamer_complete_connect;
342   e->closure = ctx;
343   eventer_add(e);
344   return;
345
346  reschedule:
347   if(fd >= 0) close(fd);
348   gettimeofday(&__now, NULL);
349   jlog_streamer_schedule_reattempt(ctx, &__now);
350   return;
351 }
352
353 int
354 initiate_jlog_streamer(const char *host, unsigned short port,
355                        noit_hash_table *sslconfig, noit_hash_table *config) {
356   jlog_streamer_ctx_t *ctx;
357
358   int8_t family;
359   int rv;
360   union {
361     struct in_addr addr4;
362     struct in6_addr addr6;
363   } a;
364
365   if(host[0] == '/') {
366     family = AF_UNIX;
367   }
368   else {
369     family = AF_INET;
370     rv = inet_pton(family, host, &a);
371     if(rv != 1) {
372       family = AF_INET6;
373       rv = inet_pton(family, host, &a);
374       if(rv != 1) {
375         noitL(noit_stderr, "Cannot translate '%s' to IP\n", host);
376         return -1;
377       }
378     }
379   }
380
381   ctx = jlog_streamer_ctx_alloc();
382  
383   memset(&ctx->r, 0, sizeof(ctx->r));
384   if(family == AF_UNIX) {
385     struct sockaddr_un *s = &ctx->r.remote_un;
386     s->sun_family = AF_UNIX;
387     strncpy(s->sun_path, host, sizeof(s->sun_path)-1);
388     ctx->remote_len = sizeof(*s);
389   }
390   else if(family == AF_INET) {
391     struct sockaddr_in *s = &ctx->r.remote_in;
392     s->sin_family = family;
393     s->sin_port = htons(port);
394     memcpy(&s->sin_addr, &a, sizeof(struct in_addr));
395     ctx->remote_len = sizeof(*s);
396   }
397   else {
398     struct sockaddr_in6 *s = &ctx->r.remote_in6;
399     s->sin6_family = family;
400     s->sin6_port = htons(port);
401     memcpy(&s->sin6_addr, &a, sizeof(a));
402     ctx->remote_len = sizeof(*s);
403   }
404
405   if(ctx->sslconfig)
406     noit_hash_delete_all(ctx->sslconfig, free, free);
407   else
408     ctx->sslconfig = calloc(1, sizeof(noit_hash_table));
409   noit_hash_merge_as_dict(ctx->sslconfig, sslconfig);
410   if(ctx->config)
411     noit_hash_delete_all(ctx->config, free, free);
412   else
413     ctx->config = calloc(1, sizeof(noit_hash_table));
414   noit_hash_merge_as_dict(ctx->config, config);
415
416   jlog_streamer_initiate_connection(ctx);
417   return 0;
418 }
419
420 void
421 stratcon_jlog_streamer_reload(const char *toplevel) {
422   int i, cnt = 0;
423   noit_conf_section_t *noit_configs;
424   char path[256];
425
426   snprintf(path, sizeof(path), "/%s/noits//noit", toplevel ? toplevel : "*");
427   noit_configs = noit_conf_get_sections(NULL, path, &cnt);
428   noitL(noit_error, "Found %d %s stanzas\n", cnt, path);
429   for(i=0; i<cnt; i++) {
430     char address[256];
431     unsigned short port;
432     int portint;
433     noit_hash_table *sslconfig, *config;
434
435     if(!noit_conf_get_stringbuf(noit_configs[i],
436                                 "ancestor-or-self::node()/@address",
437                                 address, sizeof(address))) {
438       noitL(noit_error, "address attribute missing in noit %d\n", i+1);
439       continue;
440     }
441     if(!noit_conf_get_int(noit_configs[i],
442                           "ancestor-or-self::node()/@port", &portint))
443       portint = 0;
444     port = (unsigned short) portint;
445     if(address[0] != '/' && (portint == 0 || (port != portint))) {
446       /* UNIX sockets don't require a port (they'll ignore it if specified */
447       noitL(noit_stderr,
448             "Invalid port [%d] specified in stanza %d\n", port, i+1);
449       continue;
450     }
451     sslconfig = noit_conf_get_hash(noit_configs[i], "sslconfig");
452     config = noit_conf_get_hash(noit_configs[i], "config");
453
454     initiate_jlog_streamer(address, port, sslconfig, config);
455   }
456 }
457
458 void
459 stratcon_jlog_streamer_init(const char *toplevel) {
460   eventer_name_callback("jlog_streamer_reinitiate",
461                         jlog_streamer_reinitiate);
462   eventer_name_callback("stratcon_jlog_recv_handler",
463                         stratcon_jlog_recv_handler);
464   eventer_name_callback("jlog_streamer_ssl_upgrade",
465                         jlog_streamer_ssl_upgrade);
466   eventer_name_callback("jlog_streamer_complete_connect",
467                         jlog_streamer_complete_connect);
468   stratcon_jlog_streamer_reload(toplevel);
469 }
Note: See TracBrowser for help on using the browser.