root/src/stratcon_jlog_streamer.c

Revision d346b50002d020e7864b6c06da3bbb90c3f30c8e, 17.9 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 5 years ago)

ARGH! refs #128

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