More tests and fix the deadline overflow check.
[beanstalkd.git] / prot.c
blobb16962a2f7319b8e565670378b3fe780c1814e6c
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>
28 #include "stat.h"
29 #include "prot.h"
30 #include "pq.h"
31 #include "ms.h"
32 #include "job.h"
33 #include "tube.h"
34 #include "conn.h"
35 #include "util.h"
36 #include "net.h"
37 #include "binlog.h"
38 #include "version.h"
40 /* job body cannot be greater than this many bytes long */
41 size_t job_data_size_limit = JOB_DATA_SIZE_LIMIT_DEFAULT;
43 #define NAME_CHARS \
44 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
45 "abcdefghijklmnopqrstuvwxyz" \
46 "0123456789-+/;.$()"
48 #define CMD_PUT "put "
49 #define CMD_PEEKJOB "peek "
50 #define CMD_PEEK_READY "peek-ready"
51 #define CMD_PEEK_DELAYED "peek-delayed"
52 #define CMD_PEEK_BURIED "peek-buried"
53 #define CMD_RESERVE "reserve"
54 #define CMD_RESERVE_TIMEOUT "reserve-with-timeout "
55 #define CMD_DELETE "delete "
56 #define CMD_RELEASE "release "
57 #define CMD_BURY "bury "
58 #define CMD_KICK "kick "
59 #define CMD_TOUCH "touch "
60 #define CMD_STATS "stats"
61 #define CMD_JOBSTATS "stats-job "
62 #define CMD_USE "use "
63 #define CMD_WATCH "watch "
64 #define CMD_IGNORE "ignore "
65 #define CMD_LIST_TUBES "list-tubes"
66 #define CMD_LIST_TUBE_USED "list-tube-used"
67 #define CMD_LIST_TUBES_WATCHED "list-tubes-watched"
68 #define CMD_STATS_TUBE "stats-tube "
70 #define CONSTSTRLEN(m) (sizeof(m) - 1)
72 #define CMD_PEEK_READY_LEN CONSTSTRLEN(CMD_PEEK_READY)
73 #define CMD_PEEK_DELAYED_LEN CONSTSTRLEN(CMD_PEEK_DELAYED)
74 #define CMD_PEEK_BURIED_LEN CONSTSTRLEN(CMD_PEEK_BURIED)
75 #define CMD_PEEKJOB_LEN CONSTSTRLEN(CMD_PEEKJOB)
76 #define CMD_RESERVE_LEN CONSTSTRLEN(CMD_RESERVE)
77 #define CMD_RESERVE_TIMEOUT_LEN CONSTSTRLEN(CMD_RESERVE_TIMEOUT)
78 #define CMD_DELETE_LEN CONSTSTRLEN(CMD_DELETE)
79 #define CMD_RELEASE_LEN CONSTSTRLEN(CMD_RELEASE)
80 #define CMD_BURY_LEN CONSTSTRLEN(CMD_BURY)
81 #define CMD_KICK_LEN CONSTSTRLEN(CMD_KICK)
82 #define CMD_TOUCH_LEN CONSTSTRLEN(CMD_TOUCH)
83 #define CMD_STATS_LEN CONSTSTRLEN(CMD_STATS)
84 #define CMD_JOBSTATS_LEN CONSTSTRLEN(CMD_JOBSTATS)
85 #define CMD_USE_LEN CONSTSTRLEN(CMD_USE)
86 #define CMD_WATCH_LEN CONSTSTRLEN(CMD_WATCH)
87 #define CMD_IGNORE_LEN CONSTSTRLEN(CMD_IGNORE)
88 #define CMD_LIST_TUBES_LEN CONSTSTRLEN(CMD_LIST_TUBES)
89 #define CMD_LIST_TUBE_USED_LEN CONSTSTRLEN(CMD_LIST_TUBE_USED)
90 #define CMD_LIST_TUBES_WATCHED_LEN CONSTSTRLEN(CMD_LIST_TUBES_WATCHED)
91 #define CMD_STATS_TUBE_LEN CONSTSTRLEN(CMD_STATS_TUBE)
93 #define MSG_FOUND "FOUND"
94 #define MSG_NOTFOUND "NOT_FOUND\r\n"
95 #define MSG_RESERVED "RESERVED"
96 #define MSG_DEADLINE_SOON "DEADLINE_SOON\r\n"
97 #define MSG_TIMED_OUT "TIMED_OUT\r\n"
98 #define MSG_DELETED "DELETED\r\n"
99 #define MSG_RELEASED "RELEASED\r\n"
100 #define MSG_BURIED "BURIED\r\n"
101 #define MSG_TOUCHED "TOUCHED\r\n"
102 #define MSG_BURIED_FMT "BURIED %llu\r\n"
103 #define MSG_INSERTED_FMT "INSERTED %llu\r\n"
104 #define MSG_NOT_IGNORED "NOT_IGNORED\r\n"
106 #define MSG_NOTFOUND_LEN CONSTSTRLEN(MSG_NOTFOUND)
107 #define MSG_DELETED_LEN CONSTSTRLEN(MSG_DELETED)
108 #define MSG_TOUCHED_LEN CONSTSTRLEN(MSG_TOUCHED)
109 #define MSG_RELEASED_LEN CONSTSTRLEN(MSG_RELEASED)
110 #define MSG_BURIED_LEN CONSTSTRLEN(MSG_BURIED)
111 #define MSG_NOT_IGNORED_LEN CONSTSTRLEN(MSG_NOT_IGNORED)
113 #define MSG_OUT_OF_MEMORY "OUT_OF_MEMORY\r\n"
114 #define MSG_INTERNAL_ERROR "INTERNAL_ERROR\r\n"
115 #define MSG_DRAINING "DRAINING\r\n"
116 #define MSG_BAD_FORMAT "BAD_FORMAT\r\n"
117 #define MSG_UNKNOWN_COMMAND "UNKNOWN_COMMAND\r\n"
118 #define MSG_EXPECTED_CRLF "EXPECTED_CRLF\r\n"
119 #define MSG_JOB_TOO_BIG "JOB_TOO_BIG\r\n"
121 #define STATE_WANTCOMMAND 0
122 #define STATE_WANTDATA 1
123 #define STATE_SENDJOB 2
124 #define STATE_SENDWORD 3
125 #define STATE_WAIT 4
126 #define STATE_BITBUCKET 5
128 #define OP_UNKNOWN 0
129 #define OP_PUT 1
130 #define OP_PEEKJOB 2
131 #define OP_RESERVE 3
132 #define OP_DELETE 4
133 #define OP_RELEASE 5
134 #define OP_BURY 6
135 #define OP_KICK 7
136 #define OP_STATS 8
137 #define OP_JOBSTATS 9
138 #define OP_PEEK_BURIED 10
139 #define OP_USE 11
140 #define OP_WATCH 12
141 #define OP_IGNORE 13
142 #define OP_LIST_TUBES 14
143 #define OP_LIST_TUBE_USED 15
144 #define OP_LIST_TUBES_WATCHED 16
145 #define OP_STATS_TUBE 17
146 #define OP_PEEK_READY 18
147 #define OP_PEEK_DELAYED 19
148 #define OP_RESERVE_TIMEOUT 20
149 #define OP_TOUCH 21
150 #define TOTAL_OPS 22
152 #define STATS_FMT "---\n" \
153 "current-jobs-urgent: %u\n" \
154 "current-jobs-ready: %u\n" \
155 "current-jobs-reserved: %u\n" \
156 "current-jobs-delayed: %u\n" \
157 "current-jobs-buried: %u\n" \
158 "cmd-put: %llu\n" \
159 "cmd-peek: %llu\n" \
160 "cmd-peek-ready: %llu\n" \
161 "cmd-peek-delayed: %llu\n" \
162 "cmd-peek-buried: %llu\n" \
163 "cmd-reserve: %llu\n" \
164 "cmd-reserve-with-timeout: %llu\n" \
165 "cmd-delete: %llu\n" \
166 "cmd-release: %llu\n" \
167 "cmd-use: %llu\n" \
168 "cmd-watch: %llu\n" \
169 "cmd-ignore: %llu\n" \
170 "cmd-bury: %llu\n" \
171 "cmd-kick: %llu\n" \
172 "cmd-touch: %llu\n" \
173 "cmd-stats: %llu\n" \
174 "cmd-stats-job: %llu\n" \
175 "cmd-stats-tube: %llu\n" \
176 "cmd-list-tubes: %llu\n" \
177 "cmd-list-tube-used: %llu\n" \
178 "cmd-list-tubes-watched: %llu\n" \
179 "job-timeouts: %llu\n" \
180 "total-jobs: %llu\n" \
181 "max-job-size: %zu\n" \
182 "current-tubes: %zu\n" \
183 "current-connections: %u\n" \
184 "current-producers: %u\n" \
185 "current-workers: %u\n" \
186 "current-waiting: %u\n" \
187 "total-connections: %u\n" \
188 "pid: %u\n" \
189 "version: %s\n" \
190 "rusage-utime: %d.%06d\n" \
191 "rusage-stime: %d.%06d\n" \
192 "uptime: %u\n" \
193 "\r\n"
195 #define STATS_TUBE_FMT "---\n" \
196 "name: %s\n" \
197 "current-jobs-urgent: %u\n" \
198 "current-jobs-ready: %u\n" \
199 "current-jobs-reserved: %u\n" \
200 "current-jobs-delayed: %u\n" \
201 "current-jobs-buried: %u\n" \
202 "total-jobs: %llu\n" \
203 "current-using: %u\n" \
204 "current-watching: %u\n" \
205 "current-waiting: %u\n" \
206 "\r\n"
208 #define JOB_STATS_FMT "---\n" \
209 "id: %llu\n" \
210 "tube: %s\n" \
211 "state: %s\n" \
212 "pri: %u\n" \
213 "age: %u\n" \
214 "delay: %u\n" \
215 "ttr: %u\n" \
216 "time-left: %u\n" \
217 "timeouts: %u\n" \
218 "releases: %u\n" \
219 "buries: %u\n" \
220 "kicks: %u\n" \
221 "\r\n"
223 /* this number is pretty arbitrary */
224 #define BUCKET_BUF_SIZE 1024
226 static char bucket[BUCKET_BUF_SIZE];
228 static unsigned int ready_ct = 0;
229 static struct stats global_stat = {0, 0, 0, 0, 0};
231 static tube default_tube;
233 static int drain_mode = 0;
234 static time_t start_time;
235 static unsigned long long int op_ct[TOTAL_OPS], timeout_ct = 0;
238 /* Doubly-linked list of connections with at least one reserved job. */
239 static struct conn running = { &running, &running, 0 };
241 #ifdef DEBUG
242 static const char * op_names[] = {
243 "<unknown>",
244 CMD_PUT,
245 CMD_PEEKJOB,
246 CMD_RESERVE,
247 CMD_DELETE,
248 CMD_RELEASE,
249 CMD_BURY,
250 CMD_KICK,
251 CMD_STATS,
252 CMD_JOBSTATS,
253 CMD_PEEK_BURIED,
254 CMD_USE,
255 CMD_WATCH,
256 CMD_IGNORE,
257 CMD_LIST_TUBES,
258 CMD_LIST_TUBE_USED,
259 CMD_LIST_TUBES_WATCHED,
260 CMD_STATS_TUBE,
261 CMD_PEEK_READY,
262 CMD_PEEK_DELAYED,
263 CMD_RESERVE_TIMEOUT,
264 CMD_TOUCH
266 #endif
268 static int
269 buried_job_p(tube t)
271 return job_list_any_p(&t->buried);
274 static void
275 reply(conn c, const char *line, int len, int state)
277 int r;
279 if (!c) return;
281 r = conn_update_evq(c, EV_WRITE | EV_PERSIST);
282 if (r == -1) return twarnx("conn_update_evq() failed"), conn_close(c);
284 c->reply = line;
285 c->reply_len = len;
286 c->reply_sent = 0;
287 c->state = state;
288 dprintf("sending reply: %.*s", len, line);
291 #define reply_msg(c,m) reply((c),(m),CONSTSTRLEN(m),STATE_SENDWORD)
293 #define reply_serr(c,e) (twarnx("server error: %s",(e)),\
294 reply_msg((c),(e)))
296 static void
297 reply_line(conn c, int state, const char *fmt, ...)
299 int r;
300 va_list ap;
302 va_start(ap, fmt);
303 r = vsnprintf(c->reply_buf, LINE_BUF_SIZE, fmt, ap);
304 va_end(ap);
306 /* Make sure the buffer was big enough. If not, we have a bug. */
307 if (r >= LINE_BUF_SIZE) return reply_serr(c, MSG_INTERNAL_ERROR);
309 return reply(c, c->reply_buf, r, state);
312 static void
313 reply_job(conn c, job j, const char *word)
315 /* tell this connection which job to send */
316 c->out_job = j;
317 c->out_job_sent = 0;
319 return reply_line(c, STATE_SENDJOB, "%s %llu %u\r\n",
320 word, j->id, j->body_size - 2);
323 conn
324 remove_waiting_conn(conn c)
326 tube t;
327 size_t i;
329 if (!conn_waiting(c)) return NULL;
331 c->type &= ~CONN_TYPE_WAITING;
332 global_stat.waiting_ct--;
333 for (i = 0; i < c->watch.used; i++) {
334 t = c->watch.items[i];
335 t->stat.waiting_ct--;
336 ms_remove(&t->waiting, c);
338 return c;
341 static void
342 reserve_job(conn c, job j)
344 j->deadline = time(NULL) + j->ttr;
345 global_stat.reserved_ct++; /* stats */
346 j->tube->stat.reserved_ct++;
347 conn_insert(&running, c);
348 j->state = JOB_STATE_RESERVED;
349 job_insert(&c->reserved_jobs, j);
350 j->reserver = c;
351 if (c->soonest_job && j->deadline < c->soonest_job->deadline) {
352 c->soonest_job = j;
354 return reply_job(c, j, MSG_RESERVED);
357 static job
358 next_eligible_job()
360 tube t;
361 size_t i;
362 job j = NULL, candidate;
364 dprintf("tubes.used = %zu\n", tubes.used);
365 for (i = 0; i < tubes.used; i++) {
366 t = tubes.items[i];
367 dprintf("for %s t->waiting.used=%zu t->ready.used=%d\n",
368 t->name, t->waiting.used, t->ready.used);
369 if (t->waiting.used && t->ready.used) {
370 candidate = pq_peek(&t->ready);
371 if (!j || candidate->id < j->id) j = candidate;
373 dprintf("i = %zu, tubes.used = %zu\n", i, tubes.used);
376 return j;
379 static void
380 process_queue()
382 job j;
384 dprintf("processing queue\n");
385 while ((j = next_eligible_job())) {
386 dprintf("got eligible job %llu in %s\n", j->id, j->tube->name);
387 j = pq_take(&j->tube->ready);
388 ready_ct--;
389 if (j->pri < URGENT_THRESHOLD) {
390 global_stat.urgent_ct--;
391 j->tube->stat.urgent_ct--;
393 reserve_job(remove_waiting_conn(ms_take(&j->tube->waiting)), j);
397 static job
398 delay_q_peek()
400 int i;
401 tube t;
402 job j = NULL, nj;
404 for (i = 0; i < tubes.used; i++) {
405 t = tubes.items[i];
406 nj = pq_peek(&t->delay);
407 if (!nj) continue;
408 if (!j || nj->deadline < j->deadline) j = nj;
411 return j;
414 static void
415 set_main_delay_timeout()
417 job j;
419 set_main_timeout((j = delay_q_peek()) ? j->deadline : 0);
422 static int
423 enqueue_job(job j, unsigned int delay)
425 int r;
427 j->reserver = NULL;
428 if (delay) {
429 j->deadline = time(NULL) + delay;
430 r = pq_give(&j->tube->delay, j);
431 if (!r) return 0;
432 j->state = JOB_STATE_DELAYED;
433 set_main_delay_timeout();
434 } else {
435 r = pq_give(&j->tube->ready, j);
436 if (!r) return 0;
437 j->state = JOB_STATE_READY;
438 ready_ct++;
439 if (j->pri < URGENT_THRESHOLD) {
440 global_stat.urgent_ct++;
441 j->tube->stat.urgent_ct++;
444 binlog_write_job(j);
445 process_queue();
446 return 1;
449 static void
450 bury_job(job j)
452 job_insert(&j->tube->buried, j);
453 global_stat.buried_ct++;
454 j->tube->stat.buried_ct++;
455 j->state = JOB_STATE_BURIED;
456 j->reserver = NULL;
457 j->bury_ct++;
458 binlog_write_job(j);
461 void
462 enqueue_reserved_jobs(conn c)
464 int r;
465 job j;
467 while (job_list_any_p(&c->reserved_jobs)) {
468 j = job_remove(c->reserved_jobs.next);
469 r = enqueue_job(j, 0);
470 if (!r) bury_job(j);
471 global_stat.reserved_ct--;
472 j->tube->stat.reserved_ct--;
473 c->soonest_job = NULL;
474 if (!job_list_any_p(&c->reserved_jobs)) conn_remove(c);
478 static job
479 delay_q_take()
481 job j = delay_q_peek();
482 return j ? pq_take(&j->tube->delay) : NULL;
485 static job
486 remove_this_buried_job(job j)
488 j = job_remove(j);
489 if (j) {
490 global_stat.buried_ct--;
491 j->tube->stat.buried_ct--;
493 return j;
496 static int
497 kick_buried_job(tube t)
499 int r;
500 job j;
502 if (!buried_job_p(t)) return 0;
503 j = remove_this_buried_job(t->buried.next);
504 j->kick_ct++;
505 r = enqueue_job(j, 0);
506 if (r) return 1;
508 /* ready queue is full, so bury it */
509 bury_job(j);
510 return 0;
513 static unsigned int
514 get_delayed_job_ct()
516 tube t;
517 size_t i;
518 unsigned int count = 0;
520 for (i = 0; i < tubes.used; i++) {
521 t = tubes.items[i];
522 count += pq_used(&t->delay);
524 return count;
527 static int
528 kick_delayed_job(tube t)
530 int r;
531 job j;
533 j = pq_take(&t->delay);
534 if (!j) return 0;
535 j->kick_ct++;
536 r = enqueue_job(j, 0);
537 if (r) return 1;
539 /* ready queue is full, so delay it again */
540 r = enqueue_job(j, j->delay);
541 if (r) return 0;
543 /* last resort */
544 bury_job(j);
545 return 0;
548 /* return the number of jobs successfully kicked */
549 static unsigned int
550 kick_buried_jobs(tube t, unsigned int n)
552 unsigned int i;
553 for (i = 0; (i < n) && kick_buried_job(t); ++i);
554 return i;
557 /* return the number of jobs successfully kicked */
558 static unsigned int
559 kick_delayed_jobs(tube t, unsigned int n)
561 unsigned int i;
562 for (i = 0; (i < n) && kick_delayed_job(t); ++i);
563 return i;
566 static unsigned int
567 kick_jobs(tube t, unsigned int n)
569 if (buried_job_p(t)) return kick_buried_jobs(t, n);
570 return kick_delayed_jobs(t, n);
573 static job
574 find_buried_job(unsigned long long int id)
576 job j = job_find(id);
577 return (j && j->state == JOB_STATE_BURIED) ? j : NULL;
580 static job
581 remove_buried_job(unsigned long long int id)
583 return remove_this_buried_job(find_buried_job(id));
586 static void
587 enqueue_waiting_conn(conn c)
589 tube t;
590 size_t i;
592 global_stat.waiting_ct++;
593 c->type |= CONN_TYPE_WAITING;
594 for (i = 0; i < c->watch.used; i++) {
595 t = c->watch.items[i];
596 t->stat.waiting_ct++;
597 ms_append(&t->waiting, c);
601 static job
602 find_reserved_job_in_conn(conn c, unsigned long long int id)
604 job j = job_find(id);
605 return (j && j->reserver == c && j->state == JOB_STATE_RESERVED) ? j : NULL;
608 static job
609 touch_job(conn c, unsigned long long int id)
611 job j = find_reserved_job_in_conn(c, id);
612 if (j) {
613 j->deadline = time(NULL) + j->ttr;
614 c->soonest_job = NULL;
616 return j;
619 static job
620 peek_job(unsigned long long int id)
622 return job_find(id);
625 static void
626 check_err(conn c, const char *s)
628 if (errno == EAGAIN) return;
629 if (errno == EINTR) return;
630 if (errno == EWOULDBLOCK) return;
632 twarn("%s", s);
633 conn_close(c);
634 return;
637 /* Scan the given string for the sequence "\r\n" and return the line length.
638 * Always returns at least 2 if a match is found. Returns 0 if no match. */
639 static int
640 scan_line_end(const char *s, int size)
642 char *match;
644 match = memchr(s, '\r', size - 1);
645 if (!match) return 0;
647 /* this is safe because we only scan size - 1 chars above */
648 if (match[1] == '\n') return match - s + 2;
650 return 0;
653 static int
654 cmd_len(conn c)
656 return scan_line_end(c->cmd, c->cmd_read);
659 /* parse the command line */
660 static int
661 which_cmd(conn c)
663 #define TEST_CMD(s,c,o) if (strncmp((s), (c), CONSTSTRLEN(c)) == 0) return (o);
664 TEST_CMD(c->cmd, CMD_PUT, OP_PUT);
665 TEST_CMD(c->cmd, CMD_PEEKJOB, OP_PEEKJOB);
666 TEST_CMD(c->cmd, CMD_PEEK_READY, OP_PEEK_READY);
667 TEST_CMD(c->cmd, CMD_PEEK_DELAYED, OP_PEEK_DELAYED);
668 TEST_CMD(c->cmd, CMD_PEEK_BURIED, OP_PEEK_BURIED);
669 TEST_CMD(c->cmd, CMD_RESERVE_TIMEOUT, OP_RESERVE_TIMEOUT);
670 TEST_CMD(c->cmd, CMD_RESERVE, OP_RESERVE);
671 TEST_CMD(c->cmd, CMD_DELETE, OP_DELETE);
672 TEST_CMD(c->cmd, CMD_RELEASE, OP_RELEASE);
673 TEST_CMD(c->cmd, CMD_BURY, OP_BURY);
674 TEST_CMD(c->cmd, CMD_KICK, OP_KICK);
675 TEST_CMD(c->cmd, CMD_TOUCH, OP_TOUCH);
676 TEST_CMD(c->cmd, CMD_JOBSTATS, OP_JOBSTATS);
677 TEST_CMD(c->cmd, CMD_STATS_TUBE, OP_STATS_TUBE);
678 TEST_CMD(c->cmd, CMD_STATS, OP_STATS);
679 TEST_CMD(c->cmd, CMD_USE, OP_USE);
680 TEST_CMD(c->cmd, CMD_WATCH, OP_WATCH);
681 TEST_CMD(c->cmd, CMD_IGNORE, OP_IGNORE);
682 TEST_CMD(c->cmd, CMD_LIST_TUBES_WATCHED, OP_LIST_TUBES_WATCHED);
683 TEST_CMD(c->cmd, CMD_LIST_TUBE_USED, OP_LIST_TUBE_USED);
684 TEST_CMD(c->cmd, CMD_LIST_TUBES, OP_LIST_TUBES);
685 return OP_UNKNOWN;
688 /* Copy up to body_size trailing bytes into the job, then the rest into the cmd
689 * buffer. If c->in_job exists, this assumes that c->in_job->body is empty.
690 * This function is idempotent(). */
691 static void
692 fill_extra_data(conn c)
694 int extra_bytes, job_data_bytes = 0, cmd_bytes;
696 if (!c->fd) return; /* the connection was closed */
697 if (!c->cmd_len) return; /* we don't have a complete command */
699 /* how many extra bytes did we read? */
700 extra_bytes = c->cmd_read - c->cmd_len;
702 /* how many bytes should we put into the job body? */
703 if (c->in_job) {
704 job_data_bytes = min(extra_bytes, c->in_job->body_size);
705 memcpy(c->in_job->body, c->cmd + c->cmd_len, job_data_bytes);
706 c->in_job_read = job_data_bytes;
707 } else if (c->in_job_read) {
708 /* we are in bit-bucket mode, throwing away data */
709 job_data_bytes = min(extra_bytes, c->in_job_read);
710 c->in_job_read -= job_data_bytes;
713 /* how many bytes are left to go into the future cmd? */
714 cmd_bytes = extra_bytes - job_data_bytes;
715 memmove(c->cmd, c->cmd + c->cmd_len + job_data_bytes, cmd_bytes);
716 c->cmd_read = cmd_bytes;
717 c->cmd_len = 0; /* we no longer know the length of the new command */
720 static void
721 enqueue_incoming_job(conn c)
723 int r;
724 job j = c->in_job;
726 c->in_job = NULL; /* the connection no longer owns this job */
727 c->in_job_read = 0;
729 /* check if the trailer is present and correct */
730 if (memcmp(j->body + j->body_size - 2, "\r\n", 2)) {
731 job_free(j);
732 return reply_msg(c, MSG_EXPECTED_CRLF);
735 if (drain_mode) {
736 job_free(j);
737 return reply_serr(c, MSG_DRAINING);
740 /* we have a complete job, so let's stick it in the pqueue */
741 r = enqueue_job(j, j->delay);
742 op_ct[OP_PUT]++; /* stats */
743 global_stat.total_jobs_ct++;
744 j->tube->stat.total_jobs_ct++;
746 if (r) return reply_line(c, STATE_SENDWORD, MSG_INSERTED_FMT, j->id);
748 /* out of memory trying to grow the queue, so it gets buried */
749 bury_job(j);
750 reply_line(c, STATE_SENDWORD, MSG_BURIED_FMT, j->id);
753 static unsigned int
754 uptime()
756 return time(NULL) - start_time;
759 static int
760 fmt_stats(char *buf, size_t size, void *x)
762 struct rusage ru = {{0, 0}, {0, 0}};
763 getrusage(RUSAGE_SELF, &ru); /* don't care if it fails */
764 return snprintf(buf, size, STATS_FMT,
765 global_stat.urgent_ct,
766 ready_ct,
767 global_stat.reserved_ct,
768 get_delayed_job_ct(),
769 global_stat.buried_ct,
770 op_ct[OP_PUT],
771 op_ct[OP_PEEKJOB],
772 op_ct[OP_PEEK_READY],
773 op_ct[OP_PEEK_DELAYED],
774 op_ct[OP_PEEK_BURIED],
775 op_ct[OP_RESERVE],
776 op_ct[OP_RESERVE_TIMEOUT],
777 op_ct[OP_DELETE],
778 op_ct[OP_RELEASE],
779 op_ct[OP_USE],
780 op_ct[OP_WATCH],
781 op_ct[OP_IGNORE],
782 op_ct[OP_BURY],
783 op_ct[OP_KICK],
784 op_ct[OP_TOUCH],
785 op_ct[OP_STATS],
786 op_ct[OP_JOBSTATS],
787 op_ct[OP_STATS_TUBE],
788 op_ct[OP_LIST_TUBES],
789 op_ct[OP_LIST_TUBE_USED],
790 op_ct[OP_LIST_TUBES_WATCHED],
791 timeout_ct,
792 global_stat.total_jobs_ct,
793 job_data_size_limit,
794 tubes.used,
795 count_cur_conns(),
796 count_cur_producers(),
797 count_cur_workers(),
798 global_stat.waiting_ct,
799 count_tot_conns(),
800 getpid(),
801 BEAN_VERSION,
802 (int) ru.ru_utime.tv_sec, (int) ru.ru_utime.tv_usec,
803 (int) ru.ru_stime.tv_sec, (int) ru.ru_stime.tv_usec,
804 uptime());
808 /* Read a priority value from the given buffer and place it in pri.
809 * Update end to point to the address after the last character consumed.
810 * Pri and end can be NULL. If they are both NULL, read_pri() will do the
811 * conversion and return the status code but not update any values. This is an
812 * easy way to check for errors.
813 * If end is NULL, read_pri will also check that the entire input string was
814 * consumed and return an error code otherwise.
815 * Return 0 on success, or nonzero on failure.
816 * If a failure occurs, pri and end are not modified. */
817 static int
818 read_pri(unsigned int *pri, const char *buf, char **end)
820 char *tend;
821 unsigned int tpri;
823 errno = 0;
824 while (buf[0] == ' ') buf++;
825 if (!isdigit(buf[0])) return -1;
826 tpri = strtoul(buf, &tend, 10);
827 if (tend == buf) return -1;
828 if (errno && errno != ERANGE) return -1;
829 if (!end && tend[0] != '\0') return -1;
831 if (pri) *pri = tpri;
832 if (end) *end = tend;
833 return 0;
836 /* Read a delay value from the given buffer and place it in delay.
837 * The interface and behavior are the same as in read_pri(). */
838 static int
839 read_delay(unsigned int *delay, const char *buf, char **end)
841 time_t now = time(NULL);
842 unsigned int result;
843 result = read_pri(delay, buf, end);
844 if (result) return result;
845 return (now + *delay < now);
848 /* Read a timeout value from the given buffer and place it in ttr.
849 * The interface and behavior are the same as in read_pri(). */
850 static int
851 read_ttr(unsigned int *ttr, const char *buf, char **end)
853 return read_pri(ttr, buf, end);
856 static void
857 wait_for_job(conn c, int timeout)
859 int r;
861 c->state = STATE_WAIT;
862 enqueue_waiting_conn(c);
864 /* Set the pending timeout to the requested timeout amount */
865 c->pending_timeout = timeout;
867 /* this conn is waiting, but we want to know if they hang up */
868 r = conn_update_evq(c, EV_READ | EV_PERSIST);
869 if (r == -1) return twarnx("update events failed"), conn_close(c);
872 typedef int(*fmt_fn)(char *, size_t, void *);
874 static void
875 do_stats(conn c, fmt_fn fmt, void *data)
877 int r, stats_len;
879 /* first, measure how big a buffer we will need */
880 stats_len = fmt(NULL, 0, data) + 16;
882 c->out_job = allocate_job(stats_len); /* fake job to hold stats data */
883 if (!c->out_job) return reply_serr(c, MSG_OUT_OF_MEMORY);
885 /* now actually format the stats data */
886 r = fmt(c->out_job->body, stats_len, data);
887 /* and set the actual body size */
888 c->out_job->body_size = r;
889 if (r > stats_len) return reply_serr(c, MSG_INTERNAL_ERROR);
891 c->out_job_sent = 0;
892 return reply_line(c, STATE_SENDJOB, "OK %d\r\n", r - 2);
895 static void
896 do_list_tubes(conn c, ms l)
898 char *buf;
899 tube t;
900 size_t i, resp_z;
902 /* first, measure how big a buffer we will need */
903 resp_z = 6; /* initial "---\n" and final "\r\n" */
904 for (i = 0; i < l->used; i++) {
905 t = l->items[i];
906 resp_z += 3 + strlen(t->name); /* including "- " and "\n" */
909 c->out_job = allocate_job(resp_z); /* fake job to hold response data */
910 if (!c->out_job) return reply_serr(c, MSG_OUT_OF_MEMORY);
912 /* now actually format the response */
913 buf = c->out_job->body;
914 buf += snprintf(buf, 5, "---\n");
915 for (i = 0; i < l->used; i++) {
916 t = l->items[i];
917 buf += snprintf(buf, 4 + strlen(t->name), "- %s\n", t->name);
919 buf[0] = '\r';
920 buf[1] = '\n';
922 c->out_job_sent = 0;
923 return reply_line(c, STATE_SENDJOB, "OK %d\r\n", resp_z - 2);
926 static int
927 fmt_job_stats(char *buf, size_t size, job j)
929 time_t t;
931 t = time(NULL);
932 return snprintf(buf, size, JOB_STATS_FMT,
933 j->id,
934 j->tube->name,
935 job_state(j),
936 j->pri,
937 (unsigned int) (t - j->creation),
938 j->delay,
939 j->ttr,
940 (unsigned int) (j->deadline - t),
941 j->timeout_ct,
942 j->release_ct,
943 j->bury_ct,
944 j->kick_ct);
947 static int
948 fmt_stats_tube(char *buf, size_t size, tube t)
950 return snprintf(buf, size, STATS_TUBE_FMT,
951 t->name,
952 t->stat.urgent_ct,
953 t->ready.used,
954 t->stat.reserved_ct,
955 pq_used(&t->delay),
956 t->stat.buried_ct,
957 t->stat.total_jobs_ct,
958 t->using_ct,
959 t->watching_ct,
960 t->stat.waiting_ct);
963 static void
964 maybe_enqueue_incoming_job(conn c)
966 job j = c->in_job;
968 /* do we have a complete job? */
969 if (c->in_job_read == j->body_size) return enqueue_incoming_job(c);
971 /* otherwise we have incomplete data, so just keep waiting */
972 c->state = STATE_WANTDATA;
975 /* j can be NULL */
976 static job
977 remove_this_reserved_job(conn c, job j)
979 j = job_remove(j);
980 if (j) {
981 global_stat.reserved_ct--;
982 j->tube->stat.reserved_ct--;
983 j->reserver = NULL;
985 c->soonest_job = NULL;
986 if (!job_list_any_p(&c->reserved_jobs)) conn_remove(c);
987 return j;
990 static job
991 remove_reserved_job(conn c, unsigned long long int id)
993 return remove_this_reserved_job(c, find_reserved_job_in_conn(c, id));
996 static int
997 name_is_ok(const char *name, size_t max)
999 size_t len = strlen(name);
1000 return len > 0 && len <= max &&
1001 strspn(name, NAME_CHARS) == len && name[0] != '-';
1004 void
1005 prot_remove_tube(tube t)
1007 ms_remove(&tubes, t);
1010 static void
1011 dispatch_cmd(conn c)
1013 int r, i, timeout = -1;
1014 unsigned int count;
1015 job j;
1016 unsigned char type;
1017 char *size_buf, *delay_buf, *ttr_buf, *pri_buf, *end_buf, *name;
1018 unsigned int pri, delay, ttr, body_size;
1019 unsigned long long int id;
1020 tube t = NULL;
1022 /* NUL-terminate this string so we can use strtol and friends */
1023 c->cmd[c->cmd_len - 2] = '\0';
1025 /* check for possible maliciousness */
1026 if (strlen(c->cmd) != c->cmd_len - 2) {
1027 return reply_msg(c, MSG_BAD_FORMAT);
1030 type = which_cmd(c);
1031 dprintf("got %s command: \"%s\"\n", op_names[(int) type], c->cmd);
1033 switch (type) {
1034 case OP_PUT:
1035 r = read_pri(&pri, c->cmd + 4, &delay_buf);
1036 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1038 r = read_delay(&delay, delay_buf, &ttr_buf);
1039 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1041 r = read_ttr(&ttr, ttr_buf, &size_buf);
1042 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1044 errno = 0;
1045 body_size = strtoul(size_buf, &end_buf, 10);
1046 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1048 if (body_size > job_data_size_limit) {
1049 return reply_msg(c, MSG_JOB_TOO_BIG);
1052 /* don't allow trailing garbage */
1053 if (end_buf[0] != '\0') return reply_msg(c, MSG_BAD_FORMAT);
1055 conn_set_producer(c);
1057 c->in_job = make_job(pri, delay, ttr ? : 1, body_size + 2, c->use);
1059 /* OOM? */
1060 if (!c->in_job) {
1061 /* throw away the job body and respond with OUT_OF_MEMORY */
1063 /* Invert the meaning of in_job_read while throwing away data -- it
1064 * counts the bytes that remain to be thrown away. */
1065 c->in_job_read = body_size + 2;
1066 fill_extra_data(c);
1068 if (c->in_job_read == 0) return reply_serr(c, MSG_OUT_OF_MEMORY);
1070 c->state = STATE_BITBUCKET;
1071 return;
1074 fill_extra_data(c);
1076 /* it's possible we already have a complete job */
1077 maybe_enqueue_incoming_job(c);
1079 break;
1080 case OP_PEEK_READY:
1081 /* don't allow trailing garbage */
1082 if (c->cmd_len != CMD_PEEK_READY_LEN + 2) {
1083 return reply_msg(c, MSG_BAD_FORMAT);
1085 op_ct[type]++;
1087 j = job_copy(pq_peek(&c->use->ready));
1089 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1091 reply_job(c, j, MSG_FOUND);
1092 break;
1093 case OP_PEEK_DELAYED:
1094 /* don't allow trailing garbage */
1095 if (c->cmd_len != CMD_PEEK_DELAYED_LEN + 2) {
1096 return reply_msg(c, MSG_BAD_FORMAT);
1098 op_ct[type]++;
1100 j = job_copy(pq_peek(&c->use->delay));
1102 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1104 reply_job(c, j, MSG_FOUND);
1105 break;
1106 case OP_PEEK_BURIED:
1107 /* don't allow trailing garbage */
1108 if (c->cmd_len != CMD_PEEK_BURIED_LEN + 2) {
1109 return reply_msg(c, MSG_BAD_FORMAT);
1111 op_ct[type]++;
1113 j = job_copy(buried_job_p(c->use)? j = c->use->buried.next : NULL);
1115 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1117 reply_job(c, j, MSG_FOUND);
1118 break;
1119 case OP_PEEKJOB:
1120 errno = 0;
1121 id = strtoull(c->cmd + CMD_PEEKJOB_LEN, &end_buf, 10);
1122 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1123 op_ct[type]++;
1125 /* So, peek is annoying, because some other connection might free the
1126 * job while we are still trying to write it out. So we copy it and
1127 * then free the copy when it's done sending. */
1128 j = job_copy(peek_job(id));
1130 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1132 reply_job(c, j, MSG_FOUND);
1133 break;
1134 case OP_RESERVE_TIMEOUT:
1135 errno = 0;
1136 timeout = strtol(c->cmd + CMD_RESERVE_TIMEOUT_LEN, &end_buf, 10);
1137 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1138 case OP_RESERVE: /* FALLTHROUGH */
1139 /* don't allow trailing garbage */
1140 if (type == OP_RESERVE && c->cmd_len != CMD_RESERVE_LEN + 2) {
1141 return reply_msg(c, MSG_BAD_FORMAT);
1144 op_ct[type]++;
1145 conn_set_worker(c);
1147 if (conn_has_close_deadline(c) && !conn_ready(c)) {
1148 return reply_msg(c, MSG_DEADLINE_SOON);
1151 /* try to get a new job for this guy */
1152 wait_for_job(c, timeout);
1153 process_queue();
1154 break;
1155 case OP_DELETE:
1156 errno = 0;
1157 id = strtoull(c->cmd + CMD_DELETE_LEN, &end_buf, 10);
1158 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1159 op_ct[type]++;
1161 j = remove_reserved_job(c, id) ? : remove_buried_job(id);
1163 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1165 j->state = JOB_STATE_INVALID;
1166 binlog_write_job(j);
1167 job_free(j);
1169 reply(c, MSG_DELETED, MSG_DELETED_LEN, STATE_SENDWORD);
1170 break;
1171 case OP_RELEASE:
1172 errno = 0;
1173 id = strtoull(c->cmd + CMD_RELEASE_LEN, &pri_buf, 10);
1174 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1176 r = read_pri(&pri, pri_buf, &delay_buf);
1177 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1179 r = read_delay(&delay, delay_buf, NULL);
1180 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1181 op_ct[type]++;
1183 j = remove_reserved_job(c, id);
1185 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1187 j->pri = pri;
1188 j->delay = delay;
1189 j->release_ct++;
1190 r = enqueue_job(j, delay);
1191 if (r) return reply(c, MSG_RELEASED, MSG_RELEASED_LEN, STATE_SENDWORD);
1193 /* out of memory trying to grow the queue, so it gets buried */
1194 bury_job(j);
1195 reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD);
1196 break;
1197 case OP_BURY:
1198 errno = 0;
1199 id = strtoull(c->cmd + CMD_BURY_LEN, &pri_buf, 10);
1200 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1202 r = read_pri(&pri, pri_buf, NULL);
1203 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1204 op_ct[type]++;
1206 j = remove_reserved_job(c, id);
1208 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1210 j->pri = pri;
1211 bury_job(j);
1212 reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD);
1213 break;
1214 case OP_KICK:
1215 errno = 0;
1216 count = strtoul(c->cmd + CMD_KICK_LEN, &end_buf, 10);
1217 if (end_buf == c->cmd + CMD_KICK_LEN) {
1218 return reply_msg(c, MSG_BAD_FORMAT);
1220 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1222 op_ct[type]++;
1224 i = kick_jobs(c->use, count);
1226 return reply_line(c, STATE_SENDWORD, "KICKED %u\r\n", i);
1227 case OP_TOUCH:
1228 errno = 0;
1229 id = strtoull(c->cmd + CMD_TOUCH_LEN, &end_buf, 10);
1230 if (errno) return twarn("strtoull"), reply_msg(c, MSG_BAD_FORMAT);
1232 op_ct[type]++;
1234 j = touch_job(c, id);
1236 if (j) {
1237 reply(c, MSG_TOUCHED, MSG_TOUCHED_LEN, STATE_SENDWORD);
1238 } else {
1239 return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1241 break;
1242 case OP_STATS:
1243 /* don't allow trailing garbage */
1244 if (c->cmd_len != CMD_STATS_LEN + 2) {
1245 return reply_msg(c, MSG_BAD_FORMAT);
1248 op_ct[type]++;
1250 do_stats(c, fmt_stats, NULL);
1251 break;
1252 case OP_JOBSTATS:
1253 errno = 0;
1254 id = strtoull(c->cmd + CMD_JOBSTATS_LEN, &end_buf, 10);
1255 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1257 op_ct[type]++;
1259 j = peek_job(id);
1260 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1262 if (!j->tube) return reply_serr(c, MSG_INTERNAL_ERROR);
1263 do_stats(c, (fmt_fn) fmt_job_stats, j);
1264 break;
1265 case OP_STATS_TUBE:
1266 name = c->cmd + CMD_STATS_TUBE_LEN;
1267 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1269 op_ct[type]++;
1271 t = tube_find(name);
1272 if (!t) return reply_msg(c, MSG_NOTFOUND);
1274 do_stats(c, (fmt_fn) fmt_stats_tube, t);
1275 t = NULL;
1276 break;
1277 case OP_LIST_TUBES:
1278 /* don't allow trailing garbage */
1279 if (c->cmd_len != CMD_LIST_TUBES_LEN + 2) {
1280 return reply_msg(c, MSG_BAD_FORMAT);
1283 op_ct[type]++;
1284 do_list_tubes(c, &tubes);
1285 break;
1286 case OP_LIST_TUBE_USED:
1287 /* don't allow trailing garbage */
1288 if (c->cmd_len != CMD_LIST_TUBE_USED_LEN + 2) {
1289 return reply_msg(c, MSG_BAD_FORMAT);
1292 op_ct[type]++;
1293 reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name);
1294 break;
1295 case OP_LIST_TUBES_WATCHED:
1296 /* don't allow trailing garbage */
1297 if (c->cmd_len != CMD_LIST_TUBES_WATCHED_LEN + 2) {
1298 return reply_msg(c, MSG_BAD_FORMAT);
1301 op_ct[type]++;
1302 do_list_tubes(c, &c->watch);
1303 break;
1304 case OP_USE:
1305 name = c->cmd + CMD_USE_LEN;
1306 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1307 op_ct[type]++;
1309 TUBE_ASSIGN(t, tube_find_or_make(name));
1310 if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY);
1312 c->use->using_ct--;
1313 TUBE_ASSIGN(c->use, t);
1314 TUBE_ASSIGN(t, NULL);
1315 c->use->using_ct++;
1317 reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name);
1318 break;
1319 case OP_WATCH:
1320 name = c->cmd + CMD_WATCH_LEN;
1321 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1322 op_ct[type]++;
1324 TUBE_ASSIGN(t, tube_find_or_make(name));
1325 if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY);
1327 r = 1;
1328 if (!ms_contains(&c->watch, t)) r = ms_append(&c->watch, t);
1329 TUBE_ASSIGN(t, NULL);
1330 if (!r) return reply_serr(c, MSG_OUT_OF_MEMORY);
1332 reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used);
1333 break;
1334 case OP_IGNORE:
1335 name = c->cmd + CMD_IGNORE_LEN;
1336 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1337 op_ct[type]++;
1339 t = NULL;
1340 for (i = 0; i < c->watch.used; i++) {
1341 t = c->watch.items[i];
1342 if (strncmp(t->name, name, MAX_TUBE_NAME_LEN) == 0) break;
1343 t = NULL;
1346 if (t && c->watch.used < 2) return reply_msg(c, MSG_NOT_IGNORED);
1348 if (t) ms_remove(&c->watch, t); /* may free t if refcount => 0 */
1349 t = NULL;
1351 reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used);
1352 break;
1353 default:
1354 return reply_msg(c, MSG_UNKNOWN_COMMAND);
1358 /* There are three reasons this function may be called. We need to check for
1359 * all of them.
1361 * 1. A reserved job has run out of time.
1362 * 2. A waiting client's reserved job has entered the safety margin.
1363 * 3. A waiting client's requested timeout has occurred.
1365 * If any of these happen, we must do the appropriate thing. */
1366 static void
1367 h_conn_timeout(conn c)
1369 int r, should_timeout = 0;
1370 job j;
1372 /* Check if the client was trying to reserve a job. */
1373 if (conn_waiting(c) && conn_has_close_deadline(c)) should_timeout = 1;
1375 /* Check if any reserved jobs have run out of time. We should do this
1376 * whether or not the client is waiting for a new reservation. */
1377 while ((j = soonest_job(c))) {
1378 if (j->deadline > time(NULL)) break;
1379 timeout_ct++; /* stats */
1380 j->timeout_ct++;
1381 r = enqueue_job(remove_this_reserved_job(c, j), 0);
1382 if (!r) bury_job(j); /* there was no room in the queue, so bury it */
1383 r = conn_update_evq(c, c->evq.ev_events);
1384 if (r == -1) return twarnx("conn_update_evq() failed"), conn_close(c);
1387 if (should_timeout) {
1388 dprintf("conn_waiting(%p) = %d\n", c, conn_waiting(c));
1389 return reply_msg(remove_waiting_conn(c), MSG_DEADLINE_SOON);
1390 } else if (conn_waiting(c) && c->pending_timeout >= 0) {
1391 dprintf("conn_waiting(%p) = %d\n", c, conn_waiting(c));
1392 c->pending_timeout = -1;
1393 return reply_msg(remove_waiting_conn(c), MSG_TIMED_OUT);
1397 void
1398 enter_drain_mode(int sig)
1400 drain_mode = 1;
1403 static void
1404 do_cmd(conn c)
1406 dispatch_cmd(c);
1407 fill_extra_data(c);
1410 static void
1411 reset_conn(conn c)
1413 int r;
1415 r = conn_update_evq(c, EV_READ | EV_PERSIST);
1416 if (r == -1) return twarnx("update events failed"), conn_close(c);
1418 /* was this a peek or stats command? */
1419 if (!has_reserved_this_job(c, c->out_job)) job_free(c->out_job);
1420 c->out_job = NULL;
1422 c->reply_sent = 0; /* now that we're done, reset this */
1423 c->state = STATE_WANTCOMMAND;
1426 static void
1427 h_conn_data(conn c)
1429 int r, to_read;
1430 job j;
1431 struct iovec iov[2];
1433 switch (c->state) {
1434 case STATE_WANTCOMMAND:
1435 r = read(c->fd, c->cmd + c->cmd_read, LINE_BUF_SIZE - c->cmd_read);
1436 if (r == -1) return check_err(c, "read()");
1437 if (r == 0) return conn_close(c); /* the client hung up */
1439 c->cmd_read += r; /* we got some bytes */
1441 c->cmd_len = cmd_len(c); /* find the EOL */
1443 /* yay, complete command line */
1444 if (c->cmd_len) return do_cmd(c);
1446 /* c->cmd_read > LINE_BUF_SIZE can't happen */
1448 /* command line too long? */
1449 if (c->cmd_read == LINE_BUF_SIZE) {
1450 c->cmd_read = 0; /* discard the input so far */
1451 return reply_msg(c, MSG_BAD_FORMAT);
1454 /* otherwise we have an incomplete line, so just keep waiting */
1455 break;
1456 case STATE_BITBUCKET:
1457 /* Invert the meaning of in_job_read while throwing away data -- it
1458 * counts the bytes that remain to be thrown away. */
1459 to_read = min(c->in_job_read, BUCKET_BUF_SIZE);
1460 r = read(c->fd, bucket, to_read);
1461 if (r == -1) return check_err(c, "read()");
1462 if (r == 0) return conn_close(c); /* the client hung up */
1464 c->in_job_read -= r; /* we got some bytes */
1466 /* (c->in_job_read < 0) can't happen */
1468 if (c->in_job_read == 0) return reply_serr(c, MSG_OUT_OF_MEMORY);
1469 break;
1470 case STATE_WANTDATA:
1471 j = c->in_job;
1473 r = read(c->fd, j->body + c->in_job_read, j->body_size -c->in_job_read);
1474 if (r == -1) return check_err(c, "read()");
1475 if (r == 0) return conn_close(c); /* the client hung up */
1477 c->in_job_read += r; /* we got some bytes */
1479 /* (j->in_job_read > j->body_size) can't happen */
1481 maybe_enqueue_incoming_job(c);
1482 break;
1483 case STATE_SENDWORD:
1484 r= write(c->fd, c->reply + c->reply_sent, c->reply_len - c->reply_sent);
1485 if (r == -1) return check_err(c, "write()");
1486 if (r == 0) return conn_close(c); /* the client hung up */
1488 c->reply_sent += r; /* we got some bytes */
1490 /* (c->reply_sent > c->reply_len) can't happen */
1492 if (c->reply_sent == c->reply_len) return reset_conn(c);
1494 /* otherwise we sent an incomplete reply, so just keep waiting */
1495 break;
1496 case STATE_SENDJOB:
1497 j = c->out_job;
1499 iov[0].iov_base = (void *)(c->reply + c->reply_sent);
1500 iov[0].iov_len = c->reply_len - c->reply_sent; /* maybe 0 */
1501 iov[1].iov_base = j->body + c->out_job_sent;
1502 iov[1].iov_len = j->body_size - c->out_job_sent;
1504 r = writev(c->fd, iov, 2);
1505 if (r == -1) return check_err(c, "writev()");
1506 if (r == 0) return conn_close(c); /* the client hung up */
1508 /* update the sent values */
1509 c->reply_sent += r;
1510 if (c->reply_sent >= c->reply_len) {
1511 c->out_job_sent += c->reply_sent - c->reply_len;
1512 c->reply_sent = c->reply_len;
1515 /* (c->out_job_sent > j->body_size) can't happen */
1517 /* are we done? */
1518 if (c->out_job_sent == j->body_size) return reset_conn(c);
1520 /* otherwise we sent incomplete data, so just keep waiting */
1521 break;
1522 case STATE_WAIT: /* keep an eye out in case they hang up */
1523 /* but don't hang up just because our buffer is full */
1524 if (LINE_BUF_SIZE - c->cmd_read < 1) break;
1526 r = read(c->fd, c->cmd + c->cmd_read, LINE_BUF_SIZE - c->cmd_read);
1527 if (r == -1) return check_err(c, "read()");
1528 if (r == 0) return conn_close(c); /* the client hung up */
1529 c->cmd_read += r; /* we got some bytes */
1533 #define want_command(c) ((c)->fd && ((c)->state == STATE_WANTCOMMAND))
1534 #define cmd_data_ready(c) (want_command(c) && (c)->cmd_read)
1536 static void
1537 h_conn(const int fd, const short which, conn c)
1539 if (fd != c->fd) {
1540 twarnx("Argh! event fd doesn't match conn fd.");
1541 close(fd);
1542 return conn_close(c);
1545 switch (which) {
1546 case EV_TIMEOUT:
1547 h_conn_timeout(c);
1548 event_add(&c->evq, NULL); /* seems to be necessary */
1549 break;
1550 case EV_READ:
1551 /* fall through... */
1552 case EV_WRITE:
1553 /* fall through... */
1554 default:
1555 h_conn_data(c);
1558 while (cmd_data_ready(c) && (c->cmd_len = cmd_len(c))) do_cmd(c);
1561 static void
1562 h_delay()
1564 int r;
1565 job j;
1566 time_t t;
1568 t = time(NULL);
1569 while ((j = delay_q_peek())) {
1570 if (j->deadline > t) break;
1571 j = delay_q_take();
1572 r = enqueue_job(j, 0);
1573 if (!r) bury_job(j); /* there was no room in the queue, so bury it */
1576 set_main_delay_timeout();
1579 void
1580 h_accept(const int fd, const short which, struct event *ev)
1582 conn c;
1583 int cfd, flags, r;
1584 socklen_t addrlen;
1585 struct sockaddr addr;
1587 if (which == EV_TIMEOUT) return h_delay();
1589 addrlen = sizeof addr;
1590 cfd = accept(fd, &addr, &addrlen);
1591 if (cfd == -1) {
1592 if (errno != EAGAIN && errno != EWOULDBLOCK) twarn("accept()");
1593 if (errno == EMFILE) brake();
1594 return;
1597 flags = fcntl(cfd, F_GETFL, 0);
1598 if (flags < 0) return twarn("getting flags"), close(cfd), v();
1600 r = fcntl(cfd, F_SETFL, flags | O_NONBLOCK);
1601 if (r < 0) return twarn("setting O_NONBLOCK"), close(cfd), v();
1603 c = make_conn(cfd, STATE_WANTCOMMAND, default_tube, default_tube);
1604 if (!c) return twarnx("make_conn() failed"), close(cfd), brake();
1606 dprintf("accepted conn, fd=%d\n", cfd);
1607 r = conn_set_evq(c, EV_READ | EV_PERSIST, (evh) h_conn);
1608 if (r == -1) return twarnx("conn_set_evq() failed"), close(cfd), brake();
1611 void
1612 prot_init()
1614 start_time = time(NULL);
1615 memset(op_ct, 0, sizeof(op_ct));
1617 ms_init(&tubes, NULL, NULL);
1619 TUBE_ASSIGN(default_tube, tube_find_or_make("default"));
1620 if (!default_tube) twarnx("Out of memory during startup!");
1623 void
1624 prot_replay_binlog()
1626 struct job binlog_jobs;
1627 job j, nj;
1628 unsigned int delay;
1630 binlog_jobs.prev = binlog_jobs.next = &binlog_jobs;
1631 binlog_read(&binlog_jobs);
1633 for (j = binlog_jobs.next ; j != &binlog_jobs ; j = nj) {
1634 nj = j->next;
1635 job_remove(j);
1636 delay = 0;
1637 switch (j->state) {
1638 case JOB_STATE_BURIED:
1639 bury_job(j);
1640 break;
1641 case JOB_STATE_DELAYED:
1642 if (start_time < j->deadline) delay = j->deadline - start_time;
1643 /* fall through */
1644 default:
1645 enqueue_job(j,delay);