root/src/stratcon_jlog_streamer.c

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

I sure hope this doesn't break other platforms too badly. Solaris support sans the eventer... untested, of course. refs #32.

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