root/src/stratcon_jlog_streamer.c

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

make remote_len a first-class struct member

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