1 /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <errno.h>
7 #include <poll.h>
8 #include <ctype.h>
9
10 #include "memcached.h"
11 #include "bipbuffer.h"
12
13 #ifdef LOGGER_DEBUG
14 #define L_DEBUG(...) \
15 do { \
16 fprintf(stderr, __VA_ARGS__); \
17 } while (0)
18 #else
19 #define L_DEBUG(...)
20 #endif
21
22
23 /* TODO: put this in a struct and ditch the global vars. */
24 static logger *logger_stack_head = NULL;
25 static logger *logger_stack_tail = NULL;
26 static unsigned int logger_count = 0;
27 static volatile int do_run_logger_thread = 1;
28 static pthread_t logger_tid;
29 pthread_mutex_t logger_stack_lock = PTHREAD_MUTEX_INITIALIZER;
30
31 pthread_key_t logger_key;
32
33 #if !defined(HAVE_GCC_64ATOMICS) && !defined(__sun)
34 pthread_mutex_t logger_atomics_mutex = PTHREAD_MUTEX_INITIALIZER;
35 #endif
36
37 #define WATCHER_LIMIT 20
38 logger_watcher *watchers[20];
39 struct pollfd watchers_pollfds[20];
40 int watcher_count = 0;
41
42 static char *logger_uriencode_map[256];
43 static char logger_uriencode_str[768];
44
45 /* Should this go somewhere else? */
46 static const entry_details default_entries[] = {
47 [LOGGER_ASCII_CMD] = {LOGGER_TEXT_ENTRY, 512, LOG_RAWCMDS, "<%d %s"},
48 [LOGGER_EVICTION] = {LOGGER_EVICTION_ENTRY, 512, LOG_EVICTIONS, NULL},
49 [LOGGER_ITEM_GET] = {LOGGER_ITEM_GET_ENTRY, 512, LOG_FETCHERS, NULL},
50 [LOGGER_ITEM_STORE] = {LOGGER_ITEM_STORE_ENTRY, 512, LOG_MUTATIONS, NULL}
51 };
52
53 #define WATCHER_ALL -1
54 static int logger_thread_poll_watchers(int force_poll, int watcher);
55
56 /*************************
57 * Util functions shared between bg thread and workers
58 *************************/
59
logger_uriencode_init(void)60 static void logger_uriencode_init(void) {
61 int x;
62 char *str = logger_uriencode_str;
63 for (x = 0; x < 256; x++) {
64 if (isalnum(x) || x == '-' || x == '.' || x == '_' || x == '~') {
65 logger_uriencode_map[x] = NULL;
66 } else {
67 snprintf(str, 4, "%%%02X", x);
68 logger_uriencode_map[x] = str;
69 str += 3; /* lobbing off the \0 is fine */
70 }
71 }
72 }
73
logger_uriencode(const char * src,char * dst,const size_t srclen,const size_t dstlen)74 static bool logger_uriencode(const char *src, char *dst, const size_t srclen, const size_t dstlen) {
75 int x;
76 size_t d = 0;
77 for (x = 0; x < srclen; x++) {
78 if (d + 4 >= dstlen)
79 return false;
80 if (logger_uriencode_map[(unsigned char) src[x]] != NULL) {
81 memcpy(&dst[d], logger_uriencode_map[(unsigned char) src[x]], 3);
82 d += 3;
83 } else {
84 dst[d] = src[x];
85 d++;
86 }
87 }
88 dst[d] = '\0';
89 return true;
90 }
91
92 /* Logger GID's can be used by watchers to put logs back into strict order
93 */
logger_get_gid(void)94 static uint64_t logger_get_gid(void) {
95 static uint64_t logger_gid = 0;
96 #ifdef HAVE_GCC_64ATOMICS
97 return __sync_add_and_fetch(&logger_gid, 1);
98 #elif defined(__sun)
99 return atomic_inc_64_nv(&logger_gid);
100 #else
101 mutex_lock(&logger_atomics_mutex);
102 uint64_t res = ++logger_gid;
103 mutex_unlock(&logger_atomics_mutex);
104 return res;
105 #endif
106 }
107
108 /* TODO: genericize lists. would be nice to import queue.h if the impact is
109 * studied... otherwise can just write a local one.
110 */
111 /* Add to the list of threads with a logger object */
logger_link_q(logger * l)112 static void logger_link_q(logger *l) {
113 pthread_mutex_lock(&logger_stack_lock);
114 assert(l != logger_stack_head);
115
116 l->prev = 0;
117 l->next = logger_stack_head;
118 if (l->next) l->next->prev = l;
119 logger_stack_head = l;
120 if (logger_stack_tail == 0) logger_stack_tail = l;
121 logger_count++;
122 pthread_mutex_unlock(&logger_stack_lock);
123 return;
124 }
125
126 /* Remove from the list of threads with a logger object */
127 /*static void logger_unlink_q(logger *l) {
128 pthread_mutex_lock(&logger_stack_lock);
129 if (logger_stack_head == l) {
130 assert(l->prev == 0);
131 logger_stack_head = l->next;
132 }
133 if (logger_stack_tail == l) {
134 assert(l->next == 0);
135 logger_stack_tail = l->prev;
136 }
137 assert(l->next != l);
138 assert(l->prev != l);
139
140 if (l->next) l->next->prev = l->prev;
141 if (l->prev) l->prev->next = l->next;
142 logger_count--;
143 pthread_mutex_unlock(&logger_stack_lock);
144 return;
145 }*/
146
147 /* Called with logger stack locked.
148 * Iterates over every watcher collecting enabled flags.
149 */
logger_set_flags(void)150 static void logger_set_flags(void) {
151 logger *l = NULL;
152 int x = 0;
153 uint16_t f = 0; /* logger eflags */
154
155 for (x = 0; x < WATCHER_LIMIT; x++) {
156 logger_watcher *w = watchers[x];
157 if (w == NULL)
158 continue;
159
160 f |= w->eflags;
161 }
162 for (l = logger_stack_head; l != NULL; l=l->next) {
163 pthread_mutex_lock(&l->mutex);
164 l->eflags = f;
165 pthread_mutex_unlock(&l->mutex);
166 }
167 return;
168 }
169
170 /*************************
171 * Logger background thread functions. Aggregates per-worker buffers and
172 * writes to any watchers.
173 *************************/
174
175 #define LOGGER_PARSE_SCRATCH 4096
176
_logger_thread_parse_ise(logentry * e,char * scratch)177 static int _logger_thread_parse_ise(logentry *e, char *scratch) {
178 int total;
179 const char *cmd = "na";
180 char keybuf[KEY_MAX_LENGTH * 3 + 1];
181 struct logentry_item_store *le = (struct logentry_item_store *) e->data;
182 const char * const status_map[] = {
183 "stored", "exists", "not_found", "too_large", "no_memory" };
184 const char * const cmd_map[] = {
185 "add", "set", "replace", "append", "prepend", "cas" };
186
187 if (le->cmd <= 5)
188 cmd = cmd_map[le->cmd];
189
190 logger_uriencode(le->key, keybuf, le->nkey, LOGGER_PARSE_SCRATCH);
191 total = snprintf(scratch, LOGGER_PARSE_SCRATCH,
192 "ts=%d.%d gid=%llu type=item_store key=%s status=%s cmd=%s\n",
193 (int)e->tv.tv_sec, (int)e->tv.tv_usec, (unsigned long long) e->gid,
194 keybuf, status_map[le->status], cmd);
195 return total;
196 }
197
_logger_thread_parse_ige(logentry * e,char * scratch)198 static int _logger_thread_parse_ige(logentry *e, char *scratch) {
199 int total;
200 struct logentry_item_get *le = (struct logentry_item_get *) e->data;
201 char keybuf[KEY_MAX_LENGTH * 3 + 1];
202 const char * const was_found_map[] = {
203 "not_found", "found", "flushed", "expired" };
204
205 logger_uriencode(le->key, keybuf, le->nkey, LOGGER_PARSE_SCRATCH);
206 total = snprintf(scratch, LOGGER_PARSE_SCRATCH,
207 "ts=%d.%d gid=%llu type=item_get key=%s status=%s\n",
208 (int)e->tv.tv_sec, (int)e->tv.tv_usec, (unsigned long long) e->gid,
209 keybuf, was_found_map[le->was_found]);
210 return total;
211 }
212
_logger_thread_parse_ee(logentry * e,char * scratch)213 static int _logger_thread_parse_ee(logentry *e, char *scratch) {
214 int total;
215 char keybuf[KEY_MAX_LENGTH * 3 + 1];
216 struct logentry_eviction *le = (struct logentry_eviction *) e->data;
217 logger_uriencode(le->key, keybuf, le->nkey, LOGGER_PARSE_SCRATCH);
218 total = snprintf(scratch, LOGGER_PARSE_SCRATCH,
219 "ts=%d.%d gid=%llu type=eviction key=%s fetch=%s ttl=%lld la=%d\n",
220 (int)e->tv.tv_sec, (int)e->tv.tv_usec, (unsigned long long) e->gid,
221 keybuf, (le->it_flags & ITEM_FETCHED) ? "yes" : "no",
222 (long long int)le->exptime, le->latime);
223
224 return total;
225 }
226
227 /* Completes rendering of log line. */
logger_thread_parse_entry(logentry * e,struct logger_stats * ls,char * scratch,int * scratch_len)228 static enum logger_parse_entry_ret logger_thread_parse_entry(logentry *e, struct logger_stats *ls,
229 char *scratch, int *scratch_len) {
230 int total = 0;
231
232 switch (e->event) {
233 case LOGGER_TEXT_ENTRY:
234 total = snprintf(scratch, LOGGER_PARSE_SCRATCH, "ts=%d.%d gid=%llu %s\n",
235 (int)e->tv.tv_sec, (int)e->tv.tv_usec,
236 (unsigned long long) e->gid, (char *) e->data);
237 break;
238 case LOGGER_EVICTION_ENTRY:
239 total = _logger_thread_parse_ee(e, scratch);
240 break;
241 case LOGGER_ITEM_GET_ENTRY:
242 total = _logger_thread_parse_ige(e, scratch);
243 break;
244 case LOGGER_ITEM_STORE_ENTRY:
245 total = _logger_thread_parse_ise(e, scratch);
246 break;
247
248 }
249
250 if (total >= LOGGER_PARSE_SCRATCH || total <= 0) {
251 L_DEBUG("LOGGER: Failed to flatten log entry!\n");
252 return LOGGER_PARSE_ENTRY_FAILED;
253 } else {
254 *scratch_len = total + 1;
255 }
256
257 return LOGGER_PARSE_ENTRY_OK;
258 }
259
260 /* Writes flattened entry to available watchers */
logger_thread_write_entry(logentry * e,struct logger_stats * ls,char * scratch,int scratch_len)261 static void logger_thread_write_entry(logentry *e, struct logger_stats *ls,
262 char *scratch, int scratch_len) {
263 int x, total;
264 /* Write the line into available watchers with matching flags */
265 for (x = 0; x < WATCHER_LIMIT; x++) {
266 logger_watcher *w = watchers[x];
267 char *skip_scr = NULL;
268 if (w == NULL || (e->eflags & w->eflags) == 0)
269 continue;
270
271 /* Avoid poll()'ing constantly when buffer is full by resetting a
272 * flag periodically.
273 */
274 while (!w->failed_flush &&
275 (skip_scr = (char *) bipbuf_request(w->buf, scratch_len + 128)) == NULL) {
276 if (logger_thread_poll_watchers(0, x) <= 0) {
277 L_DEBUG("LOGGER: Watcher had no free space for line of size (%d)\n", line_size);
278 w->failed_flush = true;
279 }
280 }
281
282 if (w->failed_flush) {
283 L_DEBUG("LOGGER: Fast skipped for watcher [%d] due to failed_flush\n", w->sfd);
284 w->skipped++;
285 ls->watcher_skipped++;
286 continue;
287 }
288
289 if (w->skipped > 0) {
290 total = snprintf(skip_scr, 128, "skipped=%llu\n", (unsigned long long) w->skipped);
291 if (total >= 128 || total <= 0) {
292 L_DEBUG("LOGGER: Failed to flatten skipped message into watcher [%d]\n", w->sfd);
293 w->skipped++;
294 ls->watcher_skipped++;
295 continue;
296 }
297 bipbuf_push(w->buf, total + 1);
298 w->skipped = 0;
299 }
300 /* Can't fail because bipbuf_request succeeded. */
301 bipbuf_offer(w->buf, (unsigned char *) scratch, scratch_len);
302 ls->watcher_sent++;
303 }
304 }
305
306 /* Called with logger stack locked.
307 * Releases every chunk associated with a watcher and closes the connection.
308 * We can't presently send a connection back to the worker for further
309 * processing.
310 */
logger_thread_close_watcher(logger_watcher * w)311 static void logger_thread_close_watcher(logger_watcher *w) {
312 L_DEBUG("LOGGER: Closing dead watcher\n");
313 watchers[w->id] = NULL;
314 sidethread_conn_close(w->c);
315 watcher_count--;
316 bipbuf_free(w->buf);
317 free(w);
318 logger_set_flags();
319 }
320
321 /* Reads a particular worker thread's available bipbuf bytes. Parses each log
322 * entry into the watcher buffers.
323 */
logger_thread_read(logger * l,struct logger_stats * ls)324 static int logger_thread_read(logger *l, struct logger_stats *ls) {
325 unsigned int size;
326 unsigned int pos = 0;
327 unsigned char *data;
328 char scratch[LOGGER_PARSE_SCRATCH];
329 logentry *e;
330 pthread_mutex_lock(&l->mutex);
331 data = bipbuf_peek_all(l->buf, &size);
332 pthread_mutex_unlock(&l->mutex);
333
334 if (data == NULL) {
335 return 0;
336 }
337 L_DEBUG("LOGGER: Got %d bytes from bipbuffer\n", size);
338
339 /* parse buffer */
340 while (pos < size && watcher_count > 0) {
341 enum logger_parse_entry_ret ret;
342 int scratch_len = 0;
343 e = (logentry *) (data + pos);
344 ret = logger_thread_parse_entry(e, ls, scratch, &scratch_len);
345 if (ret != LOGGER_PARSE_ENTRY_OK) {
346 /* TODO: stats counter */
347 fprintf(stderr, "LOGGER: Failed to parse log entry\n");
348 } else {
349 logger_thread_write_entry(e, ls, scratch, scratch_len);
350 }
351 pos += sizeof(logentry) + e->size;
352 }
353 assert(pos <= size);
354
355 pthread_mutex_lock(&l->mutex);
356 data = bipbuf_poll(l->buf, size);
357 ls->worker_written += l->written;
358 ls->worker_dropped += l->dropped;
359 l->written = 0;
360 l->dropped = 0;
361 pthread_mutex_unlock(&l->mutex);
362 if (data == NULL) {
363 fprintf(stderr, "LOGGER: unexpectedly couldn't advance buf pointer\n");
364 assert(0);
365 }
366 return size; /* maybe the count of objects iterated? */
367 }
368
369 /* Since the event loop code isn't reusable without a refactor, and we have a
370 * limited number of potential watchers, we run our own poll loop.
371 * This calls poll() unnecessarily during write flushes, should be possible to
372 * micro-optimize later.
373 *
374 * This flushes buffers attached to watchers, iterating through the bytes set
375 * to each worker. Also checks for readability in case client connection was
376 * closed.
377 *
378 * Allows a specific watcher to be flushed (if buf full)
379 */
logger_thread_poll_watchers(int force_poll,int watcher)380 static int logger_thread_poll_watchers(int force_poll, int watcher) {
381 int x;
382 int nfd = 0;
383 unsigned char *data;
384 unsigned int data_size = 0;
385 int flushed = 0;
386
387 for (x = 0; x < WATCHER_LIMIT; x++) {
388 logger_watcher *w = watchers[x];
389 if (w == NULL || (watcher != WATCHER_ALL && x != watcher))
390 continue;
391
392 data = bipbuf_peek_all(w->buf, &data_size);
393 if (data != NULL) {
394 watchers_pollfds[nfd].fd = w->sfd;
395 watchers_pollfds[nfd].events = POLLOUT;
396 nfd++;
397 } else if (force_poll) {
398 watchers_pollfds[nfd].fd = w->sfd;
399 watchers_pollfds[nfd].events = POLLIN;
400 nfd++;
401 }
402 /* This gets set after a call to poll, and should be used to gate on
403 * calling poll again.
404 */
405 w->failed_flush = false;
406 }
407
408 if (nfd == 0)
409 return 0;
410
411 //L_DEBUG("LOGGER: calling poll() [data_size: %d]\n", data_size);
412 int ret = poll(watchers_pollfds, nfd, 0);
413
414 if (ret < 0) {
415 perror("something failed with logger thread watcher fd polling");
416 return -1;
417 }
418
419 nfd = 0;
420 for (x = 0; x < WATCHER_LIMIT; x++) {
421 logger_watcher *w = watchers[x];
422 if (w == NULL)
423 continue;
424
425 data_size = 0;
426 /* Early detection of a disconnect. Otherwise we have to wait until
427 * the next write
428 */
429 if (watchers_pollfds[nfd].revents & POLLIN) {
430 char buf[1];
431 int res = read(w->sfd, buf, 1);
432 if (res == 0 || (res == -1 && (errno != EAGAIN && errno != EWOULDBLOCK))) {
433 logger_thread_close_watcher(w);
434 nfd++;
435 continue;
436 }
437 }
438 if ((data = bipbuf_peek_all(w->buf, &data_size)) != NULL) {
439 if (watchers_pollfds[nfd].revents & (POLLHUP|POLLERR)) {
440 L_DEBUG("LOGGER: watcher closed during poll() call\n");
441 logger_thread_close_watcher(w);
442 } else if (watchers_pollfds[nfd].revents & POLLOUT) {
443 int total = 0;
444
445 /* We can write a bit. */
446 switch (w->t) {
447 case LOGGER_WATCHER_STDERR:
448 total = fwrite(data, 1, data_size, stderr);
449 break;
450 case LOGGER_WATCHER_CLIENT:
451 total = write(w->sfd, data, data_size);
452 break;
453 }
454
455 L_DEBUG("LOGGER: poll() wrote %d to %d (data_size: %d) (bipbuf_used: %d)\n", total, w->sfd,
456 data_size, bipbuf_used(w->buf));
457 if (total == -1) {
458 if (errno != EAGAIN && errno != EWOULDBLOCK) {
459 logger_thread_close_watcher(w);
460 }
461 L_DEBUG("LOGGER: watcher hit EAGAIN\n");
462 } else if (total == 0) {
463 logger_thread_close_watcher(w);
464 } else {
465 bipbuf_poll(w->buf, total);
466 flushed += total;
467 }
468 }
469 }
470 nfd++;
471 }
472 return flushed;
473 }
474
logger_thread_sum_stats(struct logger_stats * ls)475 static void logger_thread_sum_stats(struct logger_stats *ls) {
476 STATS_LOCK();
477 stats.log_worker_dropped += ls->worker_dropped;
478 stats.log_worker_written += ls->worker_written;
479 stats.log_watcher_skipped += ls->watcher_skipped;
480 stats.log_watcher_sent += ls->watcher_sent;
481 STATS_UNLOCK();
482 }
483
484 #define MAX_LOGGER_SLEEP 100000
485 #define MIN_LOGGER_SLEEP 0
486
487 /* Primary logger thread routine */
logger_thread(void * arg)488 static void *logger_thread(void *arg) {
489 useconds_t to_sleep = MIN_LOGGER_SLEEP;
490 L_DEBUG("LOGGER: Starting logger thread\n");
491 while (do_run_logger_thread) {
492 int found_logs = 0;
493 logger *l;
494 struct logger_stats ls;
495 memset(&ls, 0, sizeof(struct logger_stats));
496 if (to_sleep)
497 usleep(to_sleep);
498
499 /* Call function to iterate each logger. */
500 pthread_mutex_lock(&logger_stack_lock);
501 for (l = logger_stack_head; l != NULL; l=l->next) {
502 /* lock logger, call function to manipulate it */
503 found_logs += logger_thread_read(l, &ls);
504 }
505
506 logger_thread_poll_watchers(1, WATCHER_ALL);
507 pthread_mutex_unlock(&logger_stack_lock);
508
509 /* TODO: abstract into a function and share with lru_crawler */
510 if (!found_logs) {
511 if (to_sleep < MAX_LOGGER_SLEEP)
512 to_sleep += 50;
513 } else {
514 to_sleep /= 2;
515 if (to_sleep < 50)
516 to_sleep = MIN_LOGGER_SLEEP;
517 }
518 logger_thread_sum_stats(&ls);
519 }
520
521 return NULL;
522 }
523
start_logger_thread(void)524 static int start_logger_thread(void) {
525 int ret;
526 do_run_logger_thread = 1;
527 if ((ret = pthread_create(&logger_tid, NULL,
528 logger_thread, NULL)) != 0) {
529 fprintf(stderr, "Can't start logger thread: %s\n", strerror(ret));
530 return -1;
531 }
532 return 0;
533 }
534
535 // future.
536 /*static int stop_logger_thread(void) {
537 do_run_logger_thread = 0;
538 pthread_join(logger_tid, NULL);
539 return 0;
540 }*/
541
542 /*************************
543 * Public functions for submitting logs and starting loggers from workers.
544 *************************/
545
546 /* Global logger thread start/init */
logger_init(void)547 void logger_init(void) {
548 /* TODO: auto destructor when threads exit */
549 /* TODO: error handling */
550
551 /* init stack for iterating loggers */
552 logger_stack_head = 0;
553 logger_stack_tail = 0;
554 pthread_key_create(&logger_key, NULL);
555 logger_uriencode_init();
556
557 if (start_logger_thread() != 0) {
558 abort();
559 }
560
561 /* This can be removed once the global stats initializer is improved */
562 STATS_LOCK();
563 stats.log_worker_dropped = 0;
564 stats.log_worker_written = 0;
565 stats.log_watcher_skipped = 0;
566 stats.log_watcher_sent = 0;
567 STATS_UNLOCK();
568 /* This is what adding a STDERR watcher looks like. should replace old
569 * "verbose" settings. */
570 //logger_add_watcher(NULL, 0);
571 return;
572 }
573
574 /* called *from* the thread using a logger.
575 * initializes the per-thread bipbuf, links it into the list of loggers
576 */
logger_create(void)577 logger *logger_create(void) {
578 L_DEBUG("LOGGER: Creating and linking new logger instance\n");
579 logger *l = calloc(1, sizeof(logger));
580 if (l == NULL) {
581 return NULL;
582 }
583
584 l->buf = bipbuf_new(settings.logger_buf_size);
585 if (l->buf == NULL) {
586 free(l);
587 return NULL;
588 }
589
590 l->entry_map = default_entries;
591
592 pthread_mutex_init(&l->mutex, NULL);
593 pthread_setspecific(logger_key, l);
594
595 /* add to list of loggers */
596 logger_link_q(l);
597 return l;
598 }
599
600 /* helpers for logger_log */
601
_logger_log_evictions(logentry * e,item * it)602 static void _logger_log_evictions(logentry *e, item *it) {
603 struct logentry_eviction *le = (struct logentry_eviction *) e->data;
604 le->exptime = (it->exptime > 0) ? (long long int)(it->exptime - current_time) : (long long int) -1;
605 le->latime = current_time - it->time;
606 le->it_flags = it->it_flags;
607 le->nkey = it->nkey;
608 memcpy(le->key, ITEM_key(it), it->nkey);
609 e->size = sizeof(struct logentry_eviction) + le->nkey;
610 }
611
612 /* 0 == nf, 1 == found. 2 == flushed. 3 == expired.
613 * might be useful to store/print the flags an item has?
614 * could also collapse this and above code into an "item status" struct. wait
615 * for more endpoints to be written before making it generic, though.
616 * TODO: This and below should track and reprint the client fd.
617 */
_logger_log_item_get(logentry * e,const int was_found,const char * key,const int nkey)618 static void _logger_log_item_get(logentry *e, const int was_found, const char *key, const int nkey) {
619 struct logentry_item_get *le = (struct logentry_item_get *) e->data;
620 le->was_found = was_found;
621 le->nkey = nkey;
622 memcpy(le->key, key, nkey);
623 e->size = sizeof(struct logentry_item_get) + nkey;
624 }
625
_logger_log_item_store(logentry * e,const enum store_item_type status,const int comm,char * key,const int nkey)626 static void _logger_log_item_store(logentry *e, const enum store_item_type status,
627 const int comm, char *key, const int nkey) {
628 struct logentry_item_store *le = (struct logentry_item_store *) e->data;
629 le->status = status;
630 le->cmd = comm;
631 le->nkey = nkey;
632 memcpy(le->key, key, nkey);
633 e->size = sizeof(struct logentry_item_store) + nkey;
634 }
635
636 /* Public function for logging an entry.
637 * Tries to encapsulate as much of the formatting as possible to simplify the
638 * caller's code.
639 */
logger_log(logger * l,const enum log_entry_type event,const void * entry,...)640 enum logger_ret_type logger_log(logger *l, const enum log_entry_type event, const void *entry, ...) {
641 bipbuf_t *buf = l->buf;
642 bool nospace = false;
643 va_list ap;
644 int total = 0;
645 logentry *e;
646
647 const entry_details *d = &l->entry_map[event];
648 int reqlen = d->reqlen;
649
650 pthread_mutex_lock(&l->mutex);
651 /* Request a maximum length of data to write to */
652 e = (logentry *) bipbuf_request(buf, (sizeof(logentry) + reqlen));
653 if (e == NULL) {
654 pthread_mutex_unlock(&l->mutex);
655 l->dropped++;
656 return LOGGER_RET_NOSPACE;
657 }
658 e->gid = logger_get_gid();
659 e->event = d->subtype;
660 /* TODO: Could pass this down as an argument now that we're using
661 * LOGGER_LOG() macro.
662 */
663 e->eflags = d->eflags;
664 /* Noting time isn't optional. A feature may be added to avoid rendering
665 * time and/or gid to a logger.
666 */
667 gettimeofday(&e->tv, NULL);
668
669 switch (d->subtype) {
670 case LOGGER_TEXT_ENTRY:
671 va_start(ap, entry);
672 total = vsnprintf((char *) e->data, reqlen, d->format, ap);
673 va_end(ap);
674 if (total >= reqlen || total <= 0) {
675 fprintf(stderr, "LOGGER: Failed to vsnprintf a text entry: (total) %d\n", total);
676 break;
677 }
678 e->size = total + 1; /* null byte */
679
680 break;
681 case LOGGER_EVICTION_ENTRY:
682 _logger_log_evictions(e, (item *)entry);
683 break;
684 case LOGGER_ITEM_GET_ENTRY:
685 va_start(ap, entry);
686 int was_found = va_arg(ap, int);
687 char *key = va_arg(ap, char *);
688 size_t nkey = va_arg(ap, size_t);
689 _logger_log_item_get(e, was_found, key, nkey);
690 va_end(ap);
691 break;
692 case LOGGER_ITEM_STORE_ENTRY:
693 va_start(ap, entry);
694 enum store_item_type status = va_arg(ap, enum store_item_type);
695 int comm = va_arg(ap, int);
696 char *skey = va_arg(ap, char *);
697 size_t snkey = va_arg(ap, size_t);
698 _logger_log_item_store(e, status, comm, skey, snkey);
699 break;
700 }
701
702 /* Push pointer forward by the actual amount required */
703 if (bipbuf_push(buf, (sizeof(logentry) + e->size)) == 0) {
704 fprintf(stderr, "LOGGER: Failed to bipbuf push a text entry\n");
705 pthread_mutex_unlock(&l->mutex);
706 return LOGGER_RET_ERR;
707 }
708 l->written++;
709 L_DEBUG("LOGGER: Requested %d bytes, wrote %d bytes\n", reqlen, total + 1);
710
711 pthread_mutex_unlock(&l->mutex);
712
713 if (nospace) {
714 return LOGGER_RET_NOSPACE;
715 } else {
716 return LOGGER_RET_OK;
717 }
718 }
719
720 /* Passes a client connection socket from a primary worker thread to the
721 * logger thread. Caller *must* event_del() the client before handing it over.
722 * Presently there's no way to hand the client back to the worker thread.
723 */
logger_add_watcher(void * c,const int sfd,uint16_t f)724 enum logger_add_watcher_ret logger_add_watcher(void *c, const int sfd, uint16_t f) {
725 int x;
726 logger_watcher *w = NULL;
727 pthread_mutex_lock(&logger_stack_lock);
728 if (watcher_count >= WATCHER_LIMIT) {
729 return LOGGER_ADD_WATCHER_TOO_MANY;
730 }
731
732 for (x = 0; x < WATCHER_LIMIT; x++) {
733 if (watchers[x] == NULL)
734 break;
735 }
736
737 w = calloc(1, sizeof(logger_watcher));
738 if (w == NULL) {
739 pthread_mutex_unlock(&logger_stack_lock);
740 return LOGGER_ADD_WATCHER_FAILED;
741 }
742 w->c = c;
743 w->sfd = sfd;
744 if (sfd == 0 && c == NULL) {
745 w->t = LOGGER_WATCHER_STDERR;
746 } else {
747 w->t = LOGGER_WATCHER_CLIENT;
748 }
749 w->id = x;
750 w->eflags = f;
751 w->buf = bipbuf_new(settings.logger_watcher_buf_size);
752 if (w->buf == NULL) {
753 free(w);
754 pthread_mutex_unlock(&logger_stack_lock);
755 return LOGGER_ADD_WATCHER_FAILED;
756 }
757 bipbuf_offer(w->buf, (unsigned char *) "OK\r\n", 4);
758
759 watchers[x] = w;
760 watcher_count++;
761 /* Update what flags the global logs will watch */
762 logger_set_flags();
763
764 pthread_mutex_unlock(&logger_stack_lock);
765 return LOGGER_ADD_WATCHER_OK;
766 }
767