root/src/stratcon_jlog_streamer.c

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

dead assignments, refs #283

  • 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, "%s", 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         snprintf(remote_str, sizeof(remote_str), "%s", nctx->r.remote_un.sun_path);
579         break;
580       default:
581         snprintf(remote_str, sizeof(remote_str), "(unknown)");
582     }
583     noitL(noit_error, "Error connecting to %s: %s\n",
584           remote_str, strerror(aerrno));
585     eventer_remove_fd(e->fd);
586     nctx->e = NULL;
587     e->opset->close(e->fd, &mask, e);
588     noit_connection_schedule_reattempt(nctx, now);
589     return 0;
590   }
591
592 #define SSLCONFGET(var,name) do { \
593   if(!noit_hash_retr_str(nctx->sslconfig, name, strlen(name), \
594                          &var)) var = NULL; } while(0)
595   SSLCONFGET(cert, "certificate_file");
596   SSLCONFGET(key, "key_file");
597   SSLCONFGET(ca, "ca_chain");
598   SSLCONFGET(ciphers, "ciphers");
599   SSLCONFGET(crl, "crl");
600   sslctx = eventer_ssl_ctx_new(SSL_CLIENT, cert, key, ca, ciphers);
601   if(!sslctx) goto connect_error;
602   if(crl) {
603     if(!eventer_ssl_use_crl(sslctx, crl)) {
604       noitL(noit_error, "Failed to load CRL from %s\n", crl);
605       eventer_ssl_ctx_free(sslctx);
606       goto connect_error;
607     }
608   }
609
610   memcpy(&nctx->last_connect, now, sizeof(*now));
611   eventer_ssl_ctx_set_verify(sslctx, eventer_ssl_verify_cert,
612                              nctx->sslconfig);
613   EVENTER_ATTACH_SSL(e, sslctx);
614   e->callback = noit_connection_ssl_upgrade;
615   return e->callback(e, mask, closure, now);
616 }
617 static void
618 noit_connection_initiate_connection(noit_connection_ctx_t *nctx) {
619   struct timeval __now;
620   eventer_t e;
621   int rv, fd = -1;
622 #ifdef SO_KEEPALIVE
623   int optval;
624   socklen_t optlen = sizeof(optval);
625 #endif
626
627   nctx->e = NULL;
628   if(nctx->wants_permanent_shutdown) {
629     noit_connection_ctx_dealloc(nctx);
630     return;
631   }
632   /* Open a socket */
633   fd = socket(nctx->r.remote.sa_family, SOCK_STREAM, 0);
634   if(fd < 0) goto reschedule;
635
636   /* Make it non-blocking */
637   if(eventer_set_fd_nonblocking(fd)) goto reschedule;
638 #define set_or_bail(type, opt, val) do { \
639   optval = val; \
640   optlen = sizeof(optval); \
641   if(setsockopt(fd, type, opt, &optval, optlen) < 0) { \
642     noitL(noit_error, "Cannot set " #type "/" #opt " on jlog socket: %s\n", \
643           strerror(errno)); \
644     goto reschedule; \
645   } \
646 } while(0)
647 #ifdef SO_KEEPALIVE
648   set_or_bail(SOL_SOCKET, SO_KEEPALIVE, 1);
649 #endif
650 #ifdef TCP_KEEPALIVE_THRESHOLD
651   set_or_bail(IPPROTO_TCP, TCP_KEEPALIVE_THRESHOLD, 10 * 1000);
652 #endif
653 #ifdef TCP_KEEPALIVE_ABORT_THRESHOLD
654   set_or_bail(IPPROTO_TCP, TCP_KEEPALIVE_ABORT_THRESHOLD, 30 * 1000);
655 #endif
656 #ifdef TCP_CONN_NOTIFY_THRESHOLD
657   set_or_bail(IPPROTO_TCP, TCP_CONN_NOTIFY_THRESHOLD, 10 * 1000);
658 #endif
659 #ifdef TCP_CONN_ABORT_THRESHOLD
660   set_or_bail(IPPROTO_TCP, TCP_CONN_ABORT_THRESHOLD, 30 * 1000);
661 #endif
662
663   /* Initiate a connection */
664   rv = connect(fd, &nctx->r.remote, nctx->remote_len);
665   if(rv == -1 && errno != EINPROGRESS) goto reschedule;
666
667   /* Register a handler for connection completion */
668   e = eventer_alloc();
669   e->fd = fd;
670   e->mask = EVENTER_READ | EVENTER_WRITE | EVENTER_EXCEPTION;
671   e->callback = noit_connection_complete_connect;
672   e->closure = nctx;
673   nctx->e = e;
674   eventer_add(e);
675
676   noit_connection_update_timeout(nctx);
677   return;
678
679  reschedule:
680   if(fd >= 0) close(fd);
681   gettimeofday(&__now, NULL);
682   noit_connection_schedule_reattempt(nctx, &__now);
683   return;
684 }
685
686 int
687 noit_connection_update_timeout(noit_connection_ctx_t *nctx) {
688   struct timeval now, diff;
689   if(nctx->max_silence == 0) return 0;
690
691   diff.tv_sec = nctx->max_silence / 1000;
692   diff.tv_usec = (nctx->max_silence % 1000) * 1000;
693   gettimeofday(&now, NULL);
694
695   if(!nctx->timeout_event) {
696     nctx->timeout_event = eventer_alloc();
697     nctx->timeout_event->mask = EVENTER_TIMER;
698     nctx->timeout_event->closure = nctx;
699     nctx->timeout_event->callback = noit_connection_session_timeout;
700     add_timeval(now, diff, &nctx->timeout_event->whence);
701     eventer_add(nctx->timeout_event);
702   }
703   else {
704     add_timeval(now, diff, &nctx->timeout_event->whence);
705     eventer_update(nctx->timeout_event, EVENTER_TIMER);
706   }
707   return 0;
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   return 0;
718 }
719
720 int
721 initiate_noit_connection(const char *host, unsigned short port,
722                          noit_hash_table *sslconfig, noit_hash_table *config,
723                          eventer_func_t handler, void *closure,
724                          void (*freefunc)(void *)) {
725   noit_connection_ctx_t *ctx;
726   const char *stimeout;
727   int8_t family;
728   int rv;
729   union {
730     struct in_addr addr4;
731     struct in6_addr addr6;
732   } a;
733
734   if(host[0] == '/') {
735     family = AF_UNIX;
736   }
737   else {
738     family = AF_INET;
739     rv = inet_pton(family, host, &a);
740     if(rv != 1) {
741       family = AF_INET6;
742       rv = inet_pton(family, host, &a);
743       if(rv != 1) {
744         noitL(noit_stderr, "Cannot translate '%s' to IP\n", host);
745         return -1;
746       }
747     }
748   }
749
750   ctx = noit_connection_ctx_alloc();
751   ctx->remote_str = calloc(1, strlen(host) + 7);
752   snprintf(ctx->remote_str, strlen(host) + 7,
753            "%s:%d", host, port);
754  
755   memset(&ctx->r, 0, sizeof(ctx->r));
756   if(family == AF_UNIX) {
757     struct sockaddr_un *s = &ctx->r.remote_un;
758     s->sun_family = AF_UNIX;
759     strncpy(s->sun_path, host, sizeof(s->sun_path)-1);
760     ctx->remote_len = sizeof(*s);
761   }
762   else if(family == AF_INET) {
763     struct sockaddr_in *s = &ctx->r.remote_in;
764     s->sin_family = family;
765     s->sin_port = htons(port);
766     memcpy(&s->sin_addr, &a, sizeof(struct in_addr));
767     ctx->remote_len = sizeof(*s);
768   }
769   else {
770     struct sockaddr_in6 *s = &ctx->r.remote_in6;
771     s->sin6_family = family;
772     s->sin6_port = htons(port);
773     memcpy(&s->sin6_addr, &a, sizeof(a));
774     ctx->remote_len = sizeof(*s);
775   }
776
777   if(ctx->sslconfig)
778     noit_hash_delete_all(ctx->sslconfig, free, free);
779   else
780     ctx->sslconfig = calloc(1, sizeof(noit_hash_table));
781   noit_hash_merge_as_dict(ctx->sslconfig, sslconfig);
782   if(ctx->config)
783     noit_hash_delete_all(ctx->config, free, free);
784   else
785     ctx->config = calloc(1, sizeof(noit_hash_table));
786   noit_hash_merge_as_dict(ctx->config, config);
787
788   if(noit_hash_retr_str(ctx->config, "timeout", strlen("timeout"), &stimeout))
789     ctx->max_silence = atoi(stimeout);
790   else
791     ctx->max_silence = DEFAULT_NOIT_CONNECTION_TIMEOUT;
792   ctx->consumer_callback = handler;
793   ctx->consumer_free = freefunc;
794   ctx->consumer_ctx = closure;
795   noit_connection_initiate_connection(ctx);
796   return 0;
797 }
798
799 void
800 stratcon_streamer_connection(const char *toplevel, const char *destination,
801                              eventer_func_t handler,
802                              void *(*handler_alloc)(void), void *handler_ctx,
803                              void (*handler_free)(void *)) {
804   int i, cnt = 0;
805   noit_conf_section_t *noit_configs;
806   char path[256];
807
808   snprintf(path, sizeof(path), "/%s/noits//noit", toplevel ? toplevel : "*");
809   noit_configs = noit_conf_get_sections(NULL, path, &cnt);
810   noitL(noit_error, "Found %d %s stanzas\n", cnt, path);
811   for(i=0; i<cnt; i++) {
812     char address[256];
813     unsigned short port;
814     int portint;
815     noit_hash_table *sslconfig, *config;
816
817     if(!noit_conf_get_stringbuf(noit_configs[i],
818                                 "ancestor-or-self::node()/@address",
819                                 address, sizeof(address))) {
820       noitL(noit_error, "address attribute missing in noit %d\n", i+1);
821       continue;
822     }
823     /* if destination is specified, exact match it */
824     if(destination && strcmp(address, destination)) continue;
825
826     if(!noit_conf_get_int(noit_configs[i],
827                           "ancestor-or-self::node()/@port", &portint))
828       portint = 0;
829     port = (unsigned short) portint;
830     if(address[0] != '/' && (portint == 0 || (port != portint))) {
831       /* UNIX sockets don't require a port (they'll ignore it if specified */
832       noitL(noit_stderr,
833             "Invalid port [%d] specified in stanza %d\n", port, i+1);
834       continue;
835     }
836     sslconfig = noit_conf_get_hash(noit_configs[i], "sslconfig");
837     config = noit_conf_get_hash(noit_configs[i], "config");
838
839     noitL(noit_error, "initiating to %s\n", address);
840     initiate_noit_connection(address, port, sslconfig, config,
841                              handler,
842                              handler_alloc ? handler_alloc() : handler_ctx,
843                              handler_free);
844     noit_hash_destroy(sslconfig,free,free);
845     free(sslconfig);
846     noit_hash_destroy(config,free,free);
847     free(config);
848   }
849   free(noit_configs);
850 }
851 int
852 stratcon_find_noit_ip_by_cn(const char *cn, char *ip, int len) {
853   int rv = -1;
854   void *vip;
855   pthread_mutex_lock(&noit_ip_by_cn_lock);
856   if(noit_hash_retrieve(&noit_ip_by_cn, cn, strlen(cn), &vip)) {
857     int new_len;
858     char *new_ip = (char *)vip;
859     new_len = strlen(new_ip);
860     strlcpy(ip, new_ip, len);
861     if(new_len >= len) rv = new_len+1;
862     else rv = 0;
863   }
864   pthread_mutex_unlock(&noit_ip_by_cn_lock);
865   return rv;
866 }
867 void
868 stratcon_jlog_streamer_recache_noit() {
869   int di, cnt;
870   noit_conf_section_t *noit_configs;
871   noit_configs = noit_conf_get_sections(NULL, "//noits//noit", &cnt);
872   pthread_mutex_lock(&noit_ip_by_cn_lock);
873   noit_hash_delete_all(&noit_ip_by_cn, free, free);
874   for(di=0; di<cnt; di++) {
875     char address[64];
876     if(noit_conf_get_stringbuf(noit_configs[di], "self::node()/@address",
877                                  address, sizeof(address))) {
878       char expected_cn[256];
879       if(noit_conf_get_stringbuf(noit_configs[di], "self::node()/config/cn",
880                                  expected_cn, sizeof(expected_cn)))
881         noit_hash_store(&noit_ip_by_cn,
882                         strdup(expected_cn), strlen(expected_cn),
883                         strdup(address));
884     }
885   }
886   free(noit_configs);
887   pthread_mutex_unlock(&noit_ip_by_cn_lock);
888 }
889 void
890 stratcon_jlog_streamer_reload(const char *toplevel) {
891   /* flush and repopulate the cn cache */
892   stratcon_jlog_streamer_recache_noit();
893   if(!stratcon_datastore_get_enabled()) return;
894   stratcon_streamer_connection(toplevel, NULL,
895                                stratcon_jlog_recv_handler,
896                                (void *(*)())stratcon_jlog_streamer_datastore_ctx_alloc,
897                                NULL,
898                                jlog_streamer_ctx_free);
899 }
900
901 static int
902 stratcon_console_show_noits(noit_console_closure_t ncct,
903                             int argc, char **argv,
904                             noit_console_state_t *dstate,
905                             void *closure) {
906   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
907   void *key_id;
908   int klen, n = 0, i;
909   void *vconn;
910   noit_connection_ctx_t **ctx;
911
912   pthread_mutex_lock(&noits_lock);
913   ctx = malloc(sizeof(*ctx) * noits.size);
914   while(noit_hash_next(&noits, &iter, (const char **)&key_id, &klen,
915                        &vconn)) {
916     ctx[n] = (noit_connection_ctx_t *)vconn;
917     noit_atomic_inc32(&ctx[n]->refcnt);
918     n++;
919   }
920   pthread_mutex_unlock(&noits_lock);
921   qsort(ctx, n, sizeof(*ctx), remote_str_sort);
922   for(i=0; i<n; i++) {
923     nc_print_noit_conn_brief(ncct, ctx[i]);
924     noit_connection_ctx_deref(ctx[i]);
925   }
926   free(ctx);
927   return 0;
928 }
929
930 static int
931 rest_show_noits(noit_http_rest_closure_t *restc,
932                 int npats, char **pats) {
933   xmlDocPtr doc;
934   xmlNodePtr root;
935   noit_hash_table seen = NOIT_HASH_EMPTY;
936   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
937   char path[256];
938   void *key_id, *vstr;
939   const char *type = NULL, *want_cn = NULL;
940   int klen, n = 0, i, di, cnt;
941   void *vconn;
942   noit_connection_ctx_t **ctxs;
943   noit_conf_section_t *noit_configs;
944   struct timeval now, diff, last;
945   xmlNodePtr node;
946
947   noit_http_process_querystring(&restc->http_ctx->req);
948   if(noit_hash_retrieve(&restc->http_ctx->req.querystring, "type", 4, &vstr))
949     type = vstr;
950   if(noit_hash_retrieve(&restc->http_ctx->req.querystring, "cn", 2, &vstr))
951     want_cn = vstr;
952
953   gettimeofday(&now, NULL);
954
955   pthread_mutex_lock(&noits_lock);
956   ctxs = malloc(sizeof(*ctxs) * noits.size);
957   while(noit_hash_next(&noits, &iter, (const char **)&key_id, &klen,
958                        &vconn)) {
959     ctxs[n] = (noit_connection_ctx_t *)vconn;
960     noit_atomic_inc32(&ctxs[n]->refcnt);
961     n++;
962   }
963   pthread_mutex_unlock(&noits_lock);
964   qsort(ctxs, n, sizeof(*ctxs), remote_str_sort);
965
966   doc = xmlNewDoc((xmlChar *)"1.0");
967   root = xmlNewDocNode(doc, NULL, (xmlChar *)"noits", NULL);
968   xmlDocSetRootElement(doc, root);
969
970   for(i=0; i<n; i++) {
971     char buff[256];
972     const char *feedtype = "unknown", *state = "unknown";
973     noit_connection_ctx_t *ctx = ctxs[i];
974     jlog_streamer_ctx_t *jctx = ctx->consumer_ctx;
975
976     feedtype = feed_type_to_str(ntohl(jctx->jlog_feed_cmd));
977
978     /* If the user requested a specific type and we're not it, skip. */
979     if(type && strcmp(feedtype, type)) continue;
980     /* If the user wants a specific CN... limit to that. */
981     if(want_cn && (!ctx->remote_cn || strcmp(want_cn, ctx->remote_cn)))
982       continue;
983
984     node = xmlNewNode(NULL, (xmlChar *)"noit");
985     snprintf(buff, sizeof(buff), "%llu.%06d",
986              (long long unsigned)ctx->last_connect.tv_sec,
987              (int)ctx->last_connect.tv_usec);
988     xmlSetProp(node, (xmlChar *)"last_connect", (xmlChar *)buff);
989     xmlSetProp(node, (xmlChar *)"state", ctx->remote_cn ?
990                (xmlChar *)"connected" :
991                (ctx->retry_event ? (xmlChar *)"disconnected" :
992                                     (xmlChar *)"connecting"));
993     if(ctx->e) {
994       char buff[128];
995       const char *addrstr = NULL;
996       struct sockaddr_in6 addr6;
997       socklen_t len = sizeof(addr6);
998       if(getsockname(ctx->e->fd, (struct sockaddr *)&addr6, &len) == 0) {
999         unsigned short port = 0;
1000         if(addr6.sin6_family == AF_INET) {
1001           addrstr = inet_ntop(addr6.sin6_family,
1002                               &((struct sockaddr_in *)&addr6)->sin_addr,
1003                               buff, sizeof(buff));
1004           port = ntohs(((struct sockaddr_in *)&addr6)->sin_port);
1005         }
1006         else if(addr6.sin6_family == AF_INET6) {
1007           addrstr = inet_ntop(addr6.sin6_family, &addr6.sin6_addr,
1008                               buff, sizeof(buff));
1009           port = ntohs(addr6.sin6_port);
1010         }
1011         if(addrstr != NULL) {
1012           snprintf(buff + strlen(buff), sizeof(buff) - strlen(buff),
1013                    ":%u", port);
1014           xmlSetProp(node, (xmlChar *)"local", (xmlChar *)buff);
1015         }
1016       }
1017     }
1018     noit_hash_replace(&seen, strdup(ctx->remote_str), strlen(ctx->remote_str),
1019                       0, free, NULL);
1020     xmlSetProp(node, (xmlChar *)"remote", (xmlChar *)ctx->remote_str);
1021     xmlSetProp(node, (xmlChar *)"type", (xmlChar *)feedtype);
1022     if(ctx->retry_event) {
1023       sub_timeval(ctx->retry_event->whence, now, &diff);
1024       snprintf(buff, sizeof(buff), "%llu.%06d",
1025                (long long unsigned)diff.tv_sec, (int)diff.tv_usec);
1026       xmlSetProp(node, (xmlChar *)"next_attempt", (xmlChar *)buff);
1027     }
1028     else if(ctx->remote_cn) {
1029       if(ctx->remote_cn)
1030         xmlSetProp(node, (xmlChar *)"remote_cn", (xmlChar *)ctx->remote_cn);
1031  
1032       switch(jctx->state) {
1033         case JLOG_STREAMER_WANT_INITIATE: state = "initiate"; break;
1034         case JLOG_STREAMER_WANT_COUNT: state = "waiting for next batch"; break;
1035         case JLOG_STREAMER_WANT_ERROR: state = "waiting for error"; break;
1036         case JLOG_STREAMER_WANT_HEADER: state = "reading header"; break;
1037         case JLOG_STREAMER_WANT_BODY: state = "reading body"; break;
1038         case JLOG_STREAMER_IS_ASYNC: state = "asynchronously processing"; break;
1039         case JLOG_STREAMER_WANT_CHKPT: state = "checkpointing"; break;
1040       }
1041       xmlSetProp(node, (xmlChar *)"state", (xmlChar *)state);
1042       snprintf(buff, sizeof(buff), "%08x:%08x",
1043                jctx->header.chkpt.log, jctx->header.chkpt.marker);
1044       xmlSetProp(node, (xmlChar *)"checkpoint", (xmlChar *)buff);
1045       snprintf(buff, sizeof(buff), "%llu",
1046                (unsigned long long)jctx->total_events);
1047       xmlSetProp(node, (xmlChar *)"session_events", (xmlChar *)buff);
1048       snprintf(buff, sizeof(buff), "%llu",
1049                (unsigned long long)jctx->total_bytes_read);
1050       xmlSetProp(node, (xmlChar *)"session_bytes", (xmlChar *)buff);
1051  
1052       sub_timeval(now, ctx->last_connect, &diff);
1053       snprintf(buff, sizeof(buff), "%lld.%06d",
1054                (long long)diff.tv_sec, (int)diff.tv_usec);
1055       xmlSetProp(node, (xmlChar *)"session_duration", (xmlChar *)buff);
1056  
1057       if(jctx->header.tv_sec) {
1058         last.tv_sec = jctx->header.tv_sec;
1059         last.tv_usec = jctx->header.tv_usec;
1060         snprintf(buff, sizeof(buff), "%llu.%06d",
1061                  (unsigned long long)last.tv_sec, (int)last.tv_usec);
1062         xmlSetProp(node, (xmlChar *)"last_event", (xmlChar *)buff);
1063         sub_timeval(now, last, &diff);
1064         snprintf(buff, sizeof(buff), "%lld.%06d",
1065                  (long long)diff.tv_sec, (int)diff.tv_usec);
1066         xmlSetProp(node, (xmlChar *)"last_event_age", (xmlChar *)buff);
1067       }
1068     }
1069
1070     xmlAddChild(root, node);
1071     noit_connection_ctx_deref(ctx);
1072   }
1073   free(ctxs);
1074
1075   if(!type || !strcmp(type, "configured")) {
1076     snprintf(path, sizeof(path), "//noits//noit");
1077     noit_configs = noit_conf_get_sections(NULL, path, &cnt);
1078     for(di=0; di<cnt; di++) {
1079       char address[64], port_str[32], remote_str[98];
1080       char expected_cn_buff[256], *expected_cn = NULL;
1081       if(noit_conf_get_stringbuf(noit_configs[di], "self::node()/config/cn",
1082                                  expected_cn_buff, sizeof(expected_cn_buff)))
1083         expected_cn = expected_cn_buff;
1084       if(want_cn && (!expected_cn || strcmp(want_cn, expected_cn))) continue;
1085       if(noit_conf_get_stringbuf(noit_configs[di], "self::node()/@address",
1086                                  address, sizeof(address))) {
1087         void *v;
1088         if(!noit_conf_get_stringbuf(noit_configs[di], "self::node()/@port",
1089                                    port_str, sizeof(port_str)))
1090           strlcpy(port_str, "43191", sizeof(port_str));
1091
1092         /* If the user wants a specific CN... limit to that. */
1093           if(want_cn && (!expected_cn || strcmp(want_cn, expected_cn)))
1094             continue;
1095
1096         snprintf(remote_str, sizeof(remote_str), "%s:%s", address, port_str);
1097         if(!noit_hash_retrieve(&seen, remote_str, strlen(remote_str), &v)) {
1098           node = xmlNewNode(NULL, (xmlChar *)"noit");
1099           xmlSetProp(node, (xmlChar *)"remote", (xmlChar *)remote_str);
1100           xmlSetProp(node, (xmlChar *)"type", (xmlChar *)"configured");
1101           if(expected_cn)
1102             xmlSetProp(node, (xmlChar *)"cn", (xmlChar *)expected_cn);
1103           xmlAddChild(root, node);
1104         }
1105       }
1106     }
1107     free(noit_configs);
1108   }
1109   noit_hash_destroy(&seen, free, NULL);
1110
1111   noit_http_response_ok(restc->http_ctx, "text/xml");
1112   noit_http_response_xml(restc->http_ctx, doc);
1113   noit_http_response_end(restc->http_ctx);
1114   xmlFreeDoc(doc);
1115   return 0;
1116 }
1117 static int
1118 stratcon_add_noit(const char *target, unsigned short port,
1119                   const char *cn) {
1120   int cnt;
1121   char path[256];
1122   char port_str[6];
1123   noit_conf_section_t *noit_configs, parent;
1124   xmlNodePtr newnoit, config, cnnode;
1125
1126   snprintf(path, sizeof(path),
1127            "//noits//noit[@address=\"%s\" and @port=\"%d\"]", target, port);
1128   noit_configs = noit_conf_get_sections(NULL, path, &cnt);
1129   free(noit_configs);
1130   if(cnt != 0) return -1;
1131
1132   parent = noit_conf_get_section(NULL, "//noits");
1133   if(!parent) return -1;
1134   snprintf(port_str, sizeof(port_str), "%d", port);
1135   newnoit = xmlNewNode(NULL, (xmlChar *)"noit");
1136   xmlSetProp(newnoit, (xmlChar *)"address", (xmlChar *)target);
1137   xmlSetProp(newnoit, (xmlChar *)"port", (xmlChar *)port_str);
1138   xmlAddChild(parent, newnoit);
1139   if(cn) {
1140     config = xmlNewNode(NULL, (xmlChar *)"config");
1141     cnnode = xmlNewNode(NULL, (xmlChar *)"cn");
1142     xmlNodeAddContent(cnnode, (xmlChar *)cn);
1143     xmlAddChild(config, cnnode);
1144     xmlAddChild(newnoit, config);
1145     pthread_mutex_lock(&noit_ip_by_cn_lock);
1146     noit_hash_replace(&noit_ip_by_cn, strdup(cn), strlen(cn),
1147                       strdup(target), free, free);
1148     pthread_mutex_unlock(&noit_ip_by_cn_lock);
1149   }
1150   if(stratcon_datastore_get_enabled())
1151     stratcon_streamer_connection(NULL, target,
1152                                  stratcon_jlog_recv_handler,
1153                                  (void *(*)())stratcon_jlog_streamer_datastore_ctx_alloc,
1154                                  NULL,
1155                                  jlog_streamer_ctx_free);
1156   if(stratcon_iep_get_enabled())
1157     stratcon_streamer_connection(NULL, target,
1158                                  stratcon_jlog_recv_handler,
1159                                  (void *(*)())stratcon_jlog_streamer_iep_ctx_alloc,
1160                                  NULL,
1161                                  jlog_streamer_ctx_free);
1162   return 1;
1163 }
1164 static int
1165 stratcon_remove_noit(const char *target, unsigned short port) {
1166   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
1167   void *key_id;
1168   int klen, n = -1, i, cnt = 0;
1169   void *vconn;
1170   noit_connection_ctx_t **ctx;
1171   noit_conf_section_t *noit_configs;
1172   char path[256];
1173   char remote_str[256];
1174
1175   snprintf(remote_str, sizeof(remote_str), "%s:%d", target, port);
1176
1177   snprintf(path, sizeof(path),
1178            "//noits//noit[@address=\"%s\" and @port=\"%d\"]", target, port);
1179   noit_configs = noit_conf_get_sections(NULL, path, &cnt);
1180   for(i=0; i<cnt; i++) {
1181     char expected_cn[256];
1182     if(noit_conf_get_stringbuf(noit_configs[i], "self::node()/config/cn",
1183                                expected_cn, sizeof(expected_cn))) {
1184       pthread_mutex_lock(&noit_ip_by_cn_lock);
1185       noit_hash_delete(&noit_ip_by_cn, expected_cn, strlen(expected_cn),
1186                        free, free);
1187       pthread_mutex_unlock(&noit_ip_by_cn_lock);
1188     }
1189     xmlUnlinkNode(noit_configs[i]);
1190     xmlFreeNode(noit_configs[i]);
1191     n = 0;
1192   }
1193   free(noit_configs);
1194
1195   pthread_mutex_lock(&noits_lock);
1196   ctx = malloc(sizeof(*ctx) * noits.size);
1197   while(noit_hash_next(&noits, &iter, (const char **)&key_id, &klen,
1198                        &vconn)) {
1199     if(!strcmp(((noit_connection_ctx_t *)vconn)->remote_str, remote_str)) {
1200       ctx[n] = (noit_connection_ctx_t *)vconn;
1201       noit_atomic_inc32(&ctx[n]->refcnt);
1202       n++;
1203     }
1204   }
1205   pthread_mutex_unlock(&noits_lock);
1206   for(i=0; i<n; i++) {
1207     noit_connection_ctx_dealloc(ctx[i]); /* once for the record */
1208     noit_connection_ctx_deref(ctx[i]);   /* once for the aboce inc32 */
1209   }
1210   free(ctx);
1211   return n;
1212 }
1213 static int
1214 rest_set_noit(noit_http_rest_closure_t *restc,
1215               int npats, char **pats) {
1216   void *vcn;
1217   const char *cn = NULL;
1218   noit_http_session_ctx *ctx = restc->http_ctx;
1219   unsigned short port = 43191;
1220   if(npats < 1 || npats > 2)
1221     noit_http_response_server_error(ctx, "text/xml");
1222   if(npats == 2) port = atoi(pats[1]);
1223   noit_http_process_querystring(&ctx->req);
1224   if(noit_hash_retrieve(&ctx->req.querystring, "cn", 2, &vcn))
1225     cn = vcn;
1226   if(stratcon_add_noit(pats[0], port, cn) >= 0)
1227     noit_http_response_ok(ctx, "text/xml");
1228   else
1229     noit_http_response_standard(ctx, 409, "EXISTS", "text/xml");
1230   if(noit_conf_write_file(NULL) != 0)
1231     noitL(noit_error, "local config write failed\n");
1232   noit_conf_mark_changed();
1233   noit_http_response_end(ctx);
1234   return 0;
1235 }
1236 static int
1237 rest_delete_noit(noit_http_rest_closure_t *restc,
1238                  int npats, char **pats) {
1239   noit_http_session_ctx *ctx = restc->http_ctx;
1240   unsigned short port = 43191;
1241   if(npats < 1 || npats > 2)
1242     noit_http_response_server_error(ctx, "text/xml");
1243   if(npats == 2) port = atoi(pats[1]);
1244   if(stratcon_remove_noit(pats[0], port) >= 0)
1245     noit_http_response_ok(ctx, "text/xml");
1246   else
1247     noit_http_response_not_found(ctx, "text/xml");
1248   if(noit_conf_write_file(NULL) != 0)
1249     noitL(noit_error, "local config write failed\n");
1250   noit_conf_mark_changed();
1251   noit_http_response_end(ctx);
1252   return 0;
1253 }
1254 static int
1255 stratcon_console_conf_noits(noit_console_closure_t ncct,
1256                             int argc, char **argv,
1257                             noit_console_state_t *dstate,
1258                             void *closure) {
1259   char *cp, target[128];
1260   unsigned short port = 43191;
1261   int adding = (int)(vpsized_int)closure;
1262   if(argc != 1)
1263     return -1;
1264
1265   cp = strchr(argv[0], ':');
1266   if(cp) {
1267     strlcpy(target, argv[0], MIN(sizeof(target), cp-argv[0]+1));
1268     port = atoi(cp+1);
1269   }
1270   else strlcpy(target, argv[0], sizeof(target));
1271   if(adding) {
1272     if(stratcon_add_noit(target, port, NULL) >= 0) {
1273       nc_printf(ncct, "Added noit at %s:%d\n", target, port);
1274     }
1275     else {
1276       nc_printf(ncct, "Failed to add noit at %s:%d\n", target, port);
1277     }
1278   }
1279   else {
1280     if(stratcon_remove_noit(target, port) >= 0) {
1281       nc_printf(ncct, "Removed noit at %s:%d\n", target, port);
1282     }
1283     else {
1284       nc_printf(ncct, "Failed to remove noit at %s:%d\n", target, port);
1285     }
1286   }
1287   return 0;
1288 }
1289
1290 static void
1291 register_console_streamer_commands() {
1292   noit_console_state_t *tl;
1293   cmd_info_t *showcmd, *confcmd, *conftcmd, *conftnocmd;
1294
1295   tl = noit_console_state_initial();
1296   showcmd = noit_console_state_get_cmd(tl, "show");
1297   assert(showcmd && showcmd->dstate);
1298   confcmd = noit_console_state_get_cmd(tl, "configure");
1299   conftcmd = noit_console_state_get_cmd(confcmd->dstate, "terminal");
1300   conftnocmd = noit_console_state_get_cmd(conftcmd->dstate, "no");
1301
1302   noit_console_state_add_cmd(conftcmd->dstate,
1303     NCSCMD("noit", stratcon_console_conf_noits, NULL, NULL, (void *)1));
1304   noit_console_state_add_cmd(conftnocmd->dstate,
1305     NCSCMD("noit", stratcon_console_conf_noits, NULL, NULL, (void *)0));
1306
1307   noit_console_state_add_cmd(showcmd->dstate,
1308     NCSCMD("noits", stratcon_console_show_noits, NULL, NULL, NULL));
1309 }
1310
1311 void
1312 stratcon_jlog_streamer_init(const char *toplevel) {
1313   pthread_mutex_init(&noits_lock, NULL);
1314   pthread_mutex_init(&noit_ip_by_cn_lock, NULL);
1315   eventer_name_callback("noit_connection_reinitiate",
1316                         noit_connection_reinitiate);
1317   eventer_name_callback("stratcon_jlog_recv_handler",
1318                         stratcon_jlog_recv_handler);
1319   eventer_name_callback("noit_connection_ssl_upgrade",
1320                         noit_connection_ssl_upgrade);
1321   eventer_name_callback("noit_connection_complete_connect",
1322                         noit_connection_complete_connect);
1323   eventer_name_callback("noit_connection_session_timeout",
1324                         noit_connection_session_timeout);
1325   register_console_streamer_commands();
1326   stratcon_jlog_streamer_reload(toplevel);
1327   stratcon_streamer_connection(toplevel, "", NULL, NULL, NULL, NULL);
1328   assert(noit_http_rest_register_auth(
1329     "GET", "/noits/", "^show$", rest_show_noits,
1330              noit_http_rest_client_cert_auth
1331   ) == 0);
1332   assert(noit_http_rest_register_auth(
1333     "PUT", "/noits/", "^set/([^/:]+)$", rest_set_noit,
1334              noit_http_rest_client_cert_auth
1335   ) == 0);
1336   assert(noit_http_rest_register_auth(
1337     "PUT", "/noits/", "^set/([^/:]+):(\\d+)$", rest_set_noit,
1338              noit_http_rest_client_cert_auth
1339   ) == 0);
1340   assert(noit_http_rest_register_auth(
1341     "DELETE", "/noits/", "^delete/([^/:]+)$", rest_delete_noit,
1342              noit_http_rest_client_cert_auth
1343   ) == 0);
1344   assert(noit_http_rest_register_auth(
1345     "DELETE", "/noits/", "^delete/([^/:]+):(\\d+)$", rest_delete_noit,
1346              noit_http_rest_client_cert_auth
1347   ) == 0);
1348 }
1349
Note: See TracBrowser for help on using the browser.