root/src/stratcon_jlog_streamer.c

Revision c07a479ca7158c58ebf6036351e6a4e1191a54e1, 45.1 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 9 years ago)

fixes #256

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