root/src/stratcon_jlog_streamer.c

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

This is pretty intrusive.

Here we refactor the console initalization in noit_conf_checks to have
the reusable parts pulled into the noit_conf directly so that stratcon
can make use of them. noit_conf_checks is retooled to extend that and
override the 'ls' command to have it's old form and function.

stratcon_jlog_streamer extends the noit_conf console syntax to allow
adding and removing of noits within the 'configure terminal' mode.

# conf t
# noit 10.1.2.3
# noit 10.1.5.5:12345
# no noit 10.1.2.3
# no noit 10.1.5.5:12345

This should not change the operation of noitd's console in any way;
however, the changes were quite substantial, so we should keep an eye
out for collateral breakage.

refs #195

  • 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 "noit_rest.h"
40 #include "stratcon_datastore.h"
41 #include "stratcon_jlog_streamer.h"
42 #include "stratcon_iep.h"
43
44 #include <unistd.h>
45 #include <assert.h>
46 #include <errno.h>
47 #include <sys/types.h>
48 #include <sys/socket.h>
49 #ifdef HAVE_SYS_FILIO_H
50 #include <sys/filio.h>
51 #endif
52 #include <netinet/in.h>
53 #include <sys/un.h>
54 #include <arpa/inet.h>
55
56 pthread_mutex_t noits_lock;
57 noit_hash_table noits = NOIT_HASH_EMPTY;
58
59 static void noit_connection_initiate_connection(noit_connection_ctx_t *ctx);
60
61 static int
62 remote_str_sort(const void *a, const void *b) {
63   int rv;
64   noit_connection_ctx_t * const *actx = a;
65   noit_connection_ctx_t * const *bctx = b;
66   jlog_streamer_ctx_t *ajctx = (*actx)->consumer_ctx;
67   jlog_streamer_ctx_t *bjctx = (*bctx)->consumer_ctx;
68   rv = strcmp((*actx)->remote_str, (*bctx)->remote_str);
69   if(rv) return rv;
70   return (ajctx->jlog_feed_cmd < bjctx->jlog_feed_cmd) ? -1 :
71            ((ajctx->jlog_feed_cmd == bjctx->jlog_feed_cmd) ? 0 : 1);
72 }
73 static void
74 nc_print_noit_conn_brief(noit_console_closure_t ncct,
75                           noit_connection_ctx_t *ctx) {
76   jlog_streamer_ctx_t *jctx = ctx->consumer_ctx;
77   struct timeval now, diff, session_duration;
78   const char *feedtype = "unknown";
79   const char *lasttime = "never";
80   if(ctx->last_connect.tv_sec != 0) {
81     char cmdbuf[4096];
82     time_t r = ctx->last_connect.tv_sec;
83     struct tm tbuf, *tm;
84     tm = gmtime_r(&r, &tbuf);
85     strftime(cmdbuf, sizeof(cmdbuf), "%Y-%m-%d %H:%M:%S UTC", tm);
86     lasttime = cmdbuf;
87   }
88   nc_printf(ncct, "%s [%s]:\n\tLast connect: %s\n", ctx->remote_str,
89             ctx->remote_cn ? "connected" :
90                              (ctx->timeout_event ? "disconnected" :
91                                                    "connecting"), lasttime);
92   switch(ntohl(jctx->jlog_feed_cmd)) {
93     case NOIT_JLOG_DATA_FEED: feedtype = "durable/storage"; break;
94     case NOIT_JLOG_DATA_TEMP_FEED: feedtype = "transient/iep"; break;
95   }
96   nc_printf(ncct, "\tJLog event streamer [%s]\n", feedtype);
97   gettimeofday(&now, NULL);
98   if(ctx->timeout_event) {
99     sub_timeval(ctx->timeout_event->whence, now, &diff);
100     nc_printf(ncct, "\tNext attempt in %llu.%06us\n",
101               (unsigned long long)diff.tv_sec, (unsigned int) diff.tv_usec);
102   }
103   else if(ctx->remote_cn) {
104     nc_printf(ncct, "\tRemote CN: '%s'\n",
105               ctx->remote_cn ? ctx->remote_cn : "???");
106     if(ctx->consumer_callback == stratcon_jlog_recv_handler) {
107       struct timeval last;
108       double session_duration_seconds;
109       const char *state = "unknown";
110
111       switch(jctx->state) {
112         case JLOG_STREAMER_WANT_INITIATE: state = "initiate"; break;
113         case JLOG_STREAMER_WANT_COUNT: state = "waiting for next batch"; break;
114         case JLOG_STREAMER_WANT_HEADER: state = "reading header"; break;
115         case JLOG_STREAMER_WANT_BODY: state = "reading body"; break;
116         case JLOG_STREAMER_IS_ASYNC: state = "asynchronously processing"; break;
117         case JLOG_STREAMER_WANT_CHKPT: state = "checkpointing"; break;
118       }
119       last.tv_sec = jctx->header.tv_sec;
120       last.tv_usec = jctx->header.tv_usec;
121       sub_timeval(now, last, &diff);
122       sub_timeval(now, ctx->last_connect, &session_duration);
123       session_duration_seconds = session_duration.tv_sec +
124                                  (double)session_duration.tv_usec/1000000.0;
125       nc_printf(ncct, "\tState: %s\n"
126                       "\tNext checkpoint: [%08x:%08x]\n"
127                       "\tLast event: %llu.%06us ago\n"
128                       "\tEvents this session: %llu (%0.2f/s)\n"
129                       "\tOctets this session: %llu (%0.2f/s)\n",
130                 state,
131                 jctx->header.chkpt.log, jctx->header.chkpt.marker,
132                 (unsigned long long)diff.tv_sec, (unsigned int)diff.tv_usec,
133                 jctx->total_events,
134                 (double)jctx->total_events/session_duration_seconds,
135                 jctx->total_bytes_read,
136                 (double)jctx->total_bytes_read/session_duration_seconds);
137     }
138     else {
139       nc_printf(ncct, "\tUnknown type.\n");
140     }
141   }
142 }
143
144 jlog_streamer_ctx_t *
145 stratcon_jlog_streamer_datastore_ctx_alloc(void) {
146   jlog_streamer_ctx_t *ctx;
147   ctx = stratcon_jlog_streamer_ctx_alloc();
148   ctx->jlog_feed_cmd = htonl(NOIT_JLOG_DATA_FEED);
149   ctx->push = stratcon_datastore_push;
150   return ctx;
151 }
152 jlog_streamer_ctx_t *
153 stratcon_jlog_streamer_ctx_alloc(void) {
154   jlog_streamer_ctx_t *ctx;
155   ctx = calloc(1, sizeof(*ctx));
156   return ctx;
157 }
158 noit_connection_ctx_t *
159 noit_connection_ctx_alloc(void) {
160   noit_connection_ctx_t *ctx, **pctx;
161   ctx = calloc(1, sizeof(*ctx));
162   ctx->refcnt = 1;
163   pctx = malloc(sizeof(*pctx));
164   *pctx = ctx;
165   pthread_mutex_lock(&noits_lock);
166   noit_hash_store(&noits, (const char *)pctx, sizeof(*pctx), ctx);
167   pthread_mutex_unlock(&noits_lock);
168   return ctx;
169 }
170 int
171 noit_connection_reinitiate(eventer_t e, int mask, void *closure,
172                          struct timeval *now) {
173   noit_connection_ctx_t *ctx = closure;
174   ctx->timeout_event = NULL;
175   noit_connection_initiate_connection(closure);
176   return 0;
177 }
178 void
179 noit_connection_schedule_reattempt(noit_connection_ctx_t *ctx,
180                                    struct timeval *now) {
181   struct timeval __now, interval;
182   const char *v;
183   u_int32_t min_interval = 1000, max_interval = 8000;
184   if(ctx->remote_cn) {
185     free(ctx->remote_cn);
186     ctx->remote_cn = NULL;
187   }
188   if(noit_hash_retr_str(ctx->config,
189                         "reconnect_initial_interval",
190                         strlen("reconnect_initial_interval"),
191                         &v)) {
192     min_interval = MAX(atoi(v), 100); /* .1 second minimum */
193   }
194   if(noit_hash_retr_str(ctx->config,
195                         "reconnect_maximum_interval",
196                         strlen("reconnect_maximum_interval"),
197                         &v)) {
198     max_interval = MIN(atoi(v), 3600*1000); /* 1 hour maximum */
199   }
200   if(ctx->current_backoff == 0) ctx->current_backoff = min_interval;
201   else {
202     ctx->current_backoff *= 2;
203     ctx->current_backoff = MAX(min_interval, ctx->current_backoff);
204     ctx->current_backoff = MIN(max_interval, ctx->current_backoff);
205   }
206   if(!now) {
207     gettimeofday(&__now, NULL);
208     now = &__now;
209   }
210   interval.tv_sec = ctx->current_backoff / 1000;
211   interval.tv_usec = (ctx->current_backoff % 1000) * 1000;
212   noitL(noit_debug, "Next jlog_streamer attempt in %ums\n",
213         ctx->current_backoff);
214   if(ctx->timeout_event)
215     eventer_remove(ctx->timeout_event);
216   else
217     ctx->timeout_event = eventer_alloc();
218   ctx->timeout_event->callback = noit_connection_reinitiate;
219   ctx->timeout_event->closure = ctx;
220   ctx->timeout_event->mask = EVENTER_TIMER;
221   add_timeval(*now, interval, &ctx->timeout_event->whence);
222   eventer_add(ctx->timeout_event);
223 }
224 static void
225 noit_connection_ctx_free(noit_connection_ctx_t *ctx) {
226   if(ctx->remote_cn) free(ctx->remote_cn);
227   if(ctx->remote_str) free(ctx->remote_str);
228   if(ctx->timeout_event) {
229     eventer_remove(ctx->timeout_event);
230     eventer_free(ctx->timeout_event);
231   }
232   ctx->consumer_free(ctx->consumer_ctx);
233   free(ctx);
234 }
235 void
236 noit_connection_ctx_deref(noit_connection_ctx_t *ctx) {
237   if(noit_atomic_dec32(&ctx->refcnt) == 0)
238     noit_connection_ctx_free(ctx);
239 }
240 void
241 noit_connection_ctx_dealloc(noit_connection_ctx_t *ctx) {
242   noit_connection_ctx_t **pctx = &ctx;
243   pthread_mutex_lock(&noits_lock);
244   noit_hash_delete(&noits, (const char *)pctx, sizeof(*pctx),
245                    free, (void (*)(void *))noit_connection_ctx_deref);
246   pthread_mutex_unlock(&noits_lock);
247 }
248 void
249 jlog_streamer_ctx_free(void *cl) {
250   jlog_streamer_ctx_t *ctx = cl;
251   if(ctx->buffer) free(ctx->buffer);
252   free(ctx);
253 }
254
255 #define Eread(a,b) e->opset->read(e->fd, (a), (b), &mask, e)
256 static int
257 __read_on_ctx(eventer_t e, jlog_streamer_ctx_t *ctx, int *newmask) {
258   int len, mask;
259   while(ctx->bytes_read < ctx->bytes_expected) {
260     len = Eread(ctx->buffer + ctx->bytes_read,
261                 ctx->bytes_expected - ctx->bytes_read);
262     if(len < 0) {
263       *newmask = mask;
264       return -1;
265     }
266     /* if we get 0 inside SSL, and there was a real error, we
267      * will actually get a -1 here.
268      * if(len == 0) return ctx->bytes_read;
269      */
270     ctx->total_bytes_read += len;
271     ctx->bytes_read += len;
272   }
273   assert(ctx->bytes_read == ctx->bytes_expected);
274   return ctx->bytes_read;
275 }
276 #define FULLREAD(e,ctx,size) do { \
277   int mask, len; \
278   if(!ctx->bytes_expected) { \
279     ctx->bytes_expected = size; \
280     if(ctx->buffer) free(ctx->buffer); \
281     ctx->buffer = malloc(size + 1); \
282     if(ctx->buffer == NULL) { \
283       noitL(noit_error, "malloc(%lu) failed.\n", (long unsigned int)size + 1); \
284       goto socket_error; \
285     } \
286     ctx->buffer[size] = '\0'; \
287   } \
288   len = __read_on_ctx(e, ctx, &mask); \
289   if(len < 0) { \
290     if(errno == EAGAIN) return mask | EVENTER_EXCEPTION; \
291     noitL(noit_error, "[%s] SSL read error: %s\n", nctx->remote_str, strerror(errno)); \
292     goto socket_error; \
293   } \
294   ctx->bytes_read = 0; \
295   ctx->bytes_expected = 0; \
296   if(len != size) { \
297     noitL(noit_error, "[%s] SSL short read [%d] (%d/%lu).  Reseting connection.\n", \
298           nctx->remote_str, ctx->state, len, (long unsigned int)size); \
299     goto socket_error; \
300   } \
301 } while(0)
302
303 int
304 stratcon_jlog_recv_handler(eventer_t e, int mask, void *closure,
305                            struct timeval *now) {
306   noit_connection_ctx_t *nctx = closure;
307   jlog_streamer_ctx_t *ctx = nctx->consumer_ctx;
308   jlog_streamer_ctx_t dummy;
309   int len;
310   jlog_id n_chkpt;
311
312   if(mask & EVENTER_EXCEPTION || nctx->wants_shutdown) {
313     if(write(e->fd, e, 0) == -1)
314       noitL(noit_error, "socket error: %s\n", strerror(errno));
315  socket_error:
316     ctx->state = JLOG_STREAMER_WANT_INITIATE;
317     ctx->count = 0;
318     ctx->bytes_read = 0;
319     ctx->bytes_expected = 0;
320     if(ctx->buffer) free(ctx->buffer);
321     ctx->buffer = NULL;
322     noit_connection_schedule_reattempt(nctx, now);
323     eventer_remove_fd(e->fd);
324     e->opset->close(e->fd, &mask, e);
325     return 0;
326   }
327
328   while(1) {
329     switch(ctx->state) {
330       case JLOG_STREAMER_WANT_INITIATE:
331         len = e->opset->write(e->fd, &ctx->jlog_feed_cmd,
332                               sizeof(ctx->jlog_feed_cmd),
333                               &mask, e);
334         if(len < 0) {
335           if(errno == EAGAIN) return mask | EVENTER_EXCEPTION;
336           goto socket_error;
337         }
338         if(len != sizeof(ctx->jlog_feed_cmd)) {
339           noitL(noit_error, "short write [%d/%d] on initiating stream.\n",
340                 (int)len, (int)sizeof(ctx->jlog_feed_cmd));
341           goto socket_error;
342         }
343         ctx->state = JLOG_STREAMER_WANT_COUNT;
344         break;
345
346       case JLOG_STREAMER_WANT_COUNT:
347         FULLREAD(e, ctx, sizeof(u_int32_t));
348         memcpy(&dummy.count, ctx->buffer, sizeof(u_int32_t));
349         ctx->count = ntohl(dummy.count);
350         free(ctx->buffer); ctx->buffer = NULL;
351         ctx->state = JLOG_STREAMER_WANT_HEADER;
352         break;
353
354       case JLOG_STREAMER_WANT_HEADER:
355         if(ctx->count == 0) {
356           ctx->state = JLOG_STREAMER_WANT_COUNT;
357           break;
358         }
359         FULLREAD(e, ctx, sizeof(ctx->header));
360         memcpy(&dummy.header, ctx->buffer, sizeof(ctx->header));
361         ctx->header.chkpt.log = ntohl(dummy.header.chkpt.log);
362         ctx->header.chkpt.marker = ntohl(dummy.header.chkpt.marker);
363         ctx->header.tv_sec = ntohl(dummy.header.tv_sec);
364         ctx->header.tv_usec = ntohl(dummy.header.tv_usec);
365         ctx->header.message_len = ntohl(dummy.header.message_len);
366         free(ctx->buffer); ctx->buffer = NULL;
367         ctx->state = JLOG_STREAMER_WANT_BODY;
368         break;
369
370       case JLOG_STREAMER_WANT_BODY:
371         FULLREAD(e, ctx, (unsigned long)ctx->header.message_len);
372         if(ctx->header.message_len > 0)
373           ctx->push(DS_OP_INSERT, &nctx->r.remote, ctx->buffer);
374         else if(ctx->buffer)
375           free(ctx->buffer);
376         /* Don't free the buffer, it's used by the datastore process. */
377         ctx->buffer = NULL;
378         ctx->count--;
379         ctx->total_events++;
380         if(ctx->count == 0) {
381           eventer_t completion_e;
382           eventer_remove_fd(e->fd);
383           completion_e = eventer_alloc();
384           memcpy(completion_e, e, sizeof(*e));
385           completion_e->mask = EVENTER_READ | EVENTER_WRITE | EVENTER_EXCEPTION;
386           ctx->state = JLOG_STREAMER_IS_ASYNC;
387           ctx->push(DS_OP_CHKPT, &nctx->r.remote, completion_e);
388           noitL(noit_debug, "Pushing batch asynch...\n");
389           return 0;
390         } else
391           ctx->state = JLOG_STREAMER_WANT_HEADER;
392         break;
393
394       case JLOG_STREAMER_IS_ASYNC:
395         ctx->state = JLOG_STREAMER_WANT_CHKPT; /* falls through */
396       case JLOG_STREAMER_WANT_CHKPT:
397         noitL(noit_debug, "Pushing checkpoint: [%u/%u]\n",
398               ctx->header.chkpt.log, ctx->header.chkpt.marker);
399         n_chkpt.log = htonl(ctx->header.chkpt.log);
400         n_chkpt.marker = htonl(ctx->header.chkpt.marker);
401
402         /* screw short writes.  I'd rather die than not write my data! */
403         len = e->opset->write(e->fd, &n_chkpt, sizeof(jlog_id),
404                               &mask, e);
405         if(len < 0) {
406           if(errno == EAGAIN) return mask | EVENTER_EXCEPTION;
407           goto socket_error;
408         }
409         if(len != sizeof(jlog_id)) {
410           noitL(noit_error, "short write on checkpointing stream.\n");
411           goto socket_error;
412         }
413         ctx->state = JLOG_STREAMER_WANT_COUNT;
414         break;
415     }
416   }
417   /* never get here */
418 }
419
420 int
421 noit_connection_ssl_upgrade(eventer_t e, int mask, void *closure,
422                             struct timeval *now) {
423   noit_connection_ctx_t *nctx = closure;
424   int rv;
425
426   rv = eventer_SSL_connect(e, &mask);
427   if(rv > 0) {
428     eventer_ssl_ctx_t *sslctx;
429     e->callback = nctx->consumer_callback;
430     /* We must make a copy of the acceptor_closure_t for each new
431      * connection.
432      */
433     if((sslctx = eventer_get_eventer_ssl_ctx(e)) != NULL) {
434       const char *cn, *end;
435       cn = eventer_ssl_get_peer_subject(sslctx);
436       if(cn && (cn = strstr(cn, "CN=")) != NULL) {
437         cn += 3;
438         end = cn;
439         while(*end && *end != '/') end++;
440         nctx->remote_cn = malloc(end - cn + 1);
441         memcpy(nctx->remote_cn, cn, end - cn);
442         nctx->remote_cn[end-cn] = '\0';
443       }
444     }
445     return e->callback(e, mask, e->closure, now);
446   }
447   if(errno == EAGAIN) return mask | EVENTER_EXCEPTION;
448
449   noitL(noit_error, "jlog streamer SSL upgrade failed.\n");
450   eventer_remove_fd(e->fd);
451   e->opset->close(e->fd, &mask, e);
452   noit_connection_schedule_reattempt(nctx, now);
453   return 0;
454 }
455 int
456 noit_connection_complete_connect(eventer_t e, int mask, void *closure,
457                                  struct timeval *now) {
458   noit_connection_ctx_t *nctx = closure;
459   const char *cert, *key, *ca, *ciphers;
460   char remote_str[128], tmp_str[128];
461   eventer_ssl_ctx_t *sslctx;
462   int aerrno, len;
463   socklen_t aerrno_len = sizeof(aerrno);
464
465   if(getsockopt(e->fd,SOL_SOCKET,SO_ERROR, &aerrno, &aerrno_len) == 0)
466     if(aerrno != 0) goto connect_error;
467   aerrno = 0;
468
469   if(mask & EVENTER_EXCEPTION) {
470     if(aerrno == 0 && (write(e->fd, e, 0) == -1))
471       aerrno = errno;
472  connect_error:
473     switch(nctx->r.remote.sa_family) {
474       case AF_INET:
475         len = sizeof(struct sockaddr_in);
476         inet_ntop(nctx->r.remote.sa_family, &nctx->r.remote_in.sin_addr,
477                   tmp_str, len);
478         snprintf(remote_str, sizeof(remote_str), "%s:%d",
479                  tmp_str, ntohs(nctx->r.remote_in.sin_port));
480         break;
481       case AF_INET6:
482         len = sizeof(struct sockaddr_in6);
483         inet_ntop(nctx->r.remote.sa_family, &nctx->r.remote_in6.sin6_addr,
484                   tmp_str, len);
485         snprintf(remote_str, sizeof(remote_str), "%s:%d",
486                  tmp_str, ntohs(nctx->r.remote_in6.sin6_port));
487        break;
488       case AF_UNIX:
489         len = SUN_LEN(&(nctx->r.remote_un));
490         snprintf(remote_str, sizeof(remote_str), "%s", nctx->r.remote_un.sun_path);
491         break;
492       default:
493         snprintf(remote_str, sizeof(remote_str), "(unknown)");
494     }
495     noitL(noit_error, "Error connecting to %s: %s\n",
496           remote_str, strerror(aerrno));
497     eventer_remove_fd(e->fd);
498     e->opset->close(e->fd, &mask, e);
499     noit_connection_schedule_reattempt(nctx, now);
500     return 0;
501   }
502
503 #define SSLCONFGET(var,name) do { \
504   if(!noit_hash_retr_str(nctx->sslconfig, name, strlen(name), \
505                          &var)) var = NULL; } while(0)
506   SSLCONFGET(cert, "certificate_file");
507   SSLCONFGET(key, "key_file");
508   SSLCONFGET(ca, "ca_chain");
509   SSLCONFGET(ciphers, "ciphers");
510   sslctx = eventer_ssl_ctx_new(SSL_CLIENT, cert, key, ca, ciphers);
511   if(!sslctx) goto connect_error;
512
513   memcpy(&nctx->last_connect, now, sizeof(*now));
514   eventer_ssl_ctx_set_verify(sslctx, eventer_ssl_verify_cert,
515                              nctx->sslconfig);
516   EVENTER_ATTACH_SSL(e, sslctx);
517   e->callback = noit_connection_ssl_upgrade;
518   return e->callback(e, mask, closure, now);
519 }
520 static void
521 noit_connection_initiate_connection(noit_connection_ctx_t *nctx) {
522   struct timeval __now;
523   eventer_t e;
524   int rv, fd = -1;
525 #ifdef SO_KEEPALIVE
526   int optval;
527   socklen_t optlen = sizeof(optval);
528 #endif
529
530   if(nctx->wants_permanent_shutdown) {
531     noit_connection_ctx_dealloc(nctx);
532     return;
533   }
534   /* Open a socket */
535   fd = socket(nctx->r.remote.sa_family, SOCK_STREAM, 0);
536   if(fd < 0) goto reschedule;
537
538   /* Make it non-blocking */
539   if(eventer_set_fd_nonblocking(fd)) goto reschedule;
540 #define set_or_bail(type, opt, val) do { \
541   optval = val; \
542   optlen = sizeof(optval); \
543   if(setsockopt(fd, type, opt, &optval, optlen) < 0) { \
544     noitL(noit_error, "Cannot set " #type "/" #opt " on jlog socket: %s\n", \
545           strerror(errno)); \
546     goto reschedule; \
547   } \
548 } while(0)
549 #ifdef SO_KEEPALIVE
550   set_or_bail(SOL_SOCKET, SO_KEEPALIVE, 1);
551 #endif
552 #ifdef TCP_KEEPALIVE_THRESHOLD
553   set_or_bail(IPPROTO_TCP, TCP_KEEPALIVE_THRESHOLD, 10 * 1000);
554 #endif
555 #ifdef TCP_KEEPALIVE_ABORT_THRESHOLD
556   set_or_bail(IPPROTO_TCP, TCP_KEEPALIVE_ABORT_THRESHOLD, 30 * 1000);
557 #endif
558 #ifdef TCP_CONN_NOTIFY_THRESHOLD
559   set_or_bail(IPPROTO_TCP, TCP_CONN_NOTIFY_THRESHOLD, 10 * 1000);
560 #endif
561 #ifdef TCP_CONN_ABORT_THRESHOLD
562   set_or_bail(IPPROTO_TCP, TCP_CONN_ABORT_THRESHOLD, 30 * 1000);
563 #endif
564
565   /* Initiate a connection */
566   rv = connect(fd, &nctx->r.remote, nctx->remote_len);
567   if(rv == -1 && errno != EINPROGRESS) goto reschedule;
568
569   /* Register a handler for connection completion */
570   e = eventer_alloc();
571   e->fd = fd;
572   e->mask = EVENTER_READ | EVENTER_WRITE | EVENTER_EXCEPTION;
573   e->callback = noit_connection_complete_connect;
574   e->closure = nctx;
575   eventer_add(e);
576   return;
577
578  reschedule:
579   if(fd >= 0) close(fd);
580   gettimeofday(&__now, NULL);
581   noit_connection_schedule_reattempt(nctx, &__now);
582   return;
583 }
584
585 int
586 initiate_noit_connection(const char *host, unsigned short port,
587                          noit_hash_table *sslconfig, noit_hash_table *config,
588                          eventer_func_t handler, void *closure,
589                          void (*freefunc)(void *)) {
590   noit_connection_ctx_t *ctx;
591
592   int8_t family;
593   int rv;
594   union {
595     struct in_addr addr4;
596     struct in6_addr addr6;
597   } a;
598
599   if(host[0] == '/') {
600     family = AF_UNIX;
601   }
602   else {
603     family = AF_INET;
604     rv = inet_pton(family, host, &a);
605     if(rv != 1) {
606       family = AF_INET6;
607       rv = inet_pton(family, host, &a);
608       if(rv != 1) {
609         noitL(noit_stderr, "Cannot translate '%s' to IP\n", host);
610         return -1;
611       }
612     }
613   }
614
615   ctx = noit_connection_ctx_alloc();
616   ctx->remote_str = calloc(1, strlen(host) + 7);
617   snprintf(ctx->remote_str, strlen(host) + 7,
618            "%s:%d", host, port);
619  
620   memset(&ctx->r, 0, sizeof(ctx->r));
621   if(family == AF_UNIX) {
622     struct sockaddr_un *s = &ctx->r.remote_un;
623     s->sun_family = AF_UNIX;
624     strncpy(s->sun_path, host, sizeof(s->sun_path)-1);
625     ctx->remote_len = sizeof(*s);
626   }
627   else if(family == AF_INET) {
628     struct sockaddr_in *s = &ctx->r.remote_in;
629     s->sin_family = family;
630     s->sin_port = htons(port);
631     memcpy(&s->sin_addr, &a, sizeof(struct in_addr));
632     ctx->remote_len = sizeof(*s);
633   }
634   else {
635     struct sockaddr_in6 *s = &ctx->r.remote_in6;
636     s->sin6_family = family;
637     s->sin6_port = htons(port);
638     memcpy(&s->sin6_addr, &a, sizeof(a));
639     ctx->remote_len = sizeof(*s);
640   }
641
642   if(ctx->sslconfig)
643     noit_hash_delete_all(ctx->sslconfig, free, free);
644   else
645     ctx->sslconfig = calloc(1, sizeof(noit_hash_table));
646   noit_hash_merge_as_dict(ctx->sslconfig, sslconfig);
647   if(ctx->config)
648     noit_hash_delete_all(ctx->config, free, free);
649   else
650     ctx->config = calloc(1, sizeof(noit_hash_table));
651   noit_hash_merge_as_dict(ctx->config, config);
652
653   ctx->consumer_callback = handler;
654   ctx->consumer_free = freefunc;
655   ctx->consumer_ctx = closure;
656   noit_connection_initiate_connection(ctx);
657   return 0;
658 }
659
660 void
661 stratcon_streamer_connection(const char *toplevel, const char *destination,
662                              eventer_func_t handler,
663                              void *(*handler_alloc)(void), void *handler_ctx,
664                              void (*handler_free)(void *)) {
665   int i, cnt = 0;
666   noit_conf_section_t *noit_configs;
667   char path[256];
668
669   snprintf(path, sizeof(path), "/%s/noits//noit", toplevel ? toplevel : "*");
670   noit_configs = noit_conf_get_sections(NULL, path, &cnt);
671   noitL(noit_error, "Found %d %s stanzas\n", cnt, path);
672   for(i=0; i<cnt; i++) {
673     char address[256];
674     unsigned short port;
675     int portint;
676     noit_hash_table *sslconfig, *config;
677
678     if(!noit_conf_get_stringbuf(noit_configs[i],
679                                 "ancestor-or-self::node()/@address",
680                                 address, sizeof(address))) {
681       noitL(noit_error, "address attribute missing in noit %d\n", i+1);
682       continue;
683     }
684     /* if destination is specified, exact match it */
685     if(destination && strcmp(address, destination)) continue;
686
687     if(!noit_conf_get_int(noit_configs[i],
688                           "ancestor-or-self::node()/@port", &portint))
689       portint = 0;
690     port = (unsigned short) portint;
691     if(address[0] != '/' && (portint == 0 || (port != portint))) {
692       /* UNIX sockets don't require a port (they'll ignore it if specified */
693       noitL(noit_stderr,
694             "Invalid port [%d] specified in stanza %d\n", port, i+1);
695       continue;
696     }
697     sslconfig = noit_conf_get_hash(noit_configs[i], "sslconfig");
698     config = noit_conf_get_hash(noit_configs[i], "config");
699
700     noitL(noit_error, "initiating to %s\n", address);
701     initiate_noit_connection(address, port, sslconfig, config,
702                              handler,
703                              handler_alloc ? handler_alloc() : handler_ctx,
704                              handler_free);
705     noit_hash_destroy(sslconfig,free,free);
706     free(sslconfig);
707     noit_hash_destroy(config,free,free);
708     free(config);
709   }
710   free(noit_configs);
711 }
712 void
713 stratcon_jlog_streamer_reload(const char *toplevel) {
714   stratcon_streamer_connection(toplevel, NULL,
715                                stratcon_jlog_recv_handler,
716                                (void *(*)())stratcon_jlog_streamer_datastore_ctx_alloc,
717                                NULL,
718                                jlog_streamer_ctx_free);
719 }
720
721 static int
722 stratcon_console_show_noits(noit_console_closure_t ncct,
723                             int argc, char **argv,
724                             noit_console_state_t *dstate,
725                             void *closure) {
726   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
727   uuid_t key_id;
728   int klen, n = 0, i;
729   void *vconn;
730   noit_connection_ctx_t **ctx;
731
732   pthread_mutex_lock(&noits_lock);
733   ctx = malloc(sizeof(*ctx) * noits.size);
734   while(noit_hash_next(&noits, &iter, (const char **)key_id, &klen,
735                        &vconn)) {
736     ctx[n] = (noit_connection_ctx_t *)vconn;
737     noit_atomic_inc32(&ctx[n]->refcnt);
738     n++;
739   }
740   pthread_mutex_unlock(&noits_lock);
741   qsort(ctx, n, sizeof(*ctx), remote_str_sort);
742   for(i=0; i<n; i++) {
743     nc_print_noit_conn_brief(ncct, ctx[i]);
744     noit_connection_ctx_deref(ctx[i]);
745   }
746   free(ctx);
747   return 0;
748 }
749
750 static int
751 rest_show_noits(noit_http_rest_closure_t *restc,
752                 int npats, char **pats) {
753   xmlDocPtr doc;
754   xmlNodePtr root;
755   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
756   uuid_t key_id;
757   int klen, n = 0, i;
758   void *vconn;
759   noit_connection_ctx_t **ctxs;
760   struct timeval now, diff, last;
761   gettimeofday(&now, NULL);
762
763   pthread_mutex_lock(&noits_lock);
764   ctxs = malloc(sizeof(*ctxs) * noits.size);
765   while(noit_hash_next(&noits, &iter, (const char **)key_id, &klen,
766                        &vconn)) {
767     ctxs[n] = (noit_connection_ctx_t *)vconn;
768     noit_atomic_inc32(&ctxs[n]->refcnt);
769     n++;
770   }
771   pthread_mutex_unlock(&noits_lock);
772   qsort(ctxs, n, sizeof(*ctxs), remote_str_sort);
773
774   doc = xmlNewDoc((xmlChar *)"1.0");
775   root = xmlNewDocNode(doc, NULL, (xmlChar *)"noits", NULL);
776   xmlDocSetRootElement(doc, root);
777   for(i=0; i<n; i++) {
778     char buff[256], *feedtype = "unknown", *state = "unknown";
779     xmlNodePtr node;
780     noit_connection_ctx_t *ctx = ctxs[i];
781     jlog_streamer_ctx_t *jctx = ctx->consumer_ctx;
782
783     node = xmlNewNode(NULL, (xmlChar *)"noit");
784     snprintf(buff, sizeof(buff), "%llu.%06d",
785              (long long unsigned)ctx->last_connect.tv_sec,
786              (int)ctx->last_connect.tv_usec);
787     xmlSetProp(node, (xmlChar *)"last_connect", (xmlChar *)buff);
788     xmlSetProp(node, (xmlChar *)"state", ctx->remote_cn ?
789                (xmlChar *)"connected" :
790                (ctx->timeout_event ? (xmlChar *)"disconnected" :
791                                     (xmlChar *)"connecting"));
792     xmlSetProp(node, (xmlChar *)"remote", (xmlChar *)ctx->remote_str);
793     switch(ntohl(jctx->jlog_feed_cmd)) {
794       case NOIT_JLOG_DATA_FEED: feedtype = "durable/storage"; break;
795       case NOIT_JLOG_DATA_TEMP_FEED: feedtype = "transient/iep"; break;
796     }
797     xmlSetProp(node, (xmlChar *)"type", (xmlChar *)feedtype);
798     if(ctx->timeout_event) {
799       sub_timeval(ctx->timeout_event->whence, now, &diff);
800       snprintf(buff, sizeof(buff), "%llu.%06d",
801                (long long unsigned)diff.tv_sec, (int)diff.tv_usec);
802       xmlSetProp(node, (xmlChar *)"next_attempt", (xmlChar *)buff);
803     }
804     else if(ctx->remote_cn) {
805       if(ctx->remote_cn)
806         xmlSetProp(node, (xmlChar *)"remote_cn", (xmlChar *)ctx->remote_cn);
807  
808       switch(jctx->state) {
809         case JLOG_STREAMER_WANT_INITIATE: state = "initiate"; break;
810         case JLOG_STREAMER_WANT_COUNT: state = "waiting for next batch"; break;
811         case JLOG_STREAMER_WANT_HEADER: state = "reading header"; break;
812         case JLOG_STREAMER_WANT_BODY: state = "reading body"; break;
813         case JLOG_STREAMER_IS_ASYNC: state = "asynchronously processing"; break;
814         case JLOG_STREAMER_WANT_CHKPT: state = "checkpointing"; break;
815       }
816       xmlSetProp(node, (xmlChar *)"state", (xmlChar *)state);
817       snprintf(buff, sizeof(buff), "%08x:%08x",
818                jctx->header.chkpt.log, jctx->header.chkpt.marker);
819       xmlSetProp(node, (xmlChar *)"checkpoint", (xmlChar *)buff);
820       snprintf(buff, sizeof(buff), "%llu",
821                (unsigned long long)jctx->total_events);
822       xmlSetProp(node, (xmlChar *)"session_events", (xmlChar *)buff);
823       snprintf(buff, sizeof(buff), "%llu",
824                (unsigned long long)jctx->total_bytes_read);
825       xmlSetProp(node, (xmlChar *)"session_bytes", (xmlChar *)buff);
826  
827       sub_timeval(now, ctx->last_connect, &diff);
828       snprintf(buff, sizeof(buff), "%llu.%06d",
829                (unsigned long long)diff.tv_sec, (int)diff.tv_usec);
830       xmlSetProp(node, (xmlChar *)"session_duration", (xmlChar *)buff);
831  
832       if(jctx->header.tv_sec) {
833         last.tv_sec = jctx->header.tv_sec;
834         last.tv_usec = jctx->header.tv_usec;
835         snprintf(buff, sizeof(buff), "%llu.%06d",
836                  (unsigned long long)last.tv_sec, (int)last.tv_usec);
837         xmlSetProp(node, (xmlChar *)"last_event", (xmlChar *)buff);
838         sub_timeval(now, last, &diff);
839         snprintf(buff, sizeof(buff), "%llu.%06d",
840                  (unsigned long long)diff.tv_sec, (int)diff.tv_usec);
841         xmlSetProp(node, (xmlChar *)"last_event_age", (xmlChar *)buff);
842       }
843     }
844
845     xmlAddChild(root, node);
846     noit_connection_ctx_deref(ctx);
847   }
848   free(ctxs);
849
850   noit_http_response_ok(restc->http_ctx, "text/xml");
851   noit_http_response_xml(restc->http_ctx, doc);
852   noit_http_response_end(restc->http_ctx);
853   xmlFreeDoc(doc);
854   return 0;
855 }
856 static int
857 stratcon_add_noit(const char *target, unsigned short port) {
858   int cnt;
859   char path[256];
860   char port_str[6];
861   noit_conf_section_t *noit_configs, parent;
862   xmlNodePtr newnoit;
863
864   snprintf(path, sizeof(path),
865            "//noits//noit[@address=\"%s\" and @port=\"%d\"]", target, port);
866   noit_configs = noit_conf_get_sections(NULL, path, &cnt);
867   free(noit_configs);
868   if(cnt != 0) return 0;
869
870   parent = noit_conf_get_section(NULL, "//noits");
871   if(!parent) return 0;
872   snprintf(port_str, sizeof(port_str), "%d", port);
873   newnoit = xmlNewNode(NULL, (xmlChar *)"noit");
874   xmlSetProp(newnoit, (xmlChar *)"address", (xmlChar *)target);
875   xmlSetProp(newnoit, (xmlChar *)"port", (xmlChar *)port_str);
876   xmlAddChild(parent, newnoit);
877   noit_conf_mark_changed();
878   stratcon_streamer_connection(NULL, target,
879                                stratcon_jlog_recv_handler,
880                                (void *(*)())stratcon_jlog_streamer_datastore_ctx_alloc,
881                                NULL,
882                                jlog_streamer_ctx_free);
883   stratcon_streamer_connection(NULL, target,
884                                stratcon_jlog_recv_handler,
885                                (void *(*)())stratcon_jlog_streamer_iep_ctx_alloc,
886                                NULL,
887                                jlog_streamer_ctx_free);
888   return 1;
889 }
890 static int
891 stratcon_remove_noit(const char *target, unsigned short port) {
892   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
893   uuid_t key_id;
894   int klen, n = 0, i, cnt = 0;
895   void *vconn;
896   noit_connection_ctx_t **ctx;
897   noit_conf_section_t *noit_configs;
898   char path[256];
899   char remote_str[256];
900
901   snprintf(remote_str, sizeof(remote_str), "%s:%d", target, port);
902
903   snprintf(path, sizeof(path),
904            "//noits//noit[@address=\"%s\" and @port=\"%d\"]", target, port);
905   noit_configs = noit_conf_get_sections(NULL, path, &cnt);
906   for(i=0; i<cnt; i++) {
907     xmlUnlinkNode(noit_configs[i]);
908     xmlFreeNode(noit_configs[i]);
909   }
910   free(noit_configs);
911   noit_conf_mark_changed();
912
913   pthread_mutex_lock(&noits_lock);
914   ctx = malloc(sizeof(*ctx) * noits.size);
915   while(noit_hash_next(&noits, &iter, (const char **)key_id, &klen,
916                        &vconn)) {
917     if(!strcmp(((noit_connection_ctx_t *)vconn)->remote_str, remote_str)) {
918       ctx[n] = (noit_connection_ctx_t *)vconn;
919       noit_atomic_inc32(&ctx[n]->refcnt);
920       n++;
921     }
922   }
923   pthread_mutex_unlock(&noits_lock);
924   for(i=0; i<n; i++) {
925     noit_connection_ctx_dealloc(ctx[i]); /* once for the record */
926     noit_connection_ctx_deref(ctx[i]);   /* once for the aboce inc32 */
927   }
928   free(ctx);
929   return n;
930 }
931 static int
932 stratcon_console_conf_noits(noit_console_closure_t ncct,
933                             int argc, char **argv,
934                             noit_console_state_t *dstate,
935                             void *closure) {
936   char *cp, target[128];
937   unsigned short port = 43191;
938   int adding = (int)closure;
939   if(argc != 1)
940     return -1;
941
942   cp = strchr(argv[0], ':');
943   if(cp) {
944     strlcpy(target, argv[0], MIN(sizeof(target), cp-argv[0]+1));
945     port = atoi(cp+1);
946   }
947   else strlcpy(target, argv[0], sizeof(target));
948   if(adding) {
949     if(stratcon_add_noit(target, port)) {
950       nc_printf(ncct, "Added noit at %s:%d\n", target, port);
951     }
952     else {
953       nc_printf(ncct, "Failed to add noit at %s:%d\n", target, port);
954     }
955   }
956   else {
957     if(stratcon_remove_noit(target, port)) {
958       nc_printf(ncct, "Removed noit at %s:%d\n", target, port);
959     }
960     else {
961       nc_printf(ncct, "Failed to remove noit at %s:%d\n", target, port);
962     }
963   }
964   return 0;
965 }
966
967 static void
968 register_console_streamer_commands() {
969   noit_console_state_t *tl;
970   cmd_info_t *showcmd, *confcmd, *conftcmd, *conftnocmd;
971
972   tl = noit_console_state_initial();
973   showcmd = noit_console_state_get_cmd(tl, "show");
974   assert(showcmd && showcmd->dstate);
975   confcmd = noit_console_state_get_cmd(tl, "configure");
976   conftcmd = noit_console_state_get_cmd(confcmd->dstate, "terminal");
977   conftnocmd = noit_console_state_get_cmd(conftcmd->dstate, "no");
978
979   noit_console_state_add_cmd(conftcmd->dstate,
980     NCSCMD("noit", stratcon_console_conf_noits, NULL, NULL, (void *)1));
981   noit_console_state_add_cmd(conftnocmd->dstate,
982     NCSCMD("noit", stratcon_console_conf_noits, NULL, NULL, (void *)0));
983
984   noit_console_state_add_cmd(showcmd->dstate,
985     NCSCMD("noits", stratcon_console_show_noits, NULL, NULL, NULL));
986 }
987
988
989 void
990 stratcon_jlog_streamer_init(const char *toplevel) {
991   pthread_mutex_init(&noits_lock, NULL);
992   eventer_name_callback("noit_connection_reinitiate",
993                         noit_connection_reinitiate);
994   eventer_name_callback("stratcon_jlog_recv_handler",
995                         stratcon_jlog_recv_handler);
996   eventer_name_callback("noit_connection_ssl_upgrade",
997                         noit_connection_ssl_upgrade);
998   eventer_name_callback("noit_connection_complete_connect",
999                         noit_connection_complete_connect);
1000   register_console_streamer_commands();
1001   stratcon_jlog_streamer_reload(toplevel);
1002   assert(noit_http_rest_register(
1003     "GET", "/noits/", "^show$", rest_show_noits
1004   ) == 0);
1005 }
1006
Note: See TracBrowser for help on using the browser.