Ditch that symbol table hack. It's not portable.
[beanstalkd.git] / prot.c
bloba8207d23580b95409b71ad6fa9ed4978b896120c
1 /* prot.c - protocol implementation */
3 /* Copyright (C) 2007 Keith Rarick and Philotic Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <unistd.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <sys/resource.h>
25 #include <sys/uio.h>
26 #include <stdarg.h>
27 #include <ctype.h>
29 #include "stat.h"
30 #include "prot.h"
31 #include "pq.h"
32 #include "ms.h"
33 #include "job.h"
34 #include "tube.h"
35 #include "conn.h"
36 #include "util.h"
37 #include "net.h"
38 #include "binlog.h"
39 #include "config.h"
41 /* job body cannot be greater than this many bytes long */
42 size_t job_data_size_limit = JOB_DATA_SIZE_LIMIT_DEFAULT;
44 #define NAME_CHARS \
45 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
46 "abcdefghijklmnopqrstuvwxyz" \
47 "0123456789-+/;.$()"
49 #define CMD_PUT "put "
50 #define CMD_PEEKJOB "peek "
51 #define CMD_PEEK_READY "peek-ready"
52 #define CMD_PEEK_DELAYED "peek-delayed"
53 #define CMD_PEEK_BURIED "peek-buried"
54 #define CMD_RESERVE "reserve"
55 #define CMD_RESERVE_TIMEOUT "reserve-with-timeout "
56 #define CMD_DELETE "delete "
57 #define CMD_RELEASE "release "
58 #define CMD_BURY "bury "
59 #define CMD_KICK "kick "
60 #define CMD_TOUCH "touch "
61 #define CMD_STATS "stats"
62 #define CMD_JOBSTATS "stats-job "
63 #define CMD_USE "use "
64 #define CMD_WATCH "watch "
65 #define CMD_IGNORE "ignore "
66 #define CMD_LIST_TUBES "list-tubes"
67 #define CMD_LIST_TUBE_USED "list-tube-used"
68 #define CMD_LIST_TUBES_WATCHED "list-tubes-watched"
69 #define CMD_STATS_TUBE "stats-tube "
71 #define CONSTSTRLEN(m) (sizeof(m) - 1)
73 #define CMD_PEEK_READY_LEN CONSTSTRLEN(CMD_PEEK_READY)
74 #define CMD_PEEK_DELAYED_LEN CONSTSTRLEN(CMD_PEEK_DELAYED)
75 #define CMD_PEEK_BURIED_LEN CONSTSTRLEN(CMD_PEEK_BURIED)
76 #define CMD_PEEKJOB_LEN CONSTSTRLEN(CMD_PEEKJOB)
77 #define CMD_RESERVE_LEN CONSTSTRLEN(CMD_RESERVE)
78 #define CMD_RESERVE_TIMEOUT_LEN CONSTSTRLEN(CMD_RESERVE_TIMEOUT)
79 #define CMD_DELETE_LEN CONSTSTRLEN(CMD_DELETE)
80 #define CMD_RELEASE_LEN CONSTSTRLEN(CMD_RELEASE)
81 #define CMD_BURY_LEN CONSTSTRLEN(CMD_BURY)
82 #define CMD_KICK_LEN CONSTSTRLEN(CMD_KICK)
83 #define CMD_TOUCH_LEN CONSTSTRLEN(CMD_TOUCH)
84 #define CMD_STATS_LEN CONSTSTRLEN(CMD_STATS)
85 #define CMD_JOBSTATS_LEN CONSTSTRLEN(CMD_JOBSTATS)
86 #define CMD_USE_LEN CONSTSTRLEN(CMD_USE)
87 #define CMD_WATCH_LEN CONSTSTRLEN(CMD_WATCH)
88 #define CMD_IGNORE_LEN CONSTSTRLEN(CMD_IGNORE)
89 #define CMD_LIST_TUBES_LEN CONSTSTRLEN(CMD_LIST_TUBES)
90 #define CMD_LIST_TUBE_USED_LEN CONSTSTRLEN(CMD_LIST_TUBE_USED)
91 #define CMD_LIST_TUBES_WATCHED_LEN CONSTSTRLEN(CMD_LIST_TUBES_WATCHED)
92 #define CMD_STATS_TUBE_LEN CONSTSTRLEN(CMD_STATS_TUBE)
94 #define MSG_FOUND "FOUND"
95 #define MSG_NOTFOUND "NOT_FOUND\r\n"
96 #define MSG_RESERVED "RESERVED"
97 #define MSG_DEADLINE_SOON "DEADLINE_SOON\r\n"
98 #define MSG_TIMED_OUT "TIMED_OUT\r\n"
99 #define MSG_DELETED "DELETED\r\n"
100 #define MSG_RELEASED "RELEASED\r\n"
101 #define MSG_BURIED "BURIED\r\n"
102 #define MSG_TOUCHED "TOUCHED\r\n"
103 #define MSG_BURIED_FMT "BURIED %llu\r\n"
104 #define MSG_INSERTED_FMT "INSERTED %llu\r\n"
105 #define MSG_NOT_IGNORED "NOT_IGNORED\r\n"
107 #define MSG_NOTFOUND_LEN CONSTSTRLEN(MSG_NOTFOUND)
108 #define MSG_DELETED_LEN CONSTSTRLEN(MSG_DELETED)
109 #define MSG_TOUCHED_LEN CONSTSTRLEN(MSG_TOUCHED)
110 #define MSG_RELEASED_LEN CONSTSTRLEN(MSG_RELEASED)
111 #define MSG_BURIED_LEN CONSTSTRLEN(MSG_BURIED)
112 #define MSG_NOT_IGNORED_LEN CONSTSTRLEN(MSG_NOT_IGNORED)
114 #define MSG_OUT_OF_MEMORY "OUT_OF_MEMORY\r\n"
115 #define MSG_INTERNAL_ERROR "INTERNAL_ERROR\r\n"
116 #define MSG_DRAINING "DRAINING\r\n"
117 #define MSG_BAD_FORMAT "BAD_FORMAT\r\n"
118 #define MSG_UNKNOWN_COMMAND "UNKNOWN_COMMAND\r\n"
119 #define MSG_EXPECTED_CRLF "EXPECTED_CRLF\r\n"
120 #define MSG_JOB_TOO_BIG "JOB_TOO_BIG\r\n"
122 #define STATE_WANTCOMMAND 0
123 #define STATE_WANTDATA 1
124 #define STATE_SENDJOB 2
125 #define STATE_SENDWORD 3
126 #define STATE_WAIT 4
127 #define STATE_BITBUCKET 5
129 #define OP_UNKNOWN 0
130 #define OP_PUT 1
131 #define OP_PEEKJOB 2
132 #define OP_RESERVE 3
133 #define OP_DELETE 4
134 #define OP_RELEASE 5
135 #define OP_BURY 6
136 #define OP_KICK 7
137 #define OP_STATS 8
138 #define OP_JOBSTATS 9
139 #define OP_PEEK_BURIED 10
140 #define OP_USE 11
141 #define OP_WATCH 12
142 #define OP_IGNORE 13
143 #define OP_LIST_TUBES 14
144 #define OP_LIST_TUBE_USED 15
145 #define OP_LIST_TUBES_WATCHED 16
146 #define OP_STATS_TUBE 17
147 #define OP_PEEK_READY 18
148 #define OP_PEEK_DELAYED 19
149 #define OP_RESERVE_TIMEOUT 20
150 #define OP_TOUCH 21
151 #define TOTAL_OPS 22
153 #define STATS_FMT "---\n" \
154 "current-jobs-urgent: %u\n" \
155 "current-jobs-ready: %u\n" \
156 "current-jobs-reserved: %u\n" \
157 "current-jobs-delayed: %u\n" \
158 "current-jobs-buried: %u\n" \
159 "cmd-put: %llu\n" \
160 "cmd-peek: %llu\n" \
161 "cmd-peek-ready: %llu\n" \
162 "cmd-peek-delayed: %llu\n" \
163 "cmd-peek-buried: %llu\n" \
164 "cmd-reserve: %llu\n" \
165 "cmd-reserve-with-timeout: %llu\n" \
166 "cmd-delete: %llu\n" \
167 "cmd-release: %llu\n" \
168 "cmd-use: %llu\n" \
169 "cmd-watch: %llu\n" \
170 "cmd-ignore: %llu\n" \
171 "cmd-bury: %llu\n" \
172 "cmd-kick: %llu\n" \
173 "cmd-touch: %llu\n" \
174 "cmd-stats: %llu\n" \
175 "cmd-stats-job: %llu\n" \
176 "cmd-stats-tube: %llu\n" \
177 "cmd-list-tubes: %llu\n" \
178 "cmd-list-tube-used: %llu\n" \
179 "cmd-list-tubes-watched: %llu\n" \
180 "job-timeouts: %llu\n" \
181 "total-jobs: %llu\n" \
182 "max-job-size: %zu\n" \
183 "current-tubes: %zu\n" \
184 "current-connections: %u\n" \
185 "current-producers: %u\n" \
186 "current-workers: %u\n" \
187 "current-waiting: %u\n" \
188 "total-connections: %u\n" \
189 "pid: %ld\n" \
190 "version: %s\n" \
191 "rusage-utime: %d.%06d\n" \
192 "rusage-stime: %d.%06d\n" \
193 "uptime: %u\n" \
194 "binlog-oldest-index: %s\n" \
195 "binlog-current-index: %s\n" \
196 "binlog-max-size: %zu\n" \
197 "\r\n"
199 #define STATS_TUBE_FMT "---\n" \
200 "name: %s\n" \
201 "current-jobs-urgent: %u\n" \
202 "current-jobs-ready: %u\n" \
203 "current-jobs-reserved: %u\n" \
204 "current-jobs-delayed: %u\n" \
205 "current-jobs-buried: %u\n" \
206 "total-jobs: %llu\n" \
207 "current-using: %u\n" \
208 "current-watching: %u\n" \
209 "current-waiting: %u\n" \
210 "\r\n"
212 #define JOB_STATS_FMT "---\n" \
213 "id: %llu\n" \
214 "tube: %s\n" \
215 "state: %s\n" \
216 "pri: %u\n" \
217 "age: %u\n" \
218 "delay: %u\n" \
219 "ttr: %u\n" \
220 "time-left: %u\n" \
221 "timeouts: %u\n" \
222 "releases: %u\n" \
223 "buries: %u\n" \
224 "kicks: %u\n" \
225 "\r\n"
227 /* this number is pretty arbitrary */
228 #define BUCKET_BUF_SIZE 1024
230 static char bucket[BUCKET_BUF_SIZE];
232 static unsigned int ready_ct = 0;
233 static struct stats global_stat = {0, 0, 0, 0, 0};
235 static tube default_tube;
237 static int drain_mode = 0;
238 static time_t start_time;
239 static unsigned long long int op_ct[TOTAL_OPS], timeout_ct = 0;
242 /* Doubly-linked list of connections with at least one reserved job. */
243 static struct conn running = { &running, &running, 0 };
245 #ifdef DEBUG
246 static const char * op_names[] = {
247 "<unknown>",
248 CMD_PUT,
249 CMD_PEEKJOB,
250 CMD_RESERVE,
251 CMD_DELETE,
252 CMD_RELEASE,
253 CMD_BURY,
254 CMD_KICK,
255 CMD_STATS,
256 CMD_JOBSTATS,
257 CMD_PEEK_BURIED,
258 CMD_USE,
259 CMD_WATCH,
260 CMD_IGNORE,
261 CMD_LIST_TUBES,
262 CMD_LIST_TUBE_USED,
263 CMD_LIST_TUBES_WATCHED,
264 CMD_STATS_TUBE,
265 CMD_PEEK_READY,
266 CMD_PEEK_DELAYED,
267 CMD_RESERVE_TIMEOUT,
268 CMD_TOUCH
270 #endif
272 static job remove_buried_job(job j);
274 static int
275 buried_job_p(tube t)
277 return job_list_any_p(&t->buried);
280 static void
281 reply(conn c, const char *line, int len, int state)
283 int r;
285 if (!c) return;
287 r = conn_update_evq(c, EV_WRITE | EV_PERSIST);
288 if (r == -1) return twarnx("conn_update_evq() failed"), conn_close(c);
290 c->reply = line;
291 c->reply_len = len;
292 c->reply_sent = 0;
293 c->state = state;
294 dprintf("sending reply: %.*s", len, line);
297 #define reply_msg(c,m) reply((c),(m),CONSTSTRLEN(m),STATE_SENDWORD)
299 #define reply_serr(c,e) (twarnx("server error: %s",(e)),\
300 reply_msg((c),(e)))
302 static void
303 reply_line(conn c, int state, const char *fmt, ...)
305 int r;
306 va_list ap;
308 va_start(ap, fmt);
309 r = vsnprintf(c->reply_buf, LINE_BUF_SIZE, fmt, ap);
310 va_end(ap);
312 /* Make sure the buffer was big enough. If not, we have a bug. */
313 if (r >= LINE_BUF_SIZE) return reply_serr(c, MSG_INTERNAL_ERROR);
315 return reply(c, c->reply_buf, r, state);
318 static void
319 reply_job(conn c, job j, const char *word)
321 /* tell this connection which job to send */
322 c->out_job = j;
323 c->out_job_sent = 0;
325 return reply_line(c, STATE_SENDJOB, "%s %llu %u\r\n",
326 word, j->id, j->body_size - 2);
329 conn
330 remove_waiting_conn(conn c)
332 tube t;
333 size_t i;
335 if (!conn_waiting(c)) return NULL;
337 c->type &= ~CONN_TYPE_WAITING;
338 global_stat.waiting_ct--;
339 for (i = 0; i < c->watch.used; i++) {
340 t = c->watch.items[i];
341 t->stat.waiting_ct--;
342 ms_remove(&t->waiting, c);
344 return c;
347 static void
348 reserve_job(conn c, job j)
350 j->deadline = time(NULL) + j->ttr;
351 global_stat.reserved_ct++; /* stats */
352 j->tube->stat.reserved_ct++;
353 conn_insert(&running, c);
354 j->state = JOB_STATE_RESERVED;
355 job_insert(&c->reserved_jobs, j);
356 j->reserver = c;
357 if (c->soonest_job && j->deadline < c->soonest_job->deadline) {
358 c->soonest_job = j;
360 return reply_job(c, j, MSG_RESERVED);
363 static job
364 next_eligible_job()
366 tube t;
367 size_t i;
368 job j = NULL, candidate;
370 dprintf("tubes.used = %zu\n", tubes.used);
371 for (i = 0; i < tubes.used; i++) {
372 t = tubes.items[i];
373 dprintf("for %s t->waiting.used=%zu t->ready.used=%d\n",
374 t->name, t->waiting.used, t->ready.used);
375 if (t->waiting.used && t->ready.used) {
376 candidate = pq_peek(&t->ready);
377 if (!j || job_pri_cmp(candidate, j) < 0) j = candidate;
379 dprintf("i = %zu, tubes.used = %zu\n", i, tubes.used);
382 return j;
385 static void
386 process_queue()
388 job j;
390 dprintf("processing queue\n");
391 while ((j = next_eligible_job())) {
392 dprintf("got eligible job %llu in %s\n", j->id, j->tube->name);
393 j = pq_take(&j->tube->ready);
394 ready_ct--;
395 if (j->pri < URGENT_THRESHOLD) {
396 global_stat.urgent_ct--;
397 j->tube->stat.urgent_ct--;
399 reserve_job(remove_waiting_conn(ms_take(&j->tube->waiting)), j);
403 static job
404 delay_q_peek()
406 int i;
407 tube t;
408 job j = NULL, nj;
410 for (i = 0; i < tubes.used; i++) {
411 t = tubes.items[i];
412 nj = pq_peek(&t->delay);
413 if (!nj) continue;
414 if (!j || nj->deadline < j->deadline) j = nj;
417 return j;
420 static void
421 set_main_delay_timeout()
423 job j;
425 set_main_timeout((j = delay_q_peek()) ? j->deadline : 0);
428 static int
429 enqueue_job(job j, unsigned int delay, char update_store)
431 int r;
433 j->reserver = NULL;
434 if (delay) {
435 j->deadline = time(NULL) + delay;
436 r = pq_give(&j->tube->delay, j);
437 if (!r) return 0;
438 j->state = JOB_STATE_DELAYED;
439 set_main_delay_timeout();
440 } else {
441 r = pq_give(&j->tube->ready, j);
442 if (!r) return 0;
443 j->state = JOB_STATE_READY;
444 ready_ct++;
445 if (j->pri < URGENT_THRESHOLD) {
446 global_stat.urgent_ct++;
447 j->tube->stat.urgent_ct++;
451 if (update_store) {
452 r = binlog_write_job(j);
453 if (!r) return -1;
456 process_queue();
457 return 1;
460 static int
461 bury_job(job j, char update_store)
463 size_t z;
465 if (update_store) {
466 z = binlog_reserve_space_update(j);
467 if (!z) return 0;
468 j->reserved_binlog_space += z;
471 job_insert(&j->tube->buried, j);
472 global_stat.buried_ct++;
473 j->tube->stat.buried_ct++;
474 j->state = JOB_STATE_BURIED;
475 j->reserver = NULL;
476 j->bury_ct++;
478 if (update_store) return binlog_write_job(j);
480 return 1;
483 void
484 enqueue_reserved_jobs(conn c)
486 int r;
487 job j;
489 while (job_list_any_p(&c->reserved_jobs)) {
490 j = job_remove(c->reserved_jobs.next);
491 r = enqueue_job(j, 0, 0);
492 if (r < 1) bury_job(j, 0);
493 global_stat.reserved_ct--;
494 j->tube->stat.reserved_ct--;
495 c->soonest_job = NULL;
496 if (!job_list_any_p(&c->reserved_jobs)) conn_remove(c);
500 static job
501 delay_q_take()
503 job j = delay_q_peek();
504 return j ? pq_take(&j->tube->delay) : NULL;
507 static int
508 kick_buried_job(tube t)
510 int r;
511 job j;
512 size_t z;
514 if (!buried_job_p(t)) return 0;
515 j = remove_buried_job(t->buried.next);
517 z = binlog_reserve_space_update(j);
518 if (!z) return pq_give(&t->delay, j), 0; /* put it back */
519 j->reserved_binlog_space += z;
521 j->kick_ct++;
522 r = enqueue_job(j, 0, 1);
523 if (r == 1) return 1;
525 /* ready queue is full, so bury it */
526 bury_job(j, 0);
527 return 0;
530 static unsigned int
531 get_delayed_job_ct()
533 tube t;
534 size_t i;
535 unsigned int count = 0;
537 for (i = 0; i < tubes.used; i++) {
538 t = tubes.items[i];
539 count += t->delay.used;
541 return count;
544 static int
545 kick_delayed_job(tube t)
547 int r;
548 job j;
549 size_t z;
551 j = pq_take(&t->delay);
552 if (!j) return 0;
554 z = binlog_reserve_space_update(j);
555 if (!z) return pq_give(&t->delay, j), 0; /* put it back */
556 j->reserved_binlog_space += z;
558 j->kick_ct++;
559 r = enqueue_job(j, 0, 1);
560 if (r == 1) return 1;
562 /* ready queue is full, so delay it again */
563 r = enqueue_job(j, j->delay, 0);
564 if (r == 1) return 0;
566 /* last resort */
567 bury_job(j, 0);
568 return 0;
571 /* return the number of jobs successfully kicked */
572 static unsigned int
573 kick_buried_jobs(tube t, unsigned int n)
575 unsigned int i;
576 for (i = 0; (i < n) && kick_buried_job(t); ++i);
577 return i;
580 /* return the number of jobs successfully kicked */
581 static unsigned int
582 kick_delayed_jobs(tube t, unsigned int n)
584 unsigned int i;
585 for (i = 0; (i < n) && kick_delayed_job(t); ++i);
586 return i;
589 static unsigned int
590 kick_jobs(tube t, unsigned int n)
592 if (buried_job_p(t)) return kick_buried_jobs(t, n);
593 return kick_delayed_jobs(t, n);
596 static job
597 remove_buried_job(job j)
599 if (!j || j->state != JOB_STATE_BURIED) return NULL;
600 j = job_remove(j);
601 if (j) {
602 global_stat.buried_ct--;
603 j->tube->stat.buried_ct--;
605 return j;
608 static job
609 remove_ready_job(job j)
611 if (!j || j->state != JOB_STATE_READY) return NULL;
612 j = pq_remove(&j->tube->ready, j);
613 if (j) {
614 ready_ct--;
615 if (j->pri < URGENT_THRESHOLD) {
616 global_stat.urgent_ct--;
617 j->tube->stat.urgent_ct--;
620 return j;
623 static void
624 enqueue_waiting_conn(conn c)
626 tube t;
627 size_t i;
629 global_stat.waiting_ct++;
630 c->type |= CONN_TYPE_WAITING;
631 for (i = 0; i < c->watch.used; i++) {
632 t = c->watch.items[i];
633 t->stat.waiting_ct++;
634 ms_append(&t->waiting, c);
638 static job
639 find_reserved_job_in_conn(conn c, job j)
641 return (j && j->reserver == c && j->state == JOB_STATE_RESERVED) ? j : NULL;
644 static job
645 touch_job(conn c, job j)
647 j = find_reserved_job_in_conn(c, j);
648 if (j) {
649 j->deadline = time(NULL) + j->ttr;
650 c->soonest_job = NULL;
652 return j;
655 static job
656 peek_job(unsigned long long int id)
658 return job_find(id);
661 static void
662 check_err(conn c, const char *s)
664 if (errno == EAGAIN) return;
665 if (errno == EINTR) return;
666 if (errno == EWOULDBLOCK) return;
668 twarn("%s", s);
669 conn_close(c);
670 return;
673 /* Scan the given string for the sequence "\r\n" and return the line length.
674 * Always returns at least 2 if a match is found. Returns 0 if no match. */
675 static int
676 scan_line_end(const char *s, int size)
678 char *match;
680 match = memchr(s, '\r', size - 1);
681 if (!match) return 0;
683 /* this is safe because we only scan size - 1 chars above */
684 if (match[1] == '\n') return match - s + 2;
686 return 0;
689 static int
690 cmd_len(conn c)
692 return scan_line_end(c->cmd, c->cmd_read);
695 /* parse the command line */
696 static int
697 which_cmd(conn c)
699 #define TEST_CMD(s,c,o) if (strncmp((s), (c), CONSTSTRLEN(c)) == 0) return (o);
700 TEST_CMD(c->cmd, CMD_PUT, OP_PUT);
701 TEST_CMD(c->cmd, CMD_PEEKJOB, OP_PEEKJOB);
702 TEST_CMD(c->cmd, CMD_PEEK_READY, OP_PEEK_READY);
703 TEST_CMD(c->cmd, CMD_PEEK_DELAYED, OP_PEEK_DELAYED);
704 TEST_CMD(c->cmd, CMD_PEEK_BURIED, OP_PEEK_BURIED);
705 TEST_CMD(c->cmd, CMD_RESERVE_TIMEOUT, OP_RESERVE_TIMEOUT);
706 TEST_CMD(c->cmd, CMD_RESERVE, OP_RESERVE);
707 TEST_CMD(c->cmd, CMD_DELETE, OP_DELETE);
708 TEST_CMD(c->cmd, CMD_RELEASE, OP_RELEASE);
709 TEST_CMD(c->cmd, CMD_BURY, OP_BURY);
710 TEST_CMD(c->cmd, CMD_KICK, OP_KICK);
711 TEST_CMD(c->cmd, CMD_TOUCH, OP_TOUCH);
712 TEST_CMD(c->cmd, CMD_JOBSTATS, OP_JOBSTATS);
713 TEST_CMD(c->cmd, CMD_STATS_TUBE, OP_STATS_TUBE);
714 TEST_CMD(c->cmd, CMD_STATS, OP_STATS);
715 TEST_CMD(c->cmd, CMD_USE, OP_USE);
716 TEST_CMD(c->cmd, CMD_WATCH, OP_WATCH);
717 TEST_CMD(c->cmd, CMD_IGNORE, OP_IGNORE);
718 TEST_CMD(c->cmd, CMD_LIST_TUBES_WATCHED, OP_LIST_TUBES_WATCHED);
719 TEST_CMD(c->cmd, CMD_LIST_TUBE_USED, OP_LIST_TUBE_USED);
720 TEST_CMD(c->cmd, CMD_LIST_TUBES, OP_LIST_TUBES);
721 return OP_UNKNOWN;
724 /* Copy up to body_size trailing bytes into the job, then the rest into the cmd
725 * buffer. If c->in_job exists, this assumes that c->in_job->body is empty.
726 * This function is idempotent(). */
727 static void
728 fill_extra_data(conn c)
730 int extra_bytes, job_data_bytes = 0, cmd_bytes;
732 if (!c->fd) return; /* the connection was closed */
733 if (!c->cmd_len) return; /* we don't have a complete command */
735 /* how many extra bytes did we read? */
736 extra_bytes = c->cmd_read - c->cmd_len;
738 /* how many bytes should we put into the job body? */
739 if (c->in_job) {
740 job_data_bytes = min(extra_bytes, c->in_job->body_size);
741 memcpy(c->in_job->body, c->cmd + c->cmd_len, job_data_bytes);
742 c->in_job_read = job_data_bytes;
743 } else if (c->in_job_read) {
744 /* we are in bit-bucket mode, throwing away data */
745 job_data_bytes = min(extra_bytes, c->in_job_read);
746 c->in_job_read -= job_data_bytes;
749 /* how many bytes are left to go into the future cmd? */
750 cmd_bytes = extra_bytes - job_data_bytes;
751 memmove(c->cmd, c->cmd + c->cmd_len + job_data_bytes, cmd_bytes);
752 c->cmd_read = cmd_bytes;
753 c->cmd_len = 0; /* we no longer know the length of the new command */
756 static void
757 enqueue_incoming_job(conn c)
759 int r;
760 job j = c->in_job;
762 c->in_job = NULL; /* the connection no longer owns this job */
763 c->in_job_read = 0;
765 /* check if the trailer is present and correct */
766 if (memcmp(j->body + j->body_size - 2, "\r\n", 2)) {
767 job_free(j);
768 return reply_msg(c, MSG_EXPECTED_CRLF);
771 if (drain_mode) {
772 job_free(j);
773 return reply_serr(c, MSG_DRAINING);
776 if (j->reserved_binlog_space) return reply_serr(c, MSG_INTERNAL_ERROR);
777 j->reserved_binlog_space = binlog_reserve_space_put(j);
778 if (!j->reserved_binlog_space) return reply_serr(c, MSG_OUT_OF_MEMORY);
780 /* we have a complete job, so let's stick it in the pqueue */
781 r = enqueue_job(j, j->delay, 1);
782 if (r < 0) return reply_serr(c, MSG_INTERNAL_ERROR);
784 op_ct[OP_PUT]++; /* stats */
785 global_stat.total_jobs_ct++;
786 j->tube->stat.total_jobs_ct++;
788 if (r == 1) return reply_line(c, STATE_SENDWORD, MSG_INSERTED_FMT, j->id);
790 /* out of memory trying to grow the queue, so it gets buried */
791 bury_job(j, 0);
792 reply_line(c, STATE_SENDWORD, MSG_BURIED_FMT, j->id);
795 static unsigned int
796 uptime()
798 return time(NULL) - start_time;
801 static int
802 fmt_stats(char *buf, size_t size, void *x)
804 struct rusage ru = {{0, 0}, {0, 0}};
805 getrusage(RUSAGE_SELF, &ru); /* don't care if it fails */
806 return snprintf(buf, size, STATS_FMT,
807 global_stat.urgent_ct,
808 ready_ct,
809 global_stat.reserved_ct,
810 get_delayed_job_ct(),
811 global_stat.buried_ct,
812 op_ct[OP_PUT],
813 op_ct[OP_PEEKJOB],
814 op_ct[OP_PEEK_READY],
815 op_ct[OP_PEEK_DELAYED],
816 op_ct[OP_PEEK_BURIED],
817 op_ct[OP_RESERVE],
818 op_ct[OP_RESERVE_TIMEOUT],
819 op_ct[OP_DELETE],
820 op_ct[OP_RELEASE],
821 op_ct[OP_USE],
822 op_ct[OP_WATCH],
823 op_ct[OP_IGNORE],
824 op_ct[OP_BURY],
825 op_ct[OP_KICK],
826 op_ct[OP_TOUCH],
827 op_ct[OP_STATS],
828 op_ct[OP_JOBSTATS],
829 op_ct[OP_STATS_TUBE],
830 op_ct[OP_LIST_TUBES],
831 op_ct[OP_LIST_TUBE_USED],
832 op_ct[OP_LIST_TUBES_WATCHED],
833 timeout_ct,
834 global_stat.total_jobs_ct,
835 job_data_size_limit,
836 tubes.used,
837 count_cur_conns(),
838 count_cur_producers(),
839 count_cur_workers(),
840 global_stat.waiting_ct,
841 count_tot_conns(),
842 (long) getpid(),
843 VERSION,
844 (int) ru.ru_utime.tv_sec, (int) ru.ru_utime.tv_usec,
845 (int) ru.ru_stime.tv_sec, (int) ru.ru_stime.tv_usec,
846 uptime(),
847 binlog_oldest_index(),
848 binlog_current_index(),
849 binlog_size_limit);
853 /* Read a priority value from the given buffer and place it in pri.
854 * Update end to point to the address after the last character consumed.
855 * Pri and end can be NULL. If they are both NULL, read_pri() will do the
856 * conversion and return the status code but not update any values. This is an
857 * easy way to check for errors.
858 * If end is NULL, read_pri will also check that the entire input string was
859 * consumed and return an error code otherwise.
860 * Return 0 on success, or nonzero on failure.
861 * If a failure occurs, pri and end are not modified. */
862 static int
863 read_pri(unsigned int *pri, const char *buf, char **end)
865 char *tend;
866 unsigned int tpri;
868 errno = 0;
869 while (buf[0] == ' ') buf++;
870 if (!isdigit(buf[0])) return -1;
871 tpri = strtoul(buf, &tend, 10);
872 if (tend == buf) return -1;
873 if (errno && errno != ERANGE) return -1;
874 if (!end && tend[0] != '\0') return -1;
876 if (pri) *pri = tpri;
877 if (end) *end = tend;
878 return 0;
881 /* Read a delay value from the given buffer and place it in delay.
882 * The interface and behavior are the same as in read_pri(). */
883 static int
884 read_delay(unsigned int *delay, const char *buf, char **end)
886 time_t now = time(NULL);
887 return read_pri(delay, buf, end) ? : (now + *delay < now);
890 /* Read a timeout value from the given buffer and place it in ttr.
891 * The interface and behavior are the same as in read_pri(). */
892 static int
893 read_ttr(unsigned int *ttr, const char *buf, char **end)
895 return read_pri(ttr, buf, end);
898 static void
899 wait_for_job(conn c, int timeout)
901 int r;
903 c->state = STATE_WAIT;
904 enqueue_waiting_conn(c);
906 /* Set the pending timeout to the requested timeout amount */
907 c->pending_timeout = timeout;
909 /* this conn is waiting, but we want to know if they hang up */
910 r = conn_update_evq(c, EV_READ | EV_PERSIST);
911 if (r == -1) return twarnx("update events failed"), conn_close(c);
914 typedef int(*fmt_fn)(char *, size_t, void *);
916 static void
917 do_stats(conn c, fmt_fn fmt, void *data)
919 int r, stats_len;
921 /* first, measure how big a buffer we will need */
922 stats_len = fmt(NULL, 0, data) + 16;
924 c->out_job = allocate_job(stats_len); /* fake job to hold stats data */
925 if (!c->out_job) return reply_serr(c, MSG_OUT_OF_MEMORY);
927 /* now actually format the stats data */
928 r = fmt(c->out_job->body, stats_len, data);
929 /* and set the actual body size */
930 c->out_job->body_size = r;
931 if (r > stats_len) return reply_serr(c, MSG_INTERNAL_ERROR);
933 c->out_job_sent = 0;
934 return reply_line(c, STATE_SENDJOB, "OK %d\r\n", r - 2);
937 static void
938 do_list_tubes(conn c, ms l)
940 char *buf;
941 tube t;
942 size_t i, resp_z;
944 /* first, measure how big a buffer we will need */
945 resp_z = 6; /* initial "---\n" and final "\r\n" */
946 for (i = 0; i < l->used; i++) {
947 t = l->items[i];
948 resp_z += 3 + strlen(t->name); /* including "- " and "\n" */
951 c->out_job = allocate_job(resp_z); /* fake job to hold response data */
952 if (!c->out_job) return reply_serr(c, MSG_OUT_OF_MEMORY);
954 /* now actually format the response */
955 buf = c->out_job->body;
956 buf += snprintf(buf, 5, "---\n");
957 for (i = 0; i < l->used; i++) {
958 t = l->items[i];
959 buf += snprintf(buf, 4 + strlen(t->name), "- %s\n", t->name);
961 buf[0] = '\r';
962 buf[1] = '\n';
964 c->out_job_sent = 0;
965 return reply_line(c, STATE_SENDJOB, "OK %d\r\n", resp_z - 2);
968 static int
969 fmt_job_stats(char *buf, size_t size, job j)
971 time_t t;
973 t = time(NULL);
974 return snprintf(buf, size, JOB_STATS_FMT,
975 j->id,
976 j->tube->name,
977 job_state(j),
978 j->pri,
979 (unsigned int) (t - j->creation),
980 j->delay,
981 j->ttr,
982 (unsigned int) (j->deadline - t),
983 j->timeout_ct,
984 j->release_ct,
985 j->bury_ct,
986 j->kick_ct);
989 static int
990 fmt_stats_tube(char *buf, size_t size, tube t)
992 return snprintf(buf, size, STATS_TUBE_FMT,
993 t->name,
994 t->stat.urgent_ct,
995 t->ready.used,
996 t->stat.reserved_ct,
997 t->delay.used,
998 t->stat.buried_ct,
999 t->stat.total_jobs_ct,
1000 t->using_ct,
1001 t->watching_ct,
1002 t->stat.waiting_ct);
1005 static void
1006 maybe_enqueue_incoming_job(conn c)
1008 job j = c->in_job;
1010 /* do we have a complete job? */
1011 if (c->in_job_read == j->body_size) return enqueue_incoming_job(c);
1013 /* otherwise we have incomplete data, so just keep waiting */
1014 c->state = STATE_WANTDATA;
1017 /* j can be NULL */
1018 static job
1019 remove_this_reserved_job(conn c, job j)
1021 j = job_remove(j);
1022 if (j) {
1023 global_stat.reserved_ct--;
1024 j->tube->stat.reserved_ct--;
1025 j->reserver = NULL;
1027 c->soonest_job = NULL;
1028 if (!job_list_any_p(&c->reserved_jobs)) conn_remove(c);
1029 return j;
1032 static job
1033 remove_reserved_job(conn c, job j)
1035 return remove_this_reserved_job(c, find_reserved_job_in_conn(c, j));
1038 static int
1039 name_is_ok(const char *name, size_t max)
1041 size_t len = strlen(name);
1042 return len > 0 && len <= max &&
1043 strspn(name, NAME_CHARS) == len && name[0] != '-';
1046 void
1047 prot_remove_tube(tube t)
1049 ms_remove(&tubes, t);
1052 static void
1053 dispatch_cmd(conn c)
1055 int r, i, timeout = -1;
1056 size_t z;
1057 unsigned int count;
1058 job j;
1059 unsigned char type;
1060 char *size_buf, *delay_buf, *ttr_buf, *pri_buf, *end_buf, *name;
1061 unsigned int pri, delay, ttr, body_size;
1062 unsigned long long int id;
1063 tube t = NULL;
1065 /* NUL-terminate this string so we can use strtol and friends */
1066 c->cmd[c->cmd_len - 2] = '\0';
1068 /* check for possible maliciousness */
1069 if (strlen(c->cmd) != c->cmd_len - 2) {
1070 return reply_msg(c, MSG_BAD_FORMAT);
1073 type = which_cmd(c);
1074 dprintf("got %s command: \"%s\"\n", op_names[(int) type], c->cmd);
1076 switch (type) {
1077 case OP_PUT:
1078 r = read_pri(&pri, c->cmd + 4, &delay_buf);
1079 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1081 r = read_delay(&delay, delay_buf, &ttr_buf);
1082 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1084 r = read_ttr(&ttr, ttr_buf, &size_buf);
1085 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1087 errno = 0;
1088 body_size = strtoul(size_buf, &end_buf, 10);
1089 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1091 if (body_size > job_data_size_limit) {
1092 return reply_msg(c, MSG_JOB_TOO_BIG);
1095 /* don't allow trailing garbage */
1096 if (end_buf[0] != '\0') return reply_msg(c, MSG_BAD_FORMAT);
1098 conn_set_producer(c);
1100 c->in_job = make_job(pri, delay, ttr ? : 1, body_size + 2, c->use);
1102 /* OOM? */
1103 if (!c->in_job) {
1104 /* throw away the job body and respond with OUT_OF_MEMORY */
1106 /* Invert the meaning of in_job_read while throwing away data -- it
1107 * counts the bytes that remain to be thrown away. */
1108 c->in_job_read = body_size + 2;
1109 fill_extra_data(c);
1111 if (c->in_job_read == 0) return reply_serr(c, MSG_OUT_OF_MEMORY);
1113 c->state = STATE_BITBUCKET;
1114 return;
1117 fill_extra_data(c);
1119 /* it's possible we already have a complete job */
1120 maybe_enqueue_incoming_job(c);
1122 break;
1123 case OP_PEEK_READY:
1124 /* don't allow trailing garbage */
1125 if (c->cmd_len != CMD_PEEK_READY_LEN + 2) {
1126 return reply_msg(c, MSG_BAD_FORMAT);
1128 op_ct[type]++;
1130 j = job_copy(pq_peek(&c->use->ready));
1132 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1134 reply_job(c, j, MSG_FOUND);
1135 break;
1136 case OP_PEEK_DELAYED:
1137 /* don't allow trailing garbage */
1138 if (c->cmd_len != CMD_PEEK_DELAYED_LEN + 2) {
1139 return reply_msg(c, MSG_BAD_FORMAT);
1141 op_ct[type]++;
1143 j = job_copy(pq_peek(&c->use->delay));
1145 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1147 reply_job(c, j, MSG_FOUND);
1148 break;
1149 case OP_PEEK_BURIED:
1150 /* don't allow trailing garbage */
1151 if (c->cmd_len != CMD_PEEK_BURIED_LEN + 2) {
1152 return reply_msg(c, MSG_BAD_FORMAT);
1154 op_ct[type]++;
1156 j = job_copy(buried_job_p(c->use)? j = c->use->buried.next : NULL);
1158 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1160 reply_job(c, j, MSG_FOUND);
1161 break;
1162 case OP_PEEKJOB:
1163 errno = 0;
1164 id = strtoull(c->cmd + CMD_PEEKJOB_LEN, &end_buf, 10);
1165 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1166 op_ct[type]++;
1168 /* So, peek is annoying, because some other connection might free the
1169 * job while we are still trying to write it out. So we copy it and
1170 * then free the copy when it's done sending. */
1171 j = job_copy(peek_job(id));
1173 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1175 reply_job(c, j, MSG_FOUND);
1176 break;
1177 case OP_RESERVE_TIMEOUT:
1178 errno = 0;
1179 timeout = strtol(c->cmd + CMD_RESERVE_TIMEOUT_LEN, &end_buf, 10);
1180 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1181 case OP_RESERVE: /* FALLTHROUGH */
1182 /* don't allow trailing garbage */
1183 if (type == OP_RESERVE && c->cmd_len != CMD_RESERVE_LEN + 2) {
1184 return reply_msg(c, MSG_BAD_FORMAT);
1187 op_ct[type]++;
1188 conn_set_worker(c);
1190 if (conn_has_close_deadline(c) && !conn_ready(c)) {
1191 return reply_msg(c, MSG_DEADLINE_SOON);
1194 /* try to get a new job for this guy */
1195 wait_for_job(c, timeout);
1196 process_queue();
1197 break;
1198 case OP_DELETE:
1199 errno = 0;
1200 id = strtoull(c->cmd + CMD_DELETE_LEN, &end_buf, 10);
1201 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1202 op_ct[type]++;
1204 j = job_find(id);
1205 j = remove_reserved_job(c, j) ? :
1206 remove_ready_job(j) ? :
1207 remove_buried_job(j);
1209 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1211 j->state = JOB_STATE_INVALID;
1212 r = binlog_write_job(j);
1213 job_free(j);
1215 if (!r) return reply_serr(c, MSG_INTERNAL_ERROR);
1217 reply(c, MSG_DELETED, MSG_DELETED_LEN, STATE_SENDWORD);
1218 break;
1219 case OP_RELEASE:
1220 errno = 0;
1221 id = strtoull(c->cmd + CMD_RELEASE_LEN, &pri_buf, 10);
1222 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1224 r = read_pri(&pri, pri_buf, &delay_buf);
1225 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1227 r = read_delay(&delay, delay_buf, NULL);
1228 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1229 op_ct[type]++;
1231 j = remove_reserved_job(c, job_find(id));
1233 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1235 /* We want to update the delay deadline on disk, so reserve space for
1236 * that. */
1237 if (delay) {
1238 z = binlog_reserve_space_update(j);
1239 if (!z) return reply_serr(c, MSG_OUT_OF_MEMORY);
1240 j->reserved_binlog_space += z;
1243 j->pri = pri;
1244 j->delay = delay;
1245 j->release_ct++;
1247 r = enqueue_job(j, delay, !!delay);
1248 if (r < 0) return reply_serr(c, MSG_INTERNAL_ERROR);
1249 if (r == 1) {
1250 return reply(c, MSG_RELEASED, MSG_RELEASED_LEN, STATE_SENDWORD);
1253 /* out of memory trying to grow the queue, so it gets buried */
1254 bury_job(j, 0);
1255 reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD);
1256 break;
1257 case OP_BURY:
1258 errno = 0;
1259 id = strtoull(c->cmd + CMD_BURY_LEN, &pri_buf, 10);
1260 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1262 r = read_pri(&pri, pri_buf, NULL);
1263 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1264 op_ct[type]++;
1266 j = remove_reserved_job(c, job_find(id));
1268 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1270 j->pri = pri;
1271 r = bury_job(j, 1);
1272 if (!r) return reply_serr(c, MSG_INTERNAL_ERROR);
1273 reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD);
1274 break;
1275 case OP_KICK:
1276 errno = 0;
1277 count = strtoul(c->cmd + CMD_KICK_LEN, &end_buf, 10);
1278 if (end_buf == c->cmd + CMD_KICK_LEN) {
1279 return reply_msg(c, MSG_BAD_FORMAT);
1281 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1283 op_ct[type]++;
1285 i = kick_jobs(c->use, count);
1287 return reply_line(c, STATE_SENDWORD, "KICKED %u\r\n", i);
1288 case OP_TOUCH:
1289 errno = 0;
1290 id = strtoull(c->cmd + CMD_TOUCH_LEN, &end_buf, 10);
1291 if (errno) return twarn("strtoull"), reply_msg(c, MSG_BAD_FORMAT);
1293 op_ct[type]++;
1295 j = touch_job(c, job_find(id));
1297 if (j) {
1298 reply(c, MSG_TOUCHED, MSG_TOUCHED_LEN, STATE_SENDWORD);
1299 } else {
1300 return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1302 break;
1303 case OP_STATS:
1304 /* don't allow trailing garbage */
1305 if (c->cmd_len != CMD_STATS_LEN + 2) {
1306 return reply_msg(c, MSG_BAD_FORMAT);
1309 op_ct[type]++;
1311 do_stats(c, fmt_stats, NULL);
1312 break;
1313 case OP_JOBSTATS:
1314 errno = 0;
1315 id = strtoull(c->cmd + CMD_JOBSTATS_LEN, &end_buf, 10);
1316 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1318 op_ct[type]++;
1320 j = peek_job(id);
1321 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1323 if (!j->tube) return reply_serr(c, MSG_INTERNAL_ERROR);
1324 do_stats(c, (fmt_fn) fmt_job_stats, j);
1325 break;
1326 case OP_STATS_TUBE:
1327 name = c->cmd + CMD_STATS_TUBE_LEN;
1328 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1330 op_ct[type]++;
1332 t = tube_find(name);
1333 if (!t) return reply_msg(c, MSG_NOTFOUND);
1335 do_stats(c, (fmt_fn) fmt_stats_tube, t);
1336 t = NULL;
1337 break;
1338 case OP_LIST_TUBES:
1339 /* don't allow trailing garbage */
1340 if (c->cmd_len != CMD_LIST_TUBES_LEN + 2) {
1341 return reply_msg(c, MSG_BAD_FORMAT);
1344 op_ct[type]++;
1345 do_list_tubes(c, &tubes);
1346 break;
1347 case OP_LIST_TUBE_USED:
1348 /* don't allow trailing garbage */
1349 if (c->cmd_len != CMD_LIST_TUBE_USED_LEN + 2) {
1350 return reply_msg(c, MSG_BAD_FORMAT);
1353 op_ct[type]++;
1354 reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name);
1355 break;
1356 case OP_LIST_TUBES_WATCHED:
1357 /* don't allow trailing garbage */
1358 if (c->cmd_len != CMD_LIST_TUBES_WATCHED_LEN + 2) {
1359 return reply_msg(c, MSG_BAD_FORMAT);
1362 op_ct[type]++;
1363 do_list_tubes(c, &c->watch);
1364 break;
1365 case OP_USE:
1366 name = c->cmd + CMD_USE_LEN;
1367 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1368 op_ct[type]++;
1370 TUBE_ASSIGN(t, tube_find_or_make(name));
1371 if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY);
1373 c->use->using_ct--;
1374 TUBE_ASSIGN(c->use, t);
1375 TUBE_ASSIGN(t, NULL);
1376 c->use->using_ct++;
1378 reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name);
1379 break;
1380 case OP_WATCH:
1381 name = c->cmd + CMD_WATCH_LEN;
1382 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1383 op_ct[type]++;
1385 TUBE_ASSIGN(t, tube_find_or_make(name));
1386 if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY);
1388 r = 1;
1389 if (!ms_contains(&c->watch, t)) r = ms_append(&c->watch, t);
1390 TUBE_ASSIGN(t, NULL);
1391 if (!r) return reply_serr(c, MSG_OUT_OF_MEMORY);
1393 reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used);
1394 break;
1395 case OP_IGNORE:
1396 name = c->cmd + CMD_IGNORE_LEN;
1397 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1398 op_ct[type]++;
1400 t = NULL;
1401 for (i = 0; i < c->watch.used; i++) {
1402 t = c->watch.items[i];
1403 if (strncmp(t->name, name, MAX_TUBE_NAME_LEN) == 0) break;
1404 t = NULL;
1407 if (t && c->watch.used < 2) return reply_msg(c, MSG_NOT_IGNORED);
1409 if (t) ms_remove(&c->watch, t); /* may free t if refcount => 0 */
1410 t = NULL;
1412 reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used);
1413 break;
1414 default:
1415 return reply_msg(c, MSG_UNKNOWN_COMMAND);
1419 /* There are three reasons this function may be called. We need to check for
1420 * all of them.
1422 * 1. A reserved job has run out of time.
1423 * 2. A waiting client's reserved job has entered the safety margin.
1424 * 3. A waiting client's requested timeout has occurred.
1426 * If any of these happen, we must do the appropriate thing. */
1427 static void
1428 h_conn_timeout(conn c)
1430 int r, should_timeout = 0;
1431 job j;
1433 /* Check if the client was trying to reserve a job. */
1434 if (conn_waiting(c) && conn_has_close_deadline(c)) should_timeout = 1;
1436 /* Check if any reserved jobs have run out of time. We should do this
1437 * whether or not the client is waiting for a new reservation. */
1438 while ((j = soonest_job(c))) {
1439 if (j->deadline >= time(NULL)) break;
1441 /* This job is in the middle of being written out. If we return it to
1442 * the ready queue, someone might free it before we finish writing it
1443 * out to the socket. So we'll copy it here and free the copy when it's
1444 * done sending. */
1445 if (j == c->out_job) {
1446 c->out_job = job_copy(c->out_job);
1447 c->out_job->id = 0;
1450 timeout_ct++; /* stats */
1451 j->timeout_ct++;
1452 r = enqueue_job(remove_this_reserved_job(c, j), 0, 0);
1453 if (r < 1) bury_job(j, 0); /* out of memory, so bury it */
1454 r = conn_update_evq(c, c->evq.ev_events);
1455 if (r == -1) return twarnx("conn_update_evq() failed"), conn_close(c);
1458 if (should_timeout) {
1459 dprintf("conn_waiting(%p) = %d\n", c, conn_waiting(c));
1460 return reply_msg(remove_waiting_conn(c), MSG_DEADLINE_SOON);
1461 } else if (conn_waiting(c) && c->pending_timeout >= 0) {
1462 dprintf("conn_waiting(%p) = %d\n", c, conn_waiting(c));
1463 c->pending_timeout = -1;
1464 return reply_msg(remove_waiting_conn(c), MSG_TIMED_OUT);
1468 void
1469 enter_drain_mode(int sig)
1471 drain_mode = 1;
1474 static void
1475 do_cmd(conn c)
1477 dispatch_cmd(c);
1478 fill_extra_data(c);
1481 static void
1482 reset_conn(conn c)
1484 int r;
1486 r = conn_update_evq(c, EV_READ | EV_PERSIST);
1487 if (r == -1) return twarnx("update events failed"), conn_close(c);
1489 /* was this a peek or stats command? */
1490 if (c->out_job && !c->out_job->id) job_free(c->out_job);
1491 c->out_job = NULL;
1493 c->reply_sent = 0; /* now that we're done, reset this */
1494 c->state = STATE_WANTCOMMAND;
1497 static void
1498 h_conn_data(conn c)
1500 int r, to_read;
1501 job j;
1502 struct iovec iov[2];
1504 switch (c->state) {
1505 case STATE_WANTCOMMAND:
1506 r = read(c->fd, c->cmd + c->cmd_read, LINE_BUF_SIZE - c->cmd_read);
1507 if (r == -1) return check_err(c, "read()");
1508 if (r == 0) return conn_close(c); /* the client hung up */
1510 c->cmd_read += r; /* we got some bytes */
1512 c->cmd_len = cmd_len(c); /* find the EOL */
1514 /* yay, complete command line */
1515 if (c->cmd_len) return do_cmd(c);
1517 /* c->cmd_read > LINE_BUF_SIZE can't happen */
1519 /* command line too long? */
1520 if (c->cmd_read == LINE_BUF_SIZE) {
1521 c->cmd_read = 0; /* discard the input so far */
1522 return reply_msg(c, MSG_BAD_FORMAT);
1525 /* otherwise we have an incomplete line, so just keep waiting */
1526 break;
1527 case STATE_BITBUCKET:
1528 /* Invert the meaning of in_job_read while throwing away data -- it
1529 * counts the bytes that remain to be thrown away. */
1530 to_read = min(c->in_job_read, BUCKET_BUF_SIZE);
1531 r = read(c->fd, bucket, to_read);
1532 if (r == -1) return check_err(c, "read()");
1533 if (r == 0) return conn_close(c); /* the client hung up */
1535 c->in_job_read -= r; /* we got some bytes */
1537 /* (c->in_job_read < 0) can't happen */
1539 if (c->in_job_read == 0) return reply_serr(c, MSG_OUT_OF_MEMORY);
1540 break;
1541 case STATE_WANTDATA:
1542 j = c->in_job;
1544 r = read(c->fd, j->body + c->in_job_read, j->body_size -c->in_job_read);
1545 if (r == -1) return check_err(c, "read()");
1546 if (r == 0) return conn_close(c); /* the client hung up */
1548 c->in_job_read += r; /* we got some bytes */
1550 /* (j->in_job_read > j->body_size) can't happen */
1552 maybe_enqueue_incoming_job(c);
1553 break;
1554 case STATE_SENDWORD:
1555 r= write(c->fd, c->reply + c->reply_sent, c->reply_len - c->reply_sent);
1556 if (r == -1) return check_err(c, "write()");
1557 if (r == 0) return conn_close(c); /* the client hung up */
1559 c->reply_sent += r; /* we got some bytes */
1561 /* (c->reply_sent > c->reply_len) can't happen */
1563 if (c->reply_sent == c->reply_len) return reset_conn(c);
1565 /* otherwise we sent an incomplete reply, so just keep waiting */
1566 break;
1567 case STATE_SENDJOB:
1568 j = c->out_job;
1570 iov[0].iov_base = (void *)(c->reply + c->reply_sent);
1571 iov[0].iov_len = c->reply_len - c->reply_sent; /* maybe 0 */
1572 iov[1].iov_base = j->body + c->out_job_sent;
1573 iov[1].iov_len = j->body_size - c->out_job_sent;
1575 r = writev(c->fd, iov, 2);
1576 if (r == -1) return check_err(c, "writev()");
1577 if (r == 0) return conn_close(c); /* the client hung up */
1579 /* update the sent values */
1580 c->reply_sent += r;
1581 if (c->reply_sent >= c->reply_len) {
1582 c->out_job_sent += c->reply_sent - c->reply_len;
1583 c->reply_sent = c->reply_len;
1586 /* (c->out_job_sent > j->body_size) can't happen */
1588 /* are we done? */
1589 if (c->out_job_sent == j->body_size) return reset_conn(c);
1591 /* otherwise we sent incomplete data, so just keep waiting */
1592 break;
1593 case STATE_WAIT: /* keep an eye out in case they hang up */
1594 /* but don't hang up just because our buffer is full */
1595 if (LINE_BUF_SIZE - c->cmd_read < 1) break;
1597 r = read(c->fd, c->cmd + c->cmd_read, LINE_BUF_SIZE - c->cmd_read);
1598 if (r == -1) return check_err(c, "read()");
1599 if (r == 0) return conn_close(c); /* the client hung up */
1600 c->cmd_read += r; /* we got some bytes */
1604 #define want_command(c) ((c)->fd && ((c)->state == STATE_WANTCOMMAND))
1605 #define cmd_data_ready(c) (want_command(c) && (c)->cmd_read)
1607 static void
1608 h_conn(const int fd, const short which, conn c)
1610 if (fd != c->fd) {
1611 twarnx("Argh! event fd doesn't match conn fd.");
1612 close(fd);
1613 return conn_close(c);
1616 switch (which) {
1617 case EV_TIMEOUT:
1618 h_conn_timeout(c);
1619 event_add(&c->evq, NULL); /* seems to be necessary */
1620 break;
1621 case EV_READ:
1622 /* fall through... */
1623 case EV_WRITE:
1624 /* fall through... */
1625 default:
1626 h_conn_data(c);
1629 while (cmd_data_ready(c) && (c->cmd_len = cmd_len(c))) do_cmd(c);
1632 static void
1633 h_delay()
1635 int r;
1636 job j;
1637 time_t t;
1639 t = time(NULL);
1640 while ((j = delay_q_peek())) {
1641 if (j->deadline > t) break;
1642 j = delay_q_take();
1643 r = enqueue_job(j, 0, 0);
1644 if (r < 1) bury_job(j, 0); /* out of memory, so bury it */
1647 set_main_delay_timeout();
1650 void
1651 h_accept(const int fd, const short which, struct event *ev)
1653 conn c;
1654 int cfd, flags, r;
1655 socklen_t addrlen;
1656 struct sockaddr addr;
1658 if (which == EV_TIMEOUT) return h_delay();
1660 addrlen = sizeof addr;
1661 cfd = accept(fd, &addr, &addrlen);
1662 if (cfd == -1) {
1663 if (errno != EAGAIN && errno != EWOULDBLOCK) twarn("accept()");
1664 if (errno == EMFILE) brake();
1665 return;
1668 flags = fcntl(cfd, F_GETFL, 0);
1669 if (flags < 0) return twarn("getting flags"), close(cfd), v();
1671 r = fcntl(cfd, F_SETFL, flags | O_NONBLOCK);
1672 if (r < 0) return twarn("setting O_NONBLOCK"), close(cfd), v();
1674 c = make_conn(cfd, STATE_WANTCOMMAND, default_tube, default_tube);
1675 if (!c) return twarnx("make_conn() failed"), close(cfd), brake();
1677 dprintf("accepted conn, fd=%d\n", cfd);
1678 r = conn_set_evq(c, EV_READ | EV_PERSIST, (evh) h_conn);
1679 if (r == -1) return twarnx("conn_set_evq() failed"), close(cfd), brake();
1682 void
1683 prot_init()
1685 start_time = time(NULL);
1686 memset(op_ct, 0, sizeof(op_ct));
1688 ms_init(&tubes, NULL, NULL);
1690 TUBE_ASSIGN(default_tube, tube_find_or_make("default"));
1691 if (!default_tube) twarnx("Out of memory during startup!");
1694 void
1695 prot_replay_binlog(job binlog_jobs)
1697 job j, nj;
1698 unsigned int delay;
1699 int r;
1701 for (j = binlog_jobs->next ; j != binlog_jobs ; j = nj) {
1702 nj = j->next;
1703 job_remove(j);
1704 binlog_reserve_space_update(j); /* reserve space for a delete */
1705 delay = 0;
1706 switch (j->state) {
1707 case JOB_STATE_BURIED:
1708 bury_job(j, 0);
1709 break;
1710 case JOB_STATE_DELAYED:
1711 if (start_time < j->deadline) delay = j->deadline - start_time;
1712 /* fall through */
1713 default:
1714 r = enqueue_job(j, delay, 0);
1715 if (r < 1) twarnx("error processing binlog job %llu", j->id);