root/src/stratcon_jlog_streamer.c

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

This change should finally fix it. closes #58

  • 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 pthread_mutex_t noit_ip_by_cn_lock;
59 noit_hash_table noit_ip_by_cn = NOIT_HASH_EMPTY;
60
61 static void noit_connection_initiate_connection(noit_connection_ctx_t *ctx);
62
63 static const char *feed_type_to_str(int jlog_feed_cmd) {
64   switch(jlog_feed_cmd) {
65     case NOIT_JLOG_DATA_FEED: return "durable/storage";
66     case NOIT_JLOG_DATA_TEMP_FEED: return "transient/iep";
67   }
68   return "unknown";
69 }
70
71 static int
72 remote_str_sort(const void *a, const void *b) {
73   int rv;
74   noit_connection_ctx_t * const *actx = a;
75   noit_connection_ctx_t * const *bctx = b;
76   jlog_streamer_ctx_t *ajctx = (*actx)->consumer_ctx;
77   jlog_streamer_ctx_t *bjctx = (*bctx)->consumer_ctx;
78   rv = strcmp((*actx)->remote_str, (*bctx)->remote_str);
79   if(rv) return rv;
80   return (ajctx->jlog_feed_cmd < bjctx->jlog_feed_cmd) ? -1 :
81            ((ajctx->jlog_feed_cmd == bjctx->jlog_feed_cmd) ? 0 : 1);
82 }
83 static void
84 nc_print_noit_conn_brief(noit_console_closure_t ncct,
85                           noit_connection_ctx_t *ctx) {
86   jlog_streamer_ctx_t *jctx = ctx->consumer_ctx;
87   struct timeval now, diff, session_duration;
88   const char *feedtype = "unknown";
89   const char *lasttime = "never";
90   if(ctx->last_connect.tv_sec != 0) {
91     char cmdbuf[4096];
92     time_t r = ctx->last_connect.tv_sec;
93     struct tm tbuf, *tm;
94     tm = gmtime_r(&r, &tbuf);
95     strftime(cmdbuf, sizeof(cmdbuf), "%Y-%m-%d %H:%M:%S UTC", tm);
96     lasttime = cmdbuf;
97   }
98   nc_printf(ncct, "%s [%s]:\n\tLast connect: %s\n", ctx->remote_str,
99             ctx->remote_cn ? "connected" :
100                              (ctx->retry_event ? "disconnected" :
101                                                    "connecting"), lasttime);
102   if(ctx->e) {
103     char buff[128];
104     const char *addrstr = NULL;
105     struct sockaddr_in6 addr6;
106     socklen_t len = sizeof(addr6);
107     if(getsockname(ctx->e->fd, (struct sockaddr *)&addr6, &len) == 0) {
108       unsigned short port = 0;
109       if(addr6.sin6_family == AF_INET) {
110         addrstr = inet_ntop(addr6.sin6_family,
111                             &((struct sockaddr_in *)&addr6)->sin_addr,
112                             buff, sizeof(buff));
113         port = ntohs(((struct sockaddr_in *)&addr6)->sin_port);
114       }
115       else if(addr6.sin6_family == AF_INET6) {
116         addrstr = inet_ntop(addr6.sin6_family, &addr6.sin6_addr,
117                             buff, sizeof(buff));
118         port = ntohs(addr6.sin6_port);
119       }
120       if(addrstr != NULL)
121         nc_printf(ncct, "\tLocal address is %s:%u\n", buff, port);
122       else
123         nc_printf(ncct, "\tLocal address not interpretable\n");
124     }
125     else {
126       nc_printf(ncct, "\tLocal address error[%d]: %s\n",
127                 ctx->e->fd, strerror(errno));
128     }
129   }
130   feedtype = feed_type_to_str(ntohl(jctx->jlog_feed_cmd));
131   nc_printf(ncct, "\tJLog event streamer [%s]\n", feedtype);
132   gettimeofday(&now, NULL);
133   if(ctx->retry_event) {
134     sub_timeval(ctx->retry_event->whence, now, &diff);
135     nc_printf(ncct, "\tNext attempt in %lld.%06us\n",
136               (long long)diff.tv_sec, (unsigned int) diff.tv_usec);
137   }
138   else if(ctx->remote_cn) {
139     nc_printf(ncct, "\tRemote CN: '%s'\n",
140               ctx->remote_cn ? ctx->remote_cn : "???");
141     if(ctx->consumer_callback == stratcon_jlog_recv_handler) {
142       struct timeval last;
143       double session_duration_seconds;
144       const char *state = "unknown";
145
146       switch(jctx->state) {
147         case JLOG_STREAMER_WANT_INITIATE: state = "initiate"; break;
148         case JLOG_STREAMER_WANT_COUNT: state = "waiting for next batch"; break;
149         case JLOG_STREAMER_WANT_ERROR: state = "waiting for error"; break;
150         case JLOG_STREAMER_WANT_HEADER: state = "reading header"; break;
151         case JLOG_STREAMER_WANT_BODY: state = "reading body"; break;
152         case JLOG_STREAMER_IS_ASYNC: state = "asynchronously processing"; break;
153         case JLOG_STREAMER_WANT_CHKPT: state = "checkpointing"; break;
154       }
155       last.tv_sec = jctx->header.tv_sec;
156       last.tv_usec = jctx->header.tv_usec;
157       sub_timeval(now, last, &diff);
158       sub_timeval(now, ctx->last_connect, &session_duration);
159       session_duration_seconds = session_duration.tv_sec +
160                                  (double)session_duration.tv_usec/1000000.0;
161       nc_printf(ncct, "\tState: %s\n"
162                       "\tNext checkpoint: [%08x:%08x]\n"
163                       "\tLast event: %lld.%06us ago\n"
164                       "\tEvents this session: %llu (%0.2f/s)\n"
165                       "\tOctets this session: %llu (%0.2f/s)\n",
166                 state,
167                 jctx->header.chkpt.log, jctx->header.chkpt.marker,
168                 (long long)diff.tv_sec, (unsigned int)diff.tv_usec,
169                 jctx->total_events,
170                 (double)jctx->total_events/session_duration_seconds,
171                 jctx->total_bytes_read,
172                 (double)jctx->total_bytes_read/session_duration_seconds);
173     }
174     else {
175       nc_printf(ncct, "\tUnknown type.\n");
176     }
177   }
178 }
179
180 jlog_streamer_ctx_t *
181 stratcon_jlog_streamer_datastore_ctx_alloc(void) {
182   jlog_streamer_ctx_t *ctx;
183   ctx = stratcon_jlog_streamer_ctx_alloc();
184   ctx->jlog_feed_cmd = htonl(NOIT_JLOG_DATA_FEED);
185   ctx->push = stratcon_datastore_push;
186   return ctx;
187 }
188 jlog_streamer_ctx_t *
189 stratcon_jlog_streamer_ctx_alloc(void) {
190   jlog_streamer_ctx_t *ctx;
191   ctx = calloc(1, sizeof(*ctx));
192   return ctx;
193 }
194 noit_connection_ctx_t *
195 noit_connection_ctx_alloc(void) {
196   noit_connection_ctx_t *ctx, **pctx;
197   ctx = calloc(1, sizeof(*ctx));
198   ctx->refcnt = 1;
199   pctx = malloc(sizeof(*pctx));
200   *pctx = ctx;
201   pthread_mutex_lock(&noits_lock);
202   noit_hash_store(&noits, (const char *)pctx, sizeof(*pctx), ctx);
203   pthread_mutex_unlock(&noits_lock);
204   return ctx;
205 }
206 int
207 noit_connection_reinitiate(eventer_t e, int mask, void *closure,
208                          struct timeval *now) {
209   noit_connection_ctx_t *ctx = closure;
210   ctx->retry_event = NULL;
211   noit_connection_initiate_connection(closure);
212   return 0;
213 }
214 void
215 noit_connection_schedule_reattempt(noit_connection_ctx_t *ctx,
216                                    struct timeval *now) {
217   struct timeval __now, interval;
218   const char *v;
219   u_int32_t min_interval = 1000, max_interval = 8000;
220
221   noit_connection_disable_timeout(ctx);
222   if(ctx->remote_cn) {
223     free(ctx->remote_cn);
224     ctx->remote_cn = NULL;
225   }
226   if(noit_hash_retr_str(ctx->config,
227                         "reconnect_initial_interval",
228                         strlen("reconnect_initial_interval"),
229                         &v)) {
230     min_interval = MAX(atoi(v), 100); /* .1 second minimum */
231   }
232   if(noit_hash_retr_str(ctx->config,
233                         "reconnect_maximum_interval",
234                         strlen("reconnect_maximum_interval"),
235                         &v)) {
236     max_interval = MIN(atoi(v), 3600*1000); /* 1 hour maximum */
237   }
238   if(ctx->current_backoff == 0) ctx->current_backoff = min_interval;
239   else {
240     ctx->current_backoff *= 2;
241     ctx->current_backoff = MAX(min_interval, ctx->current_backoff);
242     ctx->current_backoff = MIN(max_interval, ctx->current_backoff);
243   }
244   if(!now) {
245     gettimeofday(&__now, NULL);
246     now = &__now;
247   }
248   interval.tv_sec = ctx->current_backoff / 1000;
249   interval.tv_usec = (ctx->current_backoff % 1000) * 1000;
250   noitL(noit_debug, "Next jlog_streamer attempt in %ums\n",
251         ctx->current_backoff);
252   if(ctx->retry_event)
253     eventer_remove(ctx->retry_event);
254   else
255     ctx->retry_event = eventer_alloc();
256   ctx->retry_event->callback = noit_connection_reinitiate;
257   ctx->retry_event->closure = ctx;
258   ctx->retry_event->mask = EVENTER_TIMER;
259   add_timeval(*now, interval, &ctx->retry_event->whence);
260   eventer_add(ctx->retry_event);
261 }
262 static void
263 noit_connection_ctx_free(noit_connection_ctx_t *ctx) {
264   if(ctx->remote_cn) free(ctx->remote_cn);
265   if(ctx->remote_str) free(ctx->remote_str);
266   if(ctx->retry_event) {
267     eventer_remove(ctx->retry_event);
268     eventer_free(ctx->retry_event);
269   }
270   if(ctx->timeout_event) {
271     eventer_remove(ctx->timeout_event);
272     eventer_free(ctx->timeout_event);
273   }
274   ctx->consumer_free(ctx->consumer_ctx);
275   free(ctx);
276 }
277 void
278 noit_connection_ctx_deref(noit_connection_ctx_t *ctx) {
279   if(noit_atomic_dec32(&ctx->refcnt) == 0)
280     noit_connection_ctx_free(ctx);
281 }
282 void
283 noit_connection_ctx_dealloc(noit_connection_ctx_t *ctx) {
284   noit_connection_ctx_t **pctx = &ctx;
285   pthread_mutex_lock(&noits_lock);
286   noit_hash_delete(&noits, (const char *)pctx, sizeof(*pctx),
287                    free, (void (*)(void *))noit_connection_ctx_deref);
288   pthread_mutex_unlock(&noits_lock);
289 }
290 void
291 jlog_streamer_ctx_free(void *cl) {
292   jlog_streamer_ctx_t *ctx = cl;
293   if(ctx->buffer) free(ctx->buffer);
294   free(ctx);
295 }
296
297 #define Eread(a,b) e->opset->read(e->fd, (a), (b), &mask, e)
298 static int
299 __read_on_ctx(eventer_t e, jlog_streamer_ctx_t *ctx, int *newmask) {
300   int len, mask;
301   while(ctx->bytes_read < ctx->bytes_expected) {
302     len = Eread(ctx->buffer + ctx->bytes_read,
303                 ctx->bytes_expected - ctx->bytes_read);
304     if(len < 0) {
305       *newmask = mask;
306       return -1;
307     }
308     /* if we get 0 inside SSL, and there was a real error, we
309      * will actually get a -1 here.
310      * if(len == 0) return ctx->bytes_read;
311      */
312     ctx->total_bytes_read += len;
313     ctx->bytes_read += len;
314   }
315   assert(ctx->bytes_read == ctx->bytes_expected);
316   return ctx->bytes_read;
317 }
318 #define FULLREAD(e,ctx,size) do { \
319   int mask, len; \
320   if(!ctx->bytes_expected) { \
321     ctx->bytes_expected = size; \
322     if(ctx->buffer) free(ctx->buffer); \
323     ctx->buffer = malloc(size + 1); \
324     if(ctx->buffer == NULL) { \
325       noitL(noit_error, "malloc(%lu) failed.\n", (long unsigned int)size + 1); \
326       goto socket_error; \
327     } \
328     ctx->buffer[size] = '\0'; \
329   } \
330   len = __read_on_ctx(e, ctx, &mask); \
331   if(len < 0) { \
332     if(errno == EAGAIN) return mask | EVENTER_EXCEPTION; \
333     noitL(noit_error, "[%s] SSL read error: %s\n", nctx->remote_str, strerror(errno)); \
334     goto socket_error; \
335   } \
336   ctx->bytes_read = 0; \
337   ctx->bytes_expected = 0; \
338   if(len != size) { \
339     noitL(noit_error, "[%s] SSL short read [%d] (%d/%lu).  Reseting connection.\n", \
340           nctx->remote_str, ctx->state, len, (long unsigned int)size); \
341     goto socket_error; \
342   } \
343 } while(0)
344
345 int
346 noit_connection_session_timeout(eventer_t e, int mask, void *closure,
347                                 struct timeval *now) {
348   noit_connection_ctx_t *nctx = closure;
349   eventer_t fde = nctx->e;
350   nctx->timeout_event = NULL;
351   noitL(noit_error, "Timing out jlog session: %s\n",
352         nctx->remote_cn ? nctx->remote_cn : "(null)");
353   if(fde)
354     eventer_trigger(fde, EVENTER_EXCEPTION);
355   return 0;
356 }
357 int
358 stratcon_jlog_recv_handler(eventer_t e, int mask, void *closure,
359                            struct timeval *now) {
360   noit_connection_ctx_t *nctx = closure;
361   jlog_streamer_ctx_t *ctx = nctx->consumer_ctx;
362   jlog_streamer_ctx_t dummy;
363   int len;
364   jlog_id n_chkpt;
365
366   if(mask & EVENTER_EXCEPTION || nctx->wants_shutdown) {
367     if(write(e->fd, e, 0) == -1)
368       noitL(noit_error, "socket error: %s\n", strerror(errno));
369  socket_error:
370     ctx->state = JLOG_STREAMER_WANT_INITIATE;
371     ctx->count = 0;
372     ctx->bytes_read = 0;
373     ctx->bytes_expected = 0;
374     if(ctx->buffer) free(ctx->buffer);
375     ctx->buffer = NULL;
376     noit_connection_schedule_reattempt(nctx, now);
377     eventer_remove_fd(e->fd);
378     nctx->e = NULL;
379     e->opset->close(e->fd, &mask, e);
380     return 0;
381   }
382
383   noit_connection_update_timeout(nctx);
384   while(1) {
385     switch(ctx->state) {
386       case JLOG_STREAMER_WANT_INITIATE:
387         len = e->opset->write(e->fd, &ctx->jlog_feed_cmd,
388                               sizeof(ctx->jlog_feed_cmd),
389                               &mask, e);
390         if(len < 0) {
391           if(errno == EAGAIN) return mask | EVENTER_EXCEPTION;
392           goto socket_error;
393         }
394         if(len != sizeof(ctx->jlog_feed_cmd)) {
395           noitL(noit_error, "short write [%d/%d] on initiating stream.\n",
396                 (int)len, (int)sizeof(ctx->jlog_feed_cmd));
397           goto socket_error;
398         }
399         ctx->state = JLOG_STREAMER_WANT_COUNT;
400         break;
401
402       case JLOG_STREAMER_WANT_ERROR:
403         FULLREAD(e, ctx, 0 - ctx->count);
404         noitL(noit_error, "[%s] %.*s\n", nctx->remote_str,
405               0 - ctx->count, ctx->buffer);
406         free(ctx->buffer); ctx->buffer = NULL;
407         goto socket_error;
408         break;
409
410       case JLOG_STREAMER_WANT_COUNT:
411         FULLREAD(e, ctx, sizeof(u_int32_t));
412         memcpy(&dummy.count, ctx->buffer, sizeof(u_int32_t));
413         ctx->count = ntohl(dummy.count);
414         free(ctx->buffer); ctx->buffer = NULL;
415         if(ctx->count < 0)
416           ctx->state = JLOG_STREAMER_WANT_ERROR;
417         else
418           ctx->state = JLOG_STREAMER_WANT_HEADER;
419         break;
420
421       case JLOG_STREAMER_WANT_HEADER:
422         if(ctx->count == 0) {
423           ctx->state = JLOG_STREAMER_WANT_COUNT;
424           break;
425         }
426         FULLREAD(e, ctx, sizeof(ctx->header));
427         memcpy(&dummy.header, ctx->buffer, sizeof(ctx->header));
428         ctx->header.chkpt.log = ntohl(dummy.header.chkpt.log);
429         ctx->header.chkpt.marker = ntohl(dummy.header.chkpt.marker);
430         ctx->header.tv_sec = ntohl(dummy.header.tv_sec);
431         ctx->header.tv_usec = ntohl(dummy.header.tv_usec);
432         ctx->header.message_len = ntohl(dummy.header.message_len);
433         free(ctx->buffer); ctx->buffer = NULL;
434         ctx->state = JLOG_STREAMER_WANT_BODY;
435         break;
436
437       case JLOG_STREAMER_WANT_BODY:
438         FULLREAD(e, ctx, (unsigned long)ctx->header.message_len);
439         if(ctx->header.message_len > 0)
440           ctx->push(DS_OP_INSERT, &nctx->r.remote, nctx->remote_cn,
441                     ctx->buffer, NULL);
442         else if(ctx->buffer)
443           free(ctx->buffer);
444         /* Don't free the buffer, it's used by the datastore process. */
445         ctx->buffer = NULL;
446         ctx->count--;
447         ctx->total_events++;
448         if(ctx->count == 0) {
449           eventer_t completion_e;
450           eventer_remove_fd(e->fd);
451           completion_e = eventer_alloc();
452           memcpy(completion_e, e, sizeof(*e));
453           nctx->e = completion_e;
454           completion_e->mask = EVENTER_READ | EVENTER_WRITE | EVENTER_EXCEPTION;
455           ctx->state = JLOG_STREAMER_IS_ASYNC;
456           ctx->push(DS_OP_CHKPT, &nctx->r.remote, nctx->remote_cn,
457                     NULL, completion_e);
458           noitL(noit_debug, "Pushing %s batch async [%s]: [%u/%u]\n",
459                 feed_type_to_str(ntohl(ctx->jlog_feed_cmd)),
460                 nctx->remote_cn ? nctx->remote_cn : "(null)",
461                 ctx->header.chkpt.log, ctx->header.chkpt.marker);
462           noit_connection_disable_timeout(nctx);
463           return 0;
464         } else
465           ctx->state = JLOG_STREAMER_WANT_HEADER;
466         break;
467
468       case JLOG_STREAMER_IS_ASYNC:
469         ctx->state = JLOG_STREAMER_WANT_CHKPT; /* falls through */
470       case JLOG_STREAMER_WANT_CHKPT:
471         noitL(noit_debug, "Pushing %s checkpoint [%s]: [%u/%u]\n",
472               feed_type_to_str(ntohl(ctx->jlog_feed_cmd)),
473               nctx->remote_cn ? nctx->remote_cn : "(null)",
474               ctx->header.chkpt.log, ctx->header.chkpt.marker);
475         n_chkpt.log = htonl(ctx->header.chkpt.log);
476         n_chkpt.marker = htonl(ctx->header.chkpt.marker);
477
478         /* screw short writes.  I'd rather die than not write my data! */
479         len = e->opset->write(e->fd, &n_chkpt, sizeof(jlog_id),
480                               &mask, e);
481         if(len < 0) {
482           if(errno == EAGAIN) return mask | EVENTER_EXCEPTION;
483           goto socket_error;
484         }
485         if(len != sizeof(jlog_id)) {
486           noitL(noit_error, "short write on checkpointing stream.\n");
487           goto socket_error;
488         }
489         ctx->state = JLOG_STREAMER_WANT_COUNT;
490         break;
491     }
492   }
493   /* never get here */
494 }
495
496 int
497 noit_connection_ssl_upgrade(eventer_t e, int mask, void *closure,
498                             struct timeval *now) {
499   noit_connection_ctx_t *nctx = closure;
500   int rv;
501   const char *error = "jlog streamer SSL upgrade failed.\n";
502
503   rv = eventer_SSL_connect(e, &mask);
504   if(rv > 0) {
505     eventer_ssl_ctx_t *sslctx;
506     e->callback = nctx->consumer_callback;
507     /* We must make a copy of the acceptor_closure_t for each new
508      * connection.
509      */
510     if((sslctx = eventer_get_eventer_ssl_ctx(e)) != NULL) {
511       const char *cn, *end;
512       void *vcn;
513       cn = eventer_ssl_get_peer_subject(sslctx);
514       if(cn && (cn = strstr(cn, "CN=")) != NULL) {
515         cn += 3;
516         end = cn;
517         while(*end && *end != '/') end++;
518         nctx->remote_cn = malloc(end - cn + 1);
519         memcpy(nctx->remote_cn, cn, end - cn);
520         nctx->remote_cn[end-cn] = '\0';
521       }
522       if(nctx->config &&
523          noit_hash_retrieve(nctx->config, "cn", 2, &vcn)) {
524         const char *cn_expected = vcn;
525         if(!nctx->remote_cn ||
526            strcmp(nctx->remote_cn, cn_expected)) {
527           error = "jlog connect CN mismatch\n";
528           goto error;
529         }
530       }
531     }
532     return e->callback(e, mask, e->closure, now);
533   }
534   if(errno == EAGAIN) return mask | EVENTER_EXCEPTION;
535
536  error:
537   noitL(noit_error, error);
538   eventer_remove_fd(e->fd);
539   nctx->e = NULL;
540   e->opset->close(e->fd, &mask, e);
541   noit_connection_schedule_reattempt(nctx, now);
542   return 0;
543 }
544 int
545 noit_connection_complete_connect(eventer_t e, int mask, void *closure,
546                                  struct timeval *now) {
547   noit_connection_ctx_t *nctx = closure;
548   const char *cert, *key, *ca, *ciphers, *crl = NULL;
549   char remote_str[128], tmp_str[128];
550   eventer_ssl_ctx_t *sslctx;
551   int aerrno, len;
552   socklen_t aerrno_len = sizeof(aerrno);
553
554   if(getsockopt(e->fd,SOL_SOCKET,SO_ERROR, &aerrno, &aerrno_len) == 0)
555     if(aerrno != 0) goto connect_error;
556   aerrno = 0;
557
558   if(mask & EVENTER_EXCEPTION) {
559     if(aerrno == 0 && (write(e->fd, e, 0) == -1))
560       aerrno = errno;
561  connect_error:
562     switch(nctx->r.remote.sa_family) {
563       case AF_INET:
564         len = sizeof(struct sockaddr_in);
565         inet_ntop(nctx->r.remote.sa_family, &nctx->r.remote_in.sin_addr,
566                   tmp_str, len);
567         snprintf(remote_str, sizeof(remote_str), "%s:%d",
568                  tmp_str, ntohs(nctx->r.remote_in.sin_port));
569         break;
570       case AF_INET6:
571         len = sizeof(struct sockaddr_in6);
572         inet_ntop(nctx->r.remote.sa_family, &nctx->r.remote_in6.sin6_addr,
573                   tmp_str, len);
574         snprintf(remote_str, sizeof(remote_str), "%s:%d",
575                  tmp_str, ntohs(nctx->r.remote_in6.sin6_port));
576        break;
577       case AF_UNIX:
578         len = SUN_LEN(&(nctx->r.remote_un));
579         snprintf(remote_str, sizeof(remote_str), "%s", nctx->r.remote_un.sun_path);
580         break;
581       default:
582         snprintf(remote_str, sizeof(remote_str), "(unknown)");
583     }
584     noitL(noit_error, "Error connecting to %s: %s\n",
585           remote_str, strerror(aerrno));
586     eventer_remove_fd(e->fd);
587     nctx->e = NULL;
588     e->opset->close(e->fd, &mask, e);
589     noit_connection_schedule_reattempt(nctx, now);
590     return 0;
591   }
592
593 #define SSLCONFGET(var,name) do { \
594   if(!noit_hash_retr_str(nctx->sslconfig, name, strlen(name), \
595                          &var)) var = NULL; } while(0)
596   SSLCONFGET(cert, "certificate_file");
597   SSLCONFGET(key, "key_file");
598   SSLCONFGET(ca, "ca_chain");
599   SSLCONFGET(ciphers, "ciphers");
600   SSLCONFGET(crl, "crl");
601   sslctx = eventer_ssl_ctx_new(SSL_CLIENT, cert, key, ca, ciphers);
602   if(!sslctx) goto connect_error;
603   if(crl) {
604     if(!eventer_ssl_use_crl(sslctx, crl)) {
605       noitL(noit_error, "Failed to load CRL from %s\n", crl);
606       eventer_ssl_ctx_free(sslctx);
607       goto connect_error;
608     }
609   }
610
611   memcpy(&nctx->last_connect, now, sizeof(*now));
612   eventer_ssl_ctx_set_verify(sslctx, eventer_ssl_verify_cert,
613                              nctx->sslconfig);
614   EVENTER_ATTACH_SSL(e, sslctx);
615   e->callback = noit_connection_ssl_upgrade;
616   return e->callback(e, mask, closure, now);
617 }
618 static void
619 noit_connection_initiate_connection(noit_connection_ctx_t *nctx) {
620   struct timeval __now;
621   eventer_t e;
622   int rv, fd = -1;
623 #ifdef SO_KEEPALIVE
624   int optval;
625   socklen_t optlen = sizeof(optval);
626 #endif
627
628   nctx->e = NULL;
629   if(nctx->wants_permanent_shutdown) {
630     noit_connection_ctx_dealloc(nctx);
631     return;
632   }
633   /* Open a socket */
634   fd = socket(nctx->r.remote.sa_family, SOCK_STREAM, 0);
635   if(fd < 0) goto reschedule;
636
637   /* Make it non-blocking */
638   if(eventer_set_fd_nonblocking(fd)) goto reschedule;
639 #define set_or_bail(type, opt, val) do { \
640   optval = val; \
641   optlen = sizeof(optval); \
642   if(setsockopt(fd, type, opt, &optval, optlen) < 0) { \
643     noitL(noit_error, "Cannot set " #type "/" #opt " on jlog socket: %s\n", \
644           strerror(errno)); \
645     goto reschedule; \
646   } \
647 } while(0)
648 #ifdef SO_KEEPALIVE
649   set_or_bail(SOL_SOCKET, SO_KEEPALIVE, 1);
650 #endif
651 #ifdef TCP_KEEPALIVE_THRESHOLD
652   set_or_bail(IPPROTO_TCP, TCP_KEEPALIVE_THRESHOLD, 10 * 1000);
653 #endif
654 #ifdef TCP_KEEPALIVE_ABORT_THRESHOLD
655   set_or_bail(IPPROTO_TCP, TCP_KEEPALIVE_ABORT_THRESHOLD, 30 * 1000);
656 #endif
657 #ifdef TCP_CONN_NOTIFY_THRESHOLD
658   set_or_bail(IPPROTO_TCP, TCP_CONN_NOTIFY_THRESHOLD, 10 * 1000);
659 #endif
660 #ifdef TCP_CONN_ABORT_THRESHOLD
661   set_or_bail(IPPROTO_TCP, TCP_CONN_ABORT_THRESHOLD, 30 * 1000);
662 #endif
663
664   /* Initiate a connection */
665   rv = connect(fd, &nctx->r.remote, nctx->remote_len);
666   if(rv == -1 && errno != EINPROGRESS) goto reschedule;
667
668   /* Register a handler for connection completion */
669   e = eventer_alloc();
670   e->fd = fd;
671   e->mask = EVENTER_READ | EVENTER_WRITE | EVENTER_EXCEPTION;
672   e->callback = noit_connection_complete_connect;
673   e->closure = nctx;
674   nctx->e = e;
675   eventer_add(e);
676
677   noit_connection_update_timeout(nctx);
678   return;
679
680  reschedule:
681   if(fd >= 0) close(fd);
682   gettimeofday(&__now, NULL);
683   noit_connection_schedule_reattempt(nctx, &__now);
684   return;
685 }
686
687 int
688 noit_connection_update_timeout(noit_connection_ctx_t *nctx) {
689   struct timeval now, diff;
690   if(nctx->max_silence == 0) return 0;
691
692   diff.tv_sec = nctx->max_silence / 1000;
693   diff.tv_usec = (nctx->max_silence % 1000) * 1000;
694   gettimeofday(&now, NULL);
695
696   if(!nctx->timeout_event) {
697     nctx->timeout_event = eventer_alloc();
698     nctx->timeout_event->mask = EVENTER_TIMER;
699     nctx->timeout_event->closure = nctx;
700     nctx->timeout_event->callback = noit_connection_session_timeout;
701     add_timeval(now, diff, &nctx->timeout_event->whence);
702     eventer_add(nctx->timeout_event);
703   }
704   else {
705     add_timeval(now, diff, &nctx->timeout_event->whence);
706     eventer_update(nctx->timeout_event, EVENTER_TIMER);
707   }
708 }
709
710 int
711 noit_connection_disable_timeout(noit_connection_ctx_t *nctx) {
712   if(nctx->timeout_event) {
713     eventer_remove(nctx->timeout_event);
714     eventer_free(nctx->timeout_event);
715     nctx->timeout_event = NULL;
716   }
717 }
718
719 int
720 initiate_noit_connection(const char *host, unsigned short port,
721                          noit_hash_table *sslconfig, noit_hash_table *config,
722                          eventer_func_t handler, void *closure,
723                          void (*freefunc)(void *)) {
724   noit_connection_ctx_t *ctx;
725   const char *stimeout;
726   int8_t family;
727   int rv;
728   union {
729     struct in_addr addr4;
730     struct in6_addr addr6;
731   } a;
732
733   if(host[0] == '/') {
734     family = AF_UNIX;
735   }
736   else {
737     family = AF_INET;
738     rv = inet_pton(family, host, &a);
739     if(rv != 1) {
740       family = AF_INET6;
741       rv = inet_pton(family, host, &a);
742       if(rv != 1) {
743         noitL(noit_stderr, "Cannot translate '%s' to IP\n", host);
744         return -1;
745       }
746     }
747   }
748
749   ctx = noit_connection_ctx_alloc();
750   ctx->remote_str = calloc(1, strlen(host) + 7);
751   snprintf(ctx->remote_str, strlen(host) + 7,
752            "%s:%d", host, port);
753  
754   memset(&ctx->r, 0, sizeof(ctx->r));
755   if(family == AF_UNIX) {
756     struct sockaddr_un *s = &ctx->r.remote_un;
757     s->sun_family = AF_UNIX;
758     strncpy(s->sun_path, host, sizeof(s->sun_path)-1);
759     ctx->remote_len = sizeof(*s);
760   }
761   else if(family == AF_INET) {
762     struct sockaddr_in *s = &ctx->r.remote_in;
763     s->sin_family = family;
764     s->sin_port = htons(port);
765     memcpy(&s->sin_addr, &a, sizeof(struct in_addr));
766     ctx->remote_len = sizeof(*s);
767   }
768   else {
769     struct sockaddr_in6 *s = &ctx->r.remote_in6;
770     s->sin6_family = family;
771     s->sin6_port = htons(port);
772     memcpy(&s->sin6_addr, &a, sizeof(a));
773     ctx->remote_len = sizeof(*s);
774   }
775
776   if(ctx->sslconfig)
777     noit_hash_delete_all(ctx->sslconfig, free, free);
778   else
779     ctx->sslconfig = calloc(1, sizeof(noit_hash_table));
780   noit_hash_merge_as_dict(ctx->sslconfig, sslconfig);
781   if(ctx->config)
782     noit_hash_delete_all(ctx->config, free, free);
783   else
784     ctx->config = calloc(1, sizeof(noit_hash_table));
785   noit_hash_merge_as_dict(ctx->config, config);
786
787   if(noit_hash_retr_str(ctx->config, "timeout", strlen("timeout"), &stimeout))
788     ctx->max_silence = atoi(stimeout);
789   else
790     ctx->max_silence = DEFAULT_NOIT_CONNECTION_TIMEOUT;
791   ctx->consumer_callback = handler;
792   ctx->consumer_free = freefunc;
793   ctx->consumer_ctx = closure;
794   noit_connection_initiate_connection(ctx);
795   return 0;
796 }
797
798 void
799 stratcon_streamer_connection(const char *toplevel, const char *destination,
800                              eventer_func_t handler,
801                              void *(*handler_alloc)(void), void *handler_ctx,
802                              void (*handler_free)(void *)) {
803   int i, cnt = 0;
804   noit_conf_section_t *noit_configs;
805   char path[256];
806
807   snprintf(path, sizeof(path), "/%s/noits//noit", toplevel ? toplevel : "*");
808   noit_configs = noit_conf_get_sections(NULL, path, &cnt);
809   noitL(noit_error, "Found %d %s stanzas\n", cnt, path);
810   for(i=0; i<cnt; i++) {
811     char address[256];
812     unsigned short port;
813     int portint;
814     noit_hash_table *sslconfig, *config;
815
816     if(!noit_conf_get_stringbuf(noit_configs[i],
817                                 "ancestor-or-self::node()/@address",
818                                 address, sizeof(address))) {
819       noitL(noit_error, "address attribute missing in noit %d\n", i+1);
820       continue;
821     }
822     /* if destination is specified, exact match it */
823     if(destination && strcmp(address, destination)) continue;
824
825     if(!noit_conf_get_int(noit_configs[i],
826                           "ancestor-or-self::node()/@port", &portint))
827       portint = 0;
828     port = (unsigned short) portint;
829     if(address[0] != '/' && (portint == 0 || (port != portint))) {
830       /* UNIX sockets don't require a port (they'll ignore it if specified */
831       noitL(noit_stderr,
832             "Invalid port [%d] specified in stanza %d\n", port, i+1);
833       continue;
834     }
835     sslconfig = noit_conf_get_hash(noit_configs[i], "sslconfig");
836     config = noit_conf_get_hash(noit_configs[i], "config");
837
838     noitL(noit_error, "initiating to %s\n", address);
839     initiate_noit_connection(address, port, sslconfig, config,
840                              handler,
841                              handler_alloc ? handler_alloc() : handler_ctx,
842                              handler_free);
843     noit_hash_destroy(sslconfig,free,free);
844     free(sslconfig);
845     noit_hash_destroy(config,free,free);
846     free(config);
847   }
848   free(noit_configs);
849 }
850 int
851 stratcon_find_noit_ip_by_cn(const char *cn, char *ip, int len) {
852   int rv = -1;
853   void *vip;
854   pthread_mutex_lock(&noit_ip_by_cn_lock);
855   if(noit_hash_retrieve(&noit_ip_by_cn, cn, strlen(cn), &vip)) {
856     int new_len;
857     char *new_ip = (char *)vip;
858     new_len = strlen(new_ip);
859     strlcpy(ip, new_ip, len);
860     if(new_len >= len) rv = new_len+1;
861     else rv = 0;
862   }
863   pthread_mutex_unlock(&noit_ip_by_cn_lock);
864   return rv;
865 }
866 void
867 stratcon_jlog_streamer_recache_noit() {
868   int di, cnt;
869   noit_conf_section_t *noit_configs;
870   noit_configs = noit_conf_get_sections(NULL, "//noits//noit", &cnt);
871   pthread_mutex_lock(&noit_ip_by_cn_lock);
872   noit_hash_delete_all(&noit_ip_by_cn, free, free);
873   for(di=0; di<cnt; di++) {
874     char address[64];
875     if(noit_conf_get_stringbuf(noit_configs[di], "self::node()/@address",
876                                  address, sizeof(address))) {
877       char expected_cn[256];
878       if(noit_conf_get_stringbuf(noit_configs[di], "self::node()/config/cn",
879                                  expected_cn, sizeof(expected_cn)))
880         noit_hash_store(&noit_ip_by_cn,
881                         strdup(expected_cn), strlen(expected_cn),
882                         strdup(address));
883     }
884   }
885   free(noit_configs);
886   pthread_mutex_unlock(&noit_ip_by_cn_lock);
887 }
888 void
889 stratcon_jlog_streamer_reload(const char *toplevel) {
890   /* flush and repopulate the cn cache */
891   stratcon_jlog_streamer_recache_noit();
892   if(!stratcon_datastore_get_enabled()) return;
893   stratcon_streamer_connection(toplevel, NULL,
894                                stratcon_jlog_recv_handler,
895                                (void *(*)())stratcon_jlog_streamer_datastore_ctx_alloc,
896                                NULL,
897                                jlog_streamer_ctx_free);
898 }
899
900 static int
901 stratcon_console_show_noits(noit_console_closure_t ncct,
902                             int argc, char **argv,
903                             noit_console_state_t *dstate,
904                             void *closure) {
905   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
906   void *key_id;
907   int klen, n = 0, i;
908   void *vconn;
909   noit_connection_ctx_t **ctx;
910
911   pthread_mutex_lock(&noits_lock);
912   ctx = malloc(sizeof(*ctx) * noits.size);
913   while(noit_hash_next(&noits, &iter, (const char **)&key_id, &klen,
914                        &vconn)) {
915     ctx[n] = (noit_connection_ctx_t *)vconn;
916     noit_atomic_inc32(&ctx[n]->refcnt);
917     n++;
918   }
919   pthread_mutex_unlock(&noits_lock);
920   qsort(ctx, n, sizeof(*ctx), remote_str_sort);
921   for(i=0; i<n; i++) {
922     nc_print_noit_conn_brief(ncct, ctx[i]);
923     noit_connection_ctx_deref(ctx[i]);
924   }
925   free(ctx);
926   return 0;
927 }
928
929 static int
930 rest_show_noits(noit_http_rest_closure_t *restc,
931                 int npats, char **pats) {
932   xmlDocPtr doc;
933   xmlNodePtr root;
934   noit_hash_table seen = NOIT_HASH_EMPTY;
935   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
936   char path[256];
937   void *key_id, *vstr;
938   const char *type = NULL, *want_cn = NULL;
939   int klen, n = 0, i, di, cnt;
940   void *vconn;
941   noit_connection_ctx_t **ctxs;
942   noit_conf_section_t *noit_configs;
943   struct timeval now, diff, last;
944   xmlNodePtr node;
945
946   noit_http_process_querystring(&restc->http_ctx->req);
947   if(noit_hash_retrieve(&restc->http_ctx->req.querystring, "type", 4, &vstr))
948     type = vstr;
949   if(noit_hash_retrieve(&restc->http_ctx->req.querystring, "cn", 2, &vstr))
950     want_cn = vstr;
951
952   gettimeofday(&now, NULL);
953
954   pthread_mutex_lock(&noits_lock);
955   ctxs = malloc(sizeof(*ctxs) * noits.size);
956   while(noit_hash_next(&noits, &iter, (const char **)&key_id, &klen,
957                        &vconn)) {
958     ctxs[n] = (noit_connection_ctx_t *)vconn;
959     noit_atomic_inc32(&ctxs[n]->refcnt);
960     n++;
961   }
962   pthread_mutex_unlock(&noits_lock);
963   qsort(ctxs, n, sizeof(*ctxs), remote_str_sort);
964
965   doc = xmlNewDoc((xmlChar *)"1.0");
966   root = xmlNewDocNode(doc, NULL, (xmlChar *)"noits", NULL);
967   xmlDocSetRootElement(doc, root);
968
969   for(i=0; i<n; i++) {
970     char buff[256];
971     const char *feedtype = "unknown", *state = "unknown";
972     noit_connection_ctx_t *ctx = ctxs[i];
973     jlog_streamer_ctx_t *jctx = ctx->consumer_ctx;
974
975     feedtype = feed_type_to_str(ntohl(jctx->jlog_feed_cmd));
976
977     /* If the user requested a specific type and we're not it, skip. */
978     if(type && strcmp(feedtype, type)) continue;
979     /* If the user wants a specific CN... limit to that. */
980     if(want_cn && (!ctx->remote_cn || strcmp(want_cn, ctx->remote_cn)))
981       continue;
982
983     node = xmlNewNode(NULL, (xmlChar *)"noit");
984     snprintf(buff, sizeof(buff), "%llu.%06d",
985              (long long unsigned)ctx->last_connect.tv_sec,
986              (int)ctx->last_connect.tv_usec);
987     xmlSetProp(node, (xmlChar *)"last_connect", (xmlChar *)buff);
988     xmlSetProp(node, (xmlChar *)"state", ctx->remote_cn ?
989                (xmlChar *)"connected" :
990                (ctx->retry_event ? (xmlChar *)"disconnected" :
991                                     (xmlChar *)"connecting"));
992     if(ctx->e) {
993       char buff[128];
994       const char *addrstr = NULL;
995       struct sockaddr_in6 addr6;
996       socklen_t len = sizeof(addr6);
997       if(getsockname(ctx->e->fd, (struct sockaddr *)&addr6, &len) == 0) {
998         unsigned short port = 0;
999         if(addr6.sin6_family == AF_INET) {
1000           addrstr = inet_ntop(addr6.sin6_family,
1001                               &((struct sockaddr_in *)&addr6)->sin_addr,
1002                               buff, sizeof(buff));
1003           port = ntohs(((struct sockaddr_in *)&addr6)->sin_port);
1004         }
1005         else if(addr6.sin6_family == AF_INET6) {
1006           addrstr = inet_ntop(addr6.sin6_family, &addr6.sin6_addr,
1007                               buff, sizeof(buff));
1008           port = ntohs(addr6.sin6_port);
1009         }
1010         if(addrstr != NULL) {
1011           snprintf(buff + strlen(buff), sizeof(buff) - strlen(buff),
1012                    ":%u", port);
1013           xmlSetProp(node, (xmlChar *)"local", (xmlChar *)buff);
1014         }
1015       }
1016     }
1017     noit_hash_replace(&seen, strdup(ctx->remote_str), strlen(ctx->remote_str),
1018                       0, free, NULL);
1019     xmlSetProp(node, (xmlChar *)"remote", (xmlChar *)ctx->remote_str);
1020     xmlSetProp(node, (xmlChar *)"type", (xmlChar *)feedtype);
1021     if(ctx->retry_event) {
1022       sub_timeval(ctx->retry_event->whence, now, &diff);
1023       snprintf(buff, sizeof(buff), "%llu.%06d",
1024                (long long unsigned)diff.tv_sec, (int)diff.tv_usec);
1025       xmlSetProp(node, (xmlChar *)"next_attempt", (xmlChar *)buff);
1026     }
1027     else if(ctx->remote_cn) {
1028       if(ctx->remote_cn)
1029         xmlSetProp(node, (xmlChar *)"remote_cn", (xmlChar *)ctx->remote_cn);
1030  
1031       switch(jctx->state) {
1032         case JLOG_STREAMER_WANT_INITIATE: state = "initiate"; break;
1033         case JLOG_STREAMER_WANT_COUNT: state = "waiting for next batch"; break;
1034         case JLOG_STREAMER_WANT_ERROR: state = "waiting for error"; break;
1035         case JLOG_STREAMER_WANT_HEADER: state = "reading header"; break;
1036         case JLOG_STREAMER_WANT_BODY: state = "reading body"; break;
1037         case JLOG_STREAMER_IS_ASYNC: state = "asynchronously processing"; break;
1038         case JLOG_STREAMER_WANT_CHKPT: state = "checkpointing"; break;
1039       }
1040       xmlSetProp(node, (xmlChar *)"state", (xmlChar *)state);
1041       snprintf(buff, sizeof(buff), "%08x:%08x",
1042                jctx->header.chkpt.log, jctx->header.chkpt.marker);
1043       xmlSetProp(node, (xmlChar *)"checkpoint", (xmlChar *)buff);
1044       snprintf(buff, sizeof(buff), "%llu",
1045                (unsigned long long)jctx->total_events);
1046       xmlSetProp(node, (xmlChar *)"session_events", (xmlChar *)buff);
1047       snprintf(buff, sizeof(buff), "%llu",
1048                (unsigned long long)jctx->total_bytes_read);
1049       xmlSetProp(node, (xmlChar *)"session_bytes", (xmlChar *)buff);
1050  
1051       sub_timeval(now, ctx->last_connect, &diff);
1052       snprintf(buff, sizeof(buff), "%lld.%06d",
1053                (long long)diff.tv_sec, (int)diff.tv_usec);
1054       xmlSetProp(node, (xmlChar *)"session_duration", (xmlChar *)buff);
1055  
1056       if(jctx->header.tv_sec) {
1057         last.tv_sec = jctx->header.tv_sec;
1058         last.tv_usec = jctx->header.tv_usec;
1059         snprintf(buff, sizeof(buff), "%llu.%06d",
1060                  (unsigned long long)last.tv_sec, (int)last.tv_usec);
1061         xmlSetProp(node, (xmlChar *)"last_event", (xmlChar *)buff);
1062         sub_timeval(now, last, &diff);
1063         snprintf(buff, sizeof(buff), "%lld.%06d",
1064                  (long long)diff.tv_sec, (int)diff.tv_usec);
1065         xmlSetProp(node, (xmlChar *)"last_event_age", (xmlChar *)buff);
1066       }
1067     }
1068
1069     xmlAddChild(root, node);
1070     noit_connection_ctx_deref(ctx);
1071   }
1072   free(ctxs);
1073
1074   if(!type || !strcmp(type, "configured")) {
1075     snprintf(path, sizeof(path), "//noits//noit");
1076     noit_configs = noit_conf_get_sections(NULL, path, &cnt);
1077     for(di=0; di<cnt; di++) {
1078       char address[64], port_str[32], remote_str[98];
1079       char expected_cn_buff[256], *expected_cn = NULL;
1080       if(noit_conf_get_stringbuf(noit_configs[di], "self::node()/config/cn",
1081                                  expected_cn_buff, sizeof(expected_cn_buff)))
1082         expected_cn = expected_cn_buff;
1083       if(want_cn && (!expected_cn || strcmp(want_cn, expected_cn))) continue;
1084       if(noit_conf_get_stringbuf(noit_configs[di], "self::node()/@address",
1085                                  address, sizeof(address))) {
1086         void *v;
1087         if(!noit_conf_get_stringbuf(noit_configs[di], "self::node()/@port",
1088                                    port_str, sizeof(port_str)))
1089           strlcpy(port_str, "43191", sizeof(port_str));
1090
1091         /* If the user wants a specific CN... limit to that. */
1092           if(want_cn && (!expected_cn || strcmp(want_cn, expected_cn)))
1093             continue;
1094
1095         snprintf(remote_str, sizeof(remote_str), "%s:%s", address, port_str);
1096         if(!noit_hash_retrieve(&seen, remote_str, strlen(remote_str), &v)) {
1097           node = xmlNewNode(NULL, (xmlChar *)"noit");
1098           xmlSetProp(node, (xmlChar *)"remote", (xmlChar *)remote_str);
1099           xmlSetProp(node, (xmlChar *)"type", (xmlChar *)"configured");
1100           if(expected_cn)
1101             xmlSetProp(node, (xmlChar *)"cn", (xmlChar *)expected_cn);
1102           xmlAddChild(root, node);
1103         }
1104       }
1105     }
1106     free(noit_configs);
1107   }
1108   noit_hash_destroy(&seen, free, NULL);
1109
1110   noit_http_response_ok(restc->http_ctx, "text/xml");
1111   noit_http_response_xml(restc->http_ctx, doc);
1112   noit_http_response_end(restc->http_ctx);
1113   xmlFreeDoc(doc);
1114   return 0;
1115 }
1116 static int
1117 stratcon_add_noit(const char *target, unsigned short port,
1118                   const char *cn) {
1119   int cnt;
1120   char path[256];
1121   char port_str[6];
1122   noit_conf_section_t *noit_configs, parent;
1123   xmlNodePtr newnoit, config, cnnode;
1124
1125   snprintf(path, sizeof(path),
1126            "//noits//noit[@address=\"%s\" and @port=\"%d\"]", target, port);
1127   noit_configs = noit_conf_get_sections(NULL, path, &cnt);
1128   free(noit_configs);
1129   if(cnt != 0) return -1;
1130
1131   parent = noit_conf_get_section(NULL, "//noits");
1132   if(!parent) return -1;
1133   snprintf(port_str, sizeof(port_str), "%d", port);
1134   newnoit = xmlNewNode(NULL, (xmlChar *)"noit");
1135   xmlSetProp(newnoit, (xmlChar *)"address", (xmlChar *)target);
1136   xmlSetProp(newnoit, (xmlChar *)"port", (xmlChar *)port_str);
1137   xmlAddChild(parent, newnoit);
1138   if(cn) {
1139     config = xmlNewNode(NULL, (xmlChar *)"config");
1140     cnnode = xmlNewNode(NULL, (xmlChar *)"cn");
1141     xmlNodeAddContent(cnnode, (xmlChar *)cn);
1142     xmlAddChild(config, cnnode);
1143     xmlAddChild(newnoit, config);
1144     pthread_mutex_lock(&noit_ip_by_cn_lock);
1145     noit_hash_replace(&noit_ip_by_cn, strdup(cn), strlen(cn),
1146                       strdup(target), free, free);
1147     pthread_mutex_unlock(&noit_ip_by_cn_lock);
1148   }
1149   if(stratcon_datastore_get_enabled())
1150     stratcon_streamer_connection(NULL, target,
1151                                  stratcon_jlog_recv_handler,
1152                                  (void *(*)())stratcon_jlog_streamer_datastore_ctx_alloc,
1153                                  NULL,
1154                                  jlog_streamer_ctx_free);
1155   if(stratcon_iep_get_enabled())
1156     stratcon_streamer_connection(NULL, target,
1157                                  stratcon_jlog_recv_handler,
1158                                  (void *(*)())stratcon_jlog_streamer_iep_ctx_alloc,
1159                                  NULL,
1160                                  jlog_streamer_ctx_free);
1161   return 1;
1162 }
1163 static int
1164 stratcon_remove_noit(const char *target, unsigned short port) {
1165   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
1166   void *key_id;
1167   int klen, n = -1, i, cnt = 0;
1168   void *vconn;
1169   noit_connection_ctx_t **ctx;
1170   noit_conf_section_t *noit_configs;
1171   char path[256];
1172   char remote_str[256];
1173
1174   snprintf(remote_str, sizeof(remote_str), "%s:%d", target, port);
1175
1176   snprintf(path, sizeof(path),
1177            "//noits//noit[@address=\"%s\" and @port=\"%d\"]", target, port);
1178   noit_configs = noit_conf_get_sections(NULL, path, &cnt);
1179   for(i=0; i<cnt; i++) {
1180     char expected_cn[256];
1181     if(noit_conf_get_stringbuf(noit_configs[i], "self::node()/config/cn",
1182                                expected_cn, sizeof(expected_cn))) {
1183       pthread_mutex_lock(&noit_ip_by_cn_lock);
1184       noit_hash_delete(&noit_ip_by_cn, expected_cn, strlen(expected_cn),
1185                        free, free);
1186       pthread_mutex_unlock(&noit_ip_by_cn_lock);
1187     }
1188     xmlUnlinkNode(noit_configs[i]);
1189     xmlFreeNode(noit_configs[i]);
1190     n = 0;
1191   }
1192   free(noit_configs);
1193
1194   pthread_mutex_lock(&noits_lock);
1195   ctx = malloc(sizeof(*ctx) * noits.size);
1196   while(noit_hash_next(&noits, &iter, (const char **)&key_id, &klen,
1197                        &vconn)) {
1198     if(!strcmp(((noit_connection_ctx_t *)vconn)->remote_str, remote_str)) {
1199       ctx[n] = (noit_connection_ctx_t *)vconn;
1200       noit_atomic_inc32(&ctx[n]->refcnt);
1201       n++;
1202     }
1203   }
1204   pthread_mutex_unlock(&noits_lock);
1205   for(i=0; i<n; i++) {
1206     noit_connection_ctx_dealloc(ctx[i]); /* once for the record */
1207     noit_connection_ctx_deref(ctx[i]);   /* once for the aboce inc32 */
1208   }
1209   free(ctx);
1210   return n;
1211 }
1212 static int
1213 rest_set_noit(noit_http_rest_closure_t *restc,
1214               int npats, char **pats) {
1215   void *vcn;
1216   const char *cn = NULL;
1217   noit_http_session_ctx *ctx = restc->http_ctx;
1218   unsigned short port = 43191;
1219   if(npats < 1 || npats > 2)
1220     noit_http_response_server_error(ctx, "text/xml");
1221   if(npats == 2) port = atoi(pats[1]);
1222   noit_http_process_querystring(&ctx->req);
1223   if(noit_hash_retrieve(&ctx->req.querystring, "cn", 2, &vcn))
1224     cn = vcn;
1225   if(stratcon_add_noit(pats[0], port, cn) >= 0)
1226     noit_http_response_ok(ctx, "text/xml");
1227   else
1228     noit_http_response_standard(ctx, 409, "EXISTS", "text/xml");
1229   if(noit_conf_write_file(NULL) != 0)
1230     noitL(noit_error, "local config write failed\n");
1231   noit_conf_mark_changed();
1232   noit_http_response_end(ctx);
1233   return 0;
1234 }
1235 static int
1236 rest_delete_noit(noit_http_rest_closure_t *restc,
1237                  int npats, char **pats) {
1238   noit_http_session_ctx *ctx = restc->http_ctx;
1239   unsigned short port = 43191;
1240   if(npats < 1 || npats > 2)
1241     noit_http_response_server_error(ctx, "text/xml");
1242   if(npats == 2) port = atoi(pats[1]);
1243   if(stratcon_remove_noit(pats[0], port) >= 0)
1244     noit_http_response_ok(ctx, "text/xml");
1245   else
1246     noit_http_response_not_found(ctx, "text/xml");
1247   if(noit_conf_write_file(NULL) != 0)
1248     noitL(noit_error, "local config write failed\n");
1249   noit_conf_mark_changed();
1250   noit_http_response_end(ctx);
1251   return 0;
1252 }
1253 static int
1254 stratcon_console_conf_noits(noit_console_closure_t ncct,
1255                             int argc, char **argv,
1256                             noit_console_state_t *dstate,
1257                             void *closure) {
1258   char *cp, target[128];
1259   unsigned short port = 43191;
1260   int adding = (int)(vpsized_int)closure;
1261   if(argc != 1)
1262     return -1;
1263
1264   cp = strchr(argv[0], ':');
1265   if(cp) {
1266     strlcpy(target, argv[0], MIN(sizeof(target), cp-argv[0]+1));
1267     port = atoi(cp+1);
1268   }
1269   else strlcpy(target, argv[0], sizeof(target));
1270   if(adding) {
1271     if(stratcon_add_noit(target, port, NULL) >= 0) {
1272       nc_printf(ncct, "Added noit at %s:%d\n", target, port);
1273     }
1274     else {
1275       nc_printf(ncct, "Failed to add noit at %s:%d\n", target, port);
1276     }
1277   }
1278   else {
1279     if(stratcon_remove_noit(target, port) >= 0) {
1280       nc_printf(ncct, "Removed noit at %s:%d\n", target, port);
1281     }
1282     else {
1283       nc_printf(ncct, "Failed to remove noit at %s:%d\n", target, port);
1284     }
1285   }
1286   return 0;
1287 }
1288
1289 static void
1290 register_console_streamer_commands() {
1291   noit_console_state_t *tl;
1292   cmd_info_t *showcmd, *confcmd, *conftcmd, *conftnocmd;
1293
1294   tl = noit_console_state_initial();
1295   showcmd = noit_console_state_get_cmd(tl, "show");
1296   assert(showcmd && showcmd->dstate);
1297   confcmd = noit_console_state_get_cmd(tl, "configure");
1298   conftcmd = noit_console_state_get_cmd(confcmd->dstate, "terminal");
1299   conftnocmd = noit_console_state_get_cmd(conftcmd->dstate, "no");
1300
1301   noit_console_state_add_cmd(conftcmd->dstate,
1302     NCSCMD("noit", stratcon_console_conf_noits, NULL, NULL, (void *)1));
1303   noit_console_state_add_cmd(conftnocmd->dstate,
1304     NCSCMD("noit", stratcon_console_conf_noits, NULL, NULL, (void *)0));
1305
1306   noit_console_state_add_cmd(showcmd->dstate,
1307     NCSCMD("noits", stratcon_console_show_noits, NULL, NULL, NULL));
1308 }
1309
1310 void
1311 stratcon_jlog_streamer_init(const char *toplevel) {
1312   pthread_mutex_init(&noits_lock, NULL);
1313   pthread_mutex_init(&noit_ip_by_cn_lock, NULL);
1314   eventer_name_callback("noit_connection_reinitiate",
1315                         noit_connection_reinitiate);
1316   eventer_name_callback("stratcon_jlog_recv_handler",
1317                         stratcon_jlog_recv_handler);
1318   eventer_name_callback("noit_connection_ssl_upgrade",
1319                         noit_connection_ssl_upgrade);
1320   eventer_name_callback("noit_connection_complete_connect",
1321                         noit_connection_complete_connect);
1322   eventer_name_callback("noit_connection_session_timeout",
1323                         noit_connection_session_timeout);
1324   register_console_streamer_commands();
1325   stratcon_jlog_streamer_reload(toplevel);
1326   stratcon_streamer_connection(toplevel, "", NULL, NULL, NULL, NULL);
1327   assert(noit_http_rest_register_auth(
1328     "GET", "/noits/", "^show$", rest_show_noits,
1329              noit_http_rest_client_cert_auth
1330   ) == 0);
1331   assert(noit_http_rest_register_auth(
1332     "PUT", "/noits/", "^set/([^/:]+)$", rest_set_noit,
1333              noit_http_rest_client_cert_auth
1334   ) == 0);
1335   assert(noit_http_rest_register_auth(
1336     "PUT", "/noits/", "^set/([^/:]+):(\\d+)$", rest_set_noit,
1337              noit_http_rest_client_cert_auth
1338   ) == 0);
1339   assert(noit_http_rest_register_auth(
1340     "DELETE", "/noits/", "^delete/([^/:]+)$", rest_delete_noit,
1341              noit_http_rest_client_cert_auth
1342   ) == 0);
1343   assert(noit_http_rest_register_auth(
1344     "DELETE", "/noits/", "^delete/([^/:]+):(\\d+)$", rest_delete_noit,
1345              noit_http_rest_client_cert_auth
1346   ) == 0);
1347 }
1348
Note: See TracBrowser for help on using the browser.