Don't keep a pointer to a job that might be freed.
[beanstalkd.git] / prot.c
blobcc20da030bed3f0431bd09a59e6108a75992a9f6
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 "config.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 "binlog-oldest-index: %s\n" \
194 "binlog-current-index: %s\n" \
195 "binlog-max-size: %u\n" \
196 "\r\n"
198 #define STATS_TUBE_FMT "---\n" \
199 "name: %s\n" \
200 "current-jobs-urgent: %u\n" \
201 "current-jobs-ready: %u\n" \
202 "current-jobs-reserved: %u\n" \
203 "current-jobs-delayed: %u\n" \
204 "current-jobs-buried: %u\n" \
205 "total-jobs: %llu\n" \
206 "current-using: %u\n" \
207 "current-watching: %u\n" \
208 "current-waiting: %u\n" \
209 "\r\n"
211 #define JOB_STATS_FMT "---\n" \
212 "id: %llu\n" \
213 "tube: %s\n" \
214 "state: %s\n" \
215 "pri: %u\n" \
216 "age: %u\n" \
217 "delay: %u\n" \
218 "ttr: %u\n" \
219 "time-left: %u\n" \
220 "timeouts: %u\n" \
221 "releases: %u\n" \
222 "buries: %u\n" \
223 "kicks: %u\n" \
224 "\r\n"
226 /* this number is pretty arbitrary */
227 #define BUCKET_BUF_SIZE 1024
229 static char bucket[BUCKET_BUF_SIZE];
231 static unsigned int ready_ct = 0;
232 static struct stats global_stat = {0, 0, 0, 0, 0};
234 static tube default_tube;
236 static int drain_mode = 0;
237 static time_t start_time;
238 static unsigned long long int op_ct[TOTAL_OPS], timeout_ct = 0;
241 /* Doubly-linked list of connections with at least one reserved job. */
242 static struct conn running = { &running, &running, 0 };
244 #ifdef DEBUG
245 static const char * op_names[] = {
246 "<unknown>",
247 CMD_PUT,
248 CMD_PEEKJOB,
249 CMD_RESERVE,
250 CMD_DELETE,
251 CMD_RELEASE,
252 CMD_BURY,
253 CMD_KICK,
254 CMD_STATS,
255 CMD_JOBSTATS,
256 CMD_PEEK_BURIED,
257 CMD_USE,
258 CMD_WATCH,
259 CMD_IGNORE,
260 CMD_LIST_TUBES,
261 CMD_LIST_TUBE_USED,
262 CMD_LIST_TUBES_WATCHED,
263 CMD_STATS_TUBE,
264 CMD_PEEK_READY,
265 CMD_PEEK_DELAYED,
266 CMD_RESERVE_TIMEOUT,
267 CMD_TOUCH
269 #endif
271 static job remove_buried_job(job j);
273 static int
274 buried_job_p(tube t)
276 return job_list_any_p(&t->buried);
279 static void
280 reply(conn c, const char *line, int len, int state)
282 int r;
284 if (!c) return;
286 r = conn_update_evq(c, EV_WRITE | EV_PERSIST);
287 if (r == -1) return twarnx("conn_update_evq() failed"), conn_close(c);
289 c->reply = line;
290 c->reply_len = len;
291 c->reply_sent = 0;
292 c->state = state;
293 dprintf("sending reply: %.*s", len, line);
296 #define reply_msg(c,m) reply((c),(m),CONSTSTRLEN(m),STATE_SENDWORD)
298 #define reply_serr(c,e) (twarnx("server error: %s",(e)),\
299 reply_msg((c),(e)))
301 static void
302 reply_line(conn c, int state, const char *fmt, ...)
304 int r;
305 va_list ap;
307 va_start(ap, fmt);
308 r = vsnprintf(c->reply_buf, LINE_BUF_SIZE, fmt, ap);
309 va_end(ap);
311 /* Make sure the buffer was big enough. If not, we have a bug. */
312 if (r >= LINE_BUF_SIZE) return reply_serr(c, MSG_INTERNAL_ERROR);
314 return reply(c, c->reply_buf, r, state);
317 static void
318 reply_job(conn c, job j, const char *word)
320 /* tell this connection which job to send */
321 c->out_job = j;
322 c->out_job_sent = 0;
324 return reply_line(c, STATE_SENDJOB, "%s %llu %u\r\n",
325 word, j->id, j->body_size - 2);
328 conn
329 remove_waiting_conn(conn c)
331 tube t;
332 size_t i;
334 if (!conn_waiting(c)) return NULL;
336 c->type &= ~CONN_TYPE_WAITING;
337 global_stat.waiting_ct--;
338 for (i = 0; i < c->watch.used; i++) {
339 t = c->watch.items[i];
340 t->stat.waiting_ct--;
341 ms_remove(&t->waiting, c);
343 return c;
346 static void
347 reserve_job(conn c, job j)
349 j->deadline = time(NULL) + j->ttr;
350 global_stat.reserved_ct++; /* stats */
351 j->tube->stat.reserved_ct++;
352 conn_insert(&running, c);
353 j->state = JOB_STATE_RESERVED;
354 job_insert(&c->reserved_jobs, j);
355 j->reserver = c;
356 if (c->soonest_job && j->deadline < c->soonest_job->deadline) {
357 c->soonest_job = j;
359 return reply_job(c, j, MSG_RESERVED);
362 static job
363 next_eligible_job()
365 tube t;
366 size_t i;
367 job j = NULL, candidate;
369 dprintf("tubes.used = %zu\n", tubes.used);
370 for (i = 0; i < tubes.used; i++) {
371 t = tubes.items[i];
372 dprintf("for %s t->waiting.used=%zu t->ready.used=%d\n",
373 t->name, t->waiting.used, t->ready.used);
374 if (t->waiting.used && t->ready.used) {
375 candidate = pq_peek(&t->ready);
376 if (!j || job_pri_cmp(candidate, j) < 0) j = candidate;
378 dprintf("i = %zu, tubes.used = %zu\n", i, tubes.used);
381 return j;
384 static void
385 process_queue()
387 job j;
389 dprintf("processing queue\n");
390 while ((j = next_eligible_job())) {
391 dprintf("got eligible job %llu in %s\n", j->id, j->tube->name);
392 j = pq_take(&j->tube->ready);
393 ready_ct--;
394 if (j->pri < URGENT_THRESHOLD) {
395 global_stat.urgent_ct--;
396 j->tube->stat.urgent_ct--;
398 reserve_job(remove_waiting_conn(ms_take(&j->tube->waiting)), j);
402 static job
403 delay_q_peek()
405 int i;
406 tube t;
407 job j = NULL, nj;
409 for (i = 0; i < tubes.used; i++) {
410 t = tubes.items[i];
411 nj = pq_peek(&t->delay);
412 if (!nj) continue;
413 if (!j || nj->deadline < j->deadline) j = nj;
416 return j;
419 static void
420 set_main_delay_timeout()
422 job j;
424 set_main_timeout((j = delay_q_peek()) ? j->deadline : 0);
427 static int
428 enqueue_job(job j, unsigned int delay)
430 int r;
432 j->reserver = NULL;
433 if (delay) {
434 j->deadline = time(NULL) + delay;
435 r = pq_give(&j->tube->delay, j);
436 if (!r) return 0;
437 j->state = JOB_STATE_DELAYED;
438 set_main_delay_timeout();
439 } else {
440 r = pq_give(&j->tube->ready, j);
441 if (!r) return 0;
442 j->state = JOB_STATE_READY;
443 ready_ct++;
444 if (j->pri < URGENT_THRESHOLD) {
445 global_stat.urgent_ct++;
446 j->tube->stat.urgent_ct++;
449 binlog_write_job(j);
450 process_queue();
451 return 1;
454 static void
455 bury_job(job j)
457 job_insert(&j->tube->buried, j);
458 global_stat.buried_ct++;
459 j->tube->stat.buried_ct++;
460 j->state = JOB_STATE_BURIED;
461 j->reserver = NULL;
462 j->bury_ct++;
463 binlog_write_job(j);
466 void
467 enqueue_reserved_jobs(conn c)
469 int r;
470 job j;
472 while (job_list_any_p(&c->reserved_jobs)) {
473 j = job_remove(c->reserved_jobs.next);
474 r = enqueue_job(j, 0);
475 if (!r) bury_job(j);
476 global_stat.reserved_ct--;
477 j->tube->stat.reserved_ct--;
478 c->soonest_job = NULL;
479 if (!job_list_any_p(&c->reserved_jobs)) conn_remove(c);
483 static job
484 delay_q_take()
486 job j = delay_q_peek();
487 return j ? pq_take(&j->tube->delay) : NULL;
490 static int
491 kick_buried_job(tube t)
493 int r;
494 job j;
496 if (!buried_job_p(t)) return 0;
497 j = remove_buried_job(t->buried.next);
498 j->kick_ct++;
499 r = enqueue_job(j, 0);
500 if (r) return 1;
502 /* ready queue is full, so bury it */
503 bury_job(j);
504 return 0;
507 static unsigned int
508 get_delayed_job_ct()
510 tube t;
511 size_t i;
512 unsigned int count = 0;
514 for (i = 0; i < tubes.used; i++) {
515 t = tubes.items[i];
516 count += t->delay.used;
518 return count;
521 static int
522 kick_delayed_job(tube t)
524 int r;
525 job j;
527 j = pq_take(&t->delay);
528 if (!j) return 0;
529 j->kick_ct++;
530 r = enqueue_job(j, 0);
531 if (r) return 1;
533 /* ready queue is full, so delay it again */
534 r = enqueue_job(j, j->delay);
535 if (r) return 0;
537 /* last resort */
538 bury_job(j);
539 return 0;
542 /* return the number of jobs successfully kicked */
543 static unsigned int
544 kick_buried_jobs(tube t, unsigned int n)
546 unsigned int i;
547 for (i = 0; (i < n) && kick_buried_job(t); ++i);
548 return i;
551 /* return the number of jobs successfully kicked */
552 static unsigned int
553 kick_delayed_jobs(tube t, unsigned int n)
555 unsigned int i;
556 for (i = 0; (i < n) && kick_delayed_job(t); ++i);
557 return i;
560 static unsigned int
561 kick_jobs(tube t, unsigned int n)
563 if (buried_job_p(t)) return kick_buried_jobs(t, n);
564 return kick_delayed_jobs(t, n);
567 static job
568 remove_buried_job(job j)
570 if (!j || j->state != JOB_STATE_BURIED) return NULL;
571 j = job_remove(j);
572 if (j) {
573 global_stat.buried_ct--;
574 j->tube->stat.buried_ct--;
576 return j;
579 static job
580 remove_ready_job(job j)
582 if (!j || j->state != JOB_STATE_READY) return NULL;
583 j = pq_remove(&j->tube->ready, j);
584 if (j) {
585 ready_ct--;
586 if (j->pri < URGENT_THRESHOLD) {
587 global_stat.urgent_ct--;
588 j->tube->stat.urgent_ct--;
591 return j;
594 static void
595 enqueue_waiting_conn(conn c)
597 tube t;
598 size_t i;
600 global_stat.waiting_ct++;
601 c->type |= CONN_TYPE_WAITING;
602 for (i = 0; i < c->watch.used; i++) {
603 t = c->watch.items[i];
604 t->stat.waiting_ct++;
605 ms_append(&t->waiting, c);
609 static job
610 find_reserved_job_in_conn(conn c, job j)
612 return (j && j->reserver == c && j->state == JOB_STATE_RESERVED) ? j : NULL;
615 static job
616 touch_job(conn c, job j)
618 j = find_reserved_job_in_conn(c, j);
619 if (j) {
620 j->deadline = time(NULL) + j->ttr;
621 c->soonest_job = NULL;
623 return j;
626 static job
627 peek_job(unsigned long long int id)
629 return job_find(id);
632 static void
633 check_err(conn c, const char *s)
635 if (errno == EAGAIN) return;
636 if (errno == EINTR) return;
637 if (errno == EWOULDBLOCK) return;
639 twarn("%s", s);
640 conn_close(c);
641 return;
644 /* Scan the given string for the sequence "\r\n" and return the line length.
645 * Always returns at least 2 if a match is found. Returns 0 if no match. */
646 static int
647 scan_line_end(const char *s, int size)
649 char *match;
651 match = memchr(s, '\r', size - 1);
652 if (!match) return 0;
654 /* this is safe because we only scan size - 1 chars above */
655 if (match[1] == '\n') return match - s + 2;
657 return 0;
660 static int
661 cmd_len(conn c)
663 return scan_line_end(c->cmd, c->cmd_read);
666 /* parse the command line */
667 static int
668 which_cmd(conn c)
670 #define TEST_CMD(s,c,o) if (strncmp((s), (c), CONSTSTRLEN(c)) == 0) return (o);
671 TEST_CMD(c->cmd, CMD_PUT, OP_PUT);
672 TEST_CMD(c->cmd, CMD_PEEKJOB, OP_PEEKJOB);
673 TEST_CMD(c->cmd, CMD_PEEK_READY, OP_PEEK_READY);
674 TEST_CMD(c->cmd, CMD_PEEK_DELAYED, OP_PEEK_DELAYED);
675 TEST_CMD(c->cmd, CMD_PEEK_BURIED, OP_PEEK_BURIED);
676 TEST_CMD(c->cmd, CMD_RESERVE_TIMEOUT, OP_RESERVE_TIMEOUT);
677 TEST_CMD(c->cmd, CMD_RESERVE, OP_RESERVE);
678 TEST_CMD(c->cmd, CMD_DELETE, OP_DELETE);
679 TEST_CMD(c->cmd, CMD_RELEASE, OP_RELEASE);
680 TEST_CMD(c->cmd, CMD_BURY, OP_BURY);
681 TEST_CMD(c->cmd, CMD_KICK, OP_KICK);
682 TEST_CMD(c->cmd, CMD_TOUCH, OP_TOUCH);
683 TEST_CMD(c->cmd, CMD_JOBSTATS, OP_JOBSTATS);
684 TEST_CMD(c->cmd, CMD_STATS_TUBE, OP_STATS_TUBE);
685 TEST_CMD(c->cmd, CMD_STATS, OP_STATS);
686 TEST_CMD(c->cmd, CMD_USE, OP_USE);
687 TEST_CMD(c->cmd, CMD_WATCH, OP_WATCH);
688 TEST_CMD(c->cmd, CMD_IGNORE, OP_IGNORE);
689 TEST_CMD(c->cmd, CMD_LIST_TUBES_WATCHED, OP_LIST_TUBES_WATCHED);
690 TEST_CMD(c->cmd, CMD_LIST_TUBE_USED, OP_LIST_TUBE_USED);
691 TEST_CMD(c->cmd, CMD_LIST_TUBES, OP_LIST_TUBES);
692 return OP_UNKNOWN;
695 /* Copy up to body_size trailing bytes into the job, then the rest into the cmd
696 * buffer. If c->in_job exists, this assumes that c->in_job->body is empty.
697 * This function is idempotent(). */
698 static void
699 fill_extra_data(conn c)
701 int extra_bytes, job_data_bytes = 0, cmd_bytes;
703 if (!c->fd) return; /* the connection was closed */
704 if (!c->cmd_len) return; /* we don't have a complete command */
706 /* how many extra bytes did we read? */
707 extra_bytes = c->cmd_read - c->cmd_len;
709 /* how many bytes should we put into the job body? */
710 if (c->in_job) {
711 job_data_bytes = min(extra_bytes, c->in_job->body_size);
712 memcpy(c->in_job->body, c->cmd + c->cmd_len, job_data_bytes);
713 c->in_job_read = job_data_bytes;
714 } else if (c->in_job_read) {
715 /* we are in bit-bucket mode, throwing away data */
716 job_data_bytes = min(extra_bytes, c->in_job_read);
717 c->in_job_read -= job_data_bytes;
720 /* how many bytes are left to go into the future cmd? */
721 cmd_bytes = extra_bytes - job_data_bytes;
722 memmove(c->cmd, c->cmd + c->cmd_len + job_data_bytes, cmd_bytes);
723 c->cmd_read = cmd_bytes;
724 c->cmd_len = 0; /* we no longer know the length of the new command */
727 static void
728 enqueue_incoming_job(conn c)
730 int r;
731 job j = c->in_job;
733 c->in_job = NULL; /* the connection no longer owns this job */
734 c->in_job_read = 0;
736 /* check if the trailer is present and correct */
737 if (memcmp(j->body + j->body_size - 2, "\r\n", 2)) {
738 job_free(j);
739 return reply_msg(c, MSG_EXPECTED_CRLF);
742 if (drain_mode) {
743 job_free(j);
744 return reply_serr(c, MSG_DRAINING);
747 /* we have a complete job, so let's stick it in the pqueue */
748 r = enqueue_job(j, j->delay);
749 op_ct[OP_PUT]++; /* stats */
750 global_stat.total_jobs_ct++;
751 j->tube->stat.total_jobs_ct++;
753 if (r) return reply_line(c, STATE_SENDWORD, MSG_INSERTED_FMT, j->id);
755 /* out of memory trying to grow the queue, so it gets buried */
756 bury_job(j);
757 reply_line(c, STATE_SENDWORD, MSG_BURIED_FMT, j->id);
760 static unsigned int
761 uptime()
763 return time(NULL) - start_time;
766 static int
767 fmt_stats(char *buf, size_t size, void *x)
769 struct rusage ru = {{0, 0}, {0, 0}};
770 getrusage(RUSAGE_SELF, &ru); /* don't care if it fails */
771 return snprintf(buf, size, STATS_FMT,
772 global_stat.urgent_ct,
773 ready_ct,
774 global_stat.reserved_ct,
775 get_delayed_job_ct(),
776 global_stat.buried_ct,
777 op_ct[OP_PUT],
778 op_ct[OP_PEEKJOB],
779 op_ct[OP_PEEK_READY],
780 op_ct[OP_PEEK_DELAYED],
781 op_ct[OP_PEEK_BURIED],
782 op_ct[OP_RESERVE],
783 op_ct[OP_RESERVE_TIMEOUT],
784 op_ct[OP_DELETE],
785 op_ct[OP_RELEASE],
786 op_ct[OP_USE],
787 op_ct[OP_WATCH],
788 op_ct[OP_IGNORE],
789 op_ct[OP_BURY],
790 op_ct[OP_KICK],
791 op_ct[OP_TOUCH],
792 op_ct[OP_STATS],
793 op_ct[OP_JOBSTATS],
794 op_ct[OP_STATS_TUBE],
795 op_ct[OP_LIST_TUBES],
796 op_ct[OP_LIST_TUBE_USED],
797 op_ct[OP_LIST_TUBES_WATCHED],
798 timeout_ct,
799 global_stat.total_jobs_ct,
800 job_data_size_limit,
801 tubes.used,
802 count_cur_conns(),
803 count_cur_producers(),
804 count_cur_workers(),
805 global_stat.waiting_ct,
806 count_tot_conns(),
807 getpid(),
808 VERSION,
809 (int) ru.ru_utime.tv_sec, (int) ru.ru_utime.tv_usec,
810 (int) ru.ru_stime.tv_sec, (int) ru.ru_stime.tv_usec,
811 uptime(),
812 binlog_oldest_index(),
813 binlog_current_index(),
814 binlog_size_limit);
818 /* Read a priority value from the given buffer and place it in pri.
819 * Update end to point to the address after the last character consumed.
820 * Pri and end can be NULL. If they are both NULL, read_pri() will do the
821 * conversion and return the status code but not update any values. This is an
822 * easy way to check for errors.
823 * If end is NULL, read_pri will also check that the entire input string was
824 * consumed and return an error code otherwise.
825 * Return 0 on success, or nonzero on failure.
826 * If a failure occurs, pri and end are not modified. */
827 static int
828 read_pri(unsigned int *pri, const char *buf, char **end)
830 char *tend;
831 unsigned int tpri;
833 errno = 0;
834 while (buf[0] == ' ') buf++;
835 if (!isdigit(buf[0])) return -1;
836 tpri = strtoul(buf, &tend, 10);
837 if (tend == buf) return -1;
838 if (errno && errno != ERANGE) return -1;
839 if (!end && tend[0] != '\0') return -1;
841 if (pri) *pri = tpri;
842 if (end) *end = tend;
843 return 0;
846 /* Read a delay value from the given buffer and place it in delay.
847 * The interface and behavior are the same as in read_pri(). */
848 static int
849 read_delay(unsigned int *delay, const char *buf, char **end)
851 time_t now = time(NULL);
852 return read_pri(delay, buf, end) ? : (now + *delay < now);
855 /* Read a timeout value from the given buffer and place it in ttr.
856 * The interface and behavior are the same as in read_pri(). */
857 static int
858 read_ttr(unsigned int *ttr, const char *buf, char **end)
860 return read_pri(ttr, buf, end);
863 static void
864 wait_for_job(conn c, int timeout)
866 int r;
868 c->state = STATE_WAIT;
869 enqueue_waiting_conn(c);
871 /* Set the pending timeout to the requested timeout amount */
872 c->pending_timeout = timeout;
874 /* this conn is waiting, but we want to know if they hang up */
875 r = conn_update_evq(c, EV_READ | EV_PERSIST);
876 if (r == -1) return twarnx("update events failed"), conn_close(c);
879 typedef int(*fmt_fn)(char *, size_t, void *);
881 static void
882 do_stats(conn c, fmt_fn fmt, void *data)
884 int r, stats_len;
886 /* first, measure how big a buffer we will need */
887 stats_len = fmt(NULL, 0, data) + 16;
889 c->out_job = allocate_job(stats_len); /* fake job to hold stats data */
890 if (!c->out_job) return reply_serr(c, MSG_OUT_OF_MEMORY);
892 /* now actually format the stats data */
893 r = fmt(c->out_job->body, stats_len, data);
894 /* and set the actual body size */
895 c->out_job->body_size = r;
896 if (r > stats_len) return reply_serr(c, MSG_INTERNAL_ERROR);
898 c->out_job_sent = 0;
899 return reply_line(c, STATE_SENDJOB, "OK %d\r\n", r - 2);
902 static void
903 do_list_tubes(conn c, ms l)
905 char *buf;
906 tube t;
907 size_t i, resp_z;
909 /* first, measure how big a buffer we will need */
910 resp_z = 6; /* initial "---\n" and final "\r\n" */
911 for (i = 0; i < l->used; i++) {
912 t = l->items[i];
913 resp_z += 3 + strlen(t->name); /* including "- " and "\n" */
916 c->out_job = allocate_job(resp_z); /* fake job to hold response data */
917 if (!c->out_job) return reply_serr(c, MSG_OUT_OF_MEMORY);
919 /* now actually format the response */
920 buf = c->out_job->body;
921 buf += snprintf(buf, 5, "---\n");
922 for (i = 0; i < l->used; i++) {
923 t = l->items[i];
924 buf += snprintf(buf, 4 + strlen(t->name), "- %s\n", t->name);
926 buf[0] = '\r';
927 buf[1] = '\n';
929 c->out_job_sent = 0;
930 return reply_line(c, STATE_SENDJOB, "OK %d\r\n", resp_z - 2);
933 static int
934 fmt_job_stats(char *buf, size_t size, job j)
936 time_t t;
938 t = time(NULL);
939 return snprintf(buf, size, JOB_STATS_FMT,
940 j->id,
941 j->tube->name,
942 job_state(j),
943 j->pri,
944 (unsigned int) (t - j->creation),
945 j->delay,
946 j->ttr,
947 (unsigned int) (j->deadline - t),
948 j->timeout_ct,
949 j->release_ct,
950 j->bury_ct,
951 j->kick_ct);
954 static int
955 fmt_stats_tube(char *buf, size_t size, tube t)
957 return snprintf(buf, size, STATS_TUBE_FMT,
958 t->name,
959 t->stat.urgent_ct,
960 t->ready.used,
961 t->stat.reserved_ct,
962 t->delay.used,
963 t->stat.buried_ct,
964 t->stat.total_jobs_ct,
965 t->using_ct,
966 t->watching_ct,
967 t->stat.waiting_ct);
970 static void
971 maybe_enqueue_incoming_job(conn c)
973 job j = c->in_job;
975 /* do we have a complete job? */
976 if (c->in_job_read == j->body_size) return enqueue_incoming_job(c);
978 /* otherwise we have incomplete data, so just keep waiting */
979 c->state = STATE_WANTDATA;
982 /* j can be NULL */
983 static job
984 remove_this_reserved_job(conn c, job j)
986 j = job_remove(j);
987 if (j) {
988 global_stat.reserved_ct--;
989 j->tube->stat.reserved_ct--;
990 j->reserver = NULL;
992 c->soonest_job = NULL;
993 if (!job_list_any_p(&c->reserved_jobs)) conn_remove(c);
994 return j;
997 static job
998 remove_reserved_job(conn c, job j)
1000 return remove_this_reserved_job(c, find_reserved_job_in_conn(c, j));
1003 static int
1004 name_is_ok(const char *name, size_t max)
1006 size_t len = strlen(name);
1007 return len > 0 && len <= max &&
1008 strspn(name, NAME_CHARS) == len && name[0] != '-';
1011 void
1012 prot_remove_tube(tube t)
1014 ms_remove(&tubes, t);
1017 static void
1018 dispatch_cmd(conn c)
1020 int r, i, timeout = -1;
1021 unsigned int count;
1022 job j;
1023 unsigned char type;
1024 char *size_buf, *delay_buf, *ttr_buf, *pri_buf, *end_buf, *name;
1025 unsigned int pri, delay, ttr, body_size;
1026 unsigned long long int id;
1027 tube t = NULL;
1029 /* NUL-terminate this string so we can use strtol and friends */
1030 c->cmd[c->cmd_len - 2] = '\0';
1032 /* check for possible maliciousness */
1033 if (strlen(c->cmd) != c->cmd_len - 2) {
1034 return reply_msg(c, MSG_BAD_FORMAT);
1037 type = which_cmd(c);
1038 dprintf("got %s command: \"%s\"\n", op_names[(int) type], c->cmd);
1040 switch (type) {
1041 case OP_PUT:
1042 r = read_pri(&pri, c->cmd + 4, &delay_buf);
1043 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1045 r = read_delay(&delay, delay_buf, &ttr_buf);
1046 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1048 r = read_ttr(&ttr, ttr_buf, &size_buf);
1049 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1051 errno = 0;
1052 body_size = strtoul(size_buf, &end_buf, 10);
1053 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1055 if (body_size > job_data_size_limit) {
1056 return reply_msg(c, MSG_JOB_TOO_BIG);
1059 /* don't allow trailing garbage */
1060 if (end_buf[0] != '\0') return reply_msg(c, MSG_BAD_FORMAT);
1062 conn_set_producer(c);
1064 c->in_job = make_job(pri, delay, ttr ? : 1, body_size + 2, c->use);
1066 /* OOM? */
1067 if (!c->in_job) {
1068 /* throw away the job body and respond with OUT_OF_MEMORY */
1070 /* Invert the meaning of in_job_read while throwing away data -- it
1071 * counts the bytes that remain to be thrown away. */
1072 c->in_job_read = body_size + 2;
1073 fill_extra_data(c);
1075 if (c->in_job_read == 0) return reply_serr(c, MSG_OUT_OF_MEMORY);
1077 c->state = STATE_BITBUCKET;
1078 return;
1081 fill_extra_data(c);
1083 /* it's possible we already have a complete job */
1084 maybe_enqueue_incoming_job(c);
1086 break;
1087 case OP_PEEK_READY:
1088 /* don't allow trailing garbage */
1089 if (c->cmd_len != CMD_PEEK_READY_LEN + 2) {
1090 return reply_msg(c, MSG_BAD_FORMAT);
1092 op_ct[type]++;
1094 j = job_copy(pq_peek(&c->use->ready));
1096 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1098 reply_job(c, j, MSG_FOUND);
1099 break;
1100 case OP_PEEK_DELAYED:
1101 /* don't allow trailing garbage */
1102 if (c->cmd_len != CMD_PEEK_DELAYED_LEN + 2) {
1103 return reply_msg(c, MSG_BAD_FORMAT);
1105 op_ct[type]++;
1107 j = job_copy(pq_peek(&c->use->delay));
1109 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1111 reply_job(c, j, MSG_FOUND);
1112 break;
1113 case OP_PEEK_BURIED:
1114 /* don't allow trailing garbage */
1115 if (c->cmd_len != CMD_PEEK_BURIED_LEN + 2) {
1116 return reply_msg(c, MSG_BAD_FORMAT);
1118 op_ct[type]++;
1120 j = job_copy(buried_job_p(c->use)? j = c->use->buried.next : NULL);
1122 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1124 reply_job(c, j, MSG_FOUND);
1125 break;
1126 case OP_PEEKJOB:
1127 errno = 0;
1128 id = strtoull(c->cmd + CMD_PEEKJOB_LEN, &end_buf, 10);
1129 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1130 op_ct[type]++;
1132 /* So, peek is annoying, because some other connection might free the
1133 * job while we are still trying to write it out. So we copy it and
1134 * then free the copy when it's done sending. */
1135 j = job_copy(peek_job(id));
1137 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1139 reply_job(c, j, MSG_FOUND);
1140 break;
1141 case OP_RESERVE_TIMEOUT:
1142 errno = 0;
1143 timeout = strtol(c->cmd + CMD_RESERVE_TIMEOUT_LEN, &end_buf, 10);
1144 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1145 case OP_RESERVE: /* FALLTHROUGH */
1146 /* don't allow trailing garbage */
1147 if (type == OP_RESERVE && c->cmd_len != CMD_RESERVE_LEN + 2) {
1148 return reply_msg(c, MSG_BAD_FORMAT);
1151 op_ct[type]++;
1152 conn_set_worker(c);
1154 if (conn_has_close_deadline(c) && !conn_ready(c)) {
1155 return reply_msg(c, MSG_DEADLINE_SOON);
1158 /* try to get a new job for this guy */
1159 wait_for_job(c, timeout);
1160 process_queue();
1161 break;
1162 case OP_DELETE:
1163 errno = 0;
1164 id = strtoull(c->cmd + CMD_DELETE_LEN, &end_buf, 10);
1165 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1166 op_ct[type]++;
1168 j = job_find(id);
1169 j = remove_reserved_job(c, j) ? :
1170 remove_ready_job(j) ? :
1171 remove_buried_job(j);
1173 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1175 j->state = JOB_STATE_INVALID;
1176 binlog_write_job(j);
1177 job_free(j);
1179 reply(c, MSG_DELETED, MSG_DELETED_LEN, STATE_SENDWORD);
1180 break;
1181 case OP_RELEASE:
1182 errno = 0;
1183 id = strtoull(c->cmd + CMD_RELEASE_LEN, &pri_buf, 10);
1184 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1186 r = read_pri(&pri, pri_buf, &delay_buf);
1187 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1189 r = read_delay(&delay, delay_buf, NULL);
1190 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1191 op_ct[type]++;
1193 j = remove_reserved_job(c, job_find(id));
1195 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1197 j->pri = pri;
1198 j->delay = delay;
1199 j->release_ct++;
1200 r = enqueue_job(j, delay);
1201 if (r) return reply(c, MSG_RELEASED, MSG_RELEASED_LEN, STATE_SENDWORD);
1203 /* out of memory trying to grow the queue, so it gets buried */
1204 bury_job(j);
1205 reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD);
1206 break;
1207 case OP_BURY:
1208 errno = 0;
1209 id = strtoull(c->cmd + CMD_BURY_LEN, &pri_buf, 10);
1210 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1212 r = read_pri(&pri, pri_buf, NULL);
1213 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1214 op_ct[type]++;
1216 j = remove_reserved_job(c, job_find(id));
1218 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1220 j->pri = pri;
1221 bury_job(j);
1222 reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD);
1223 break;
1224 case OP_KICK:
1225 errno = 0;
1226 count = strtoul(c->cmd + CMD_KICK_LEN, &end_buf, 10);
1227 if (end_buf == c->cmd + CMD_KICK_LEN) {
1228 return reply_msg(c, MSG_BAD_FORMAT);
1230 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1232 op_ct[type]++;
1234 i = kick_jobs(c->use, count);
1236 return reply_line(c, STATE_SENDWORD, "KICKED %u\r\n", i);
1237 case OP_TOUCH:
1238 errno = 0;
1239 id = strtoull(c->cmd + CMD_TOUCH_LEN, &end_buf, 10);
1240 if (errno) return twarn("strtoull"), reply_msg(c, MSG_BAD_FORMAT);
1242 op_ct[type]++;
1244 j = touch_job(c, job_find(id));
1246 if (j) {
1247 reply(c, MSG_TOUCHED, MSG_TOUCHED_LEN, STATE_SENDWORD);
1248 } else {
1249 return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1251 break;
1252 case OP_STATS:
1253 /* don't allow trailing garbage */
1254 if (c->cmd_len != CMD_STATS_LEN + 2) {
1255 return reply_msg(c, MSG_BAD_FORMAT);
1258 op_ct[type]++;
1260 do_stats(c, fmt_stats, NULL);
1261 break;
1262 case OP_JOBSTATS:
1263 errno = 0;
1264 id = strtoull(c->cmd + CMD_JOBSTATS_LEN, &end_buf, 10);
1265 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1267 op_ct[type]++;
1269 j = peek_job(id);
1270 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1272 if (!j->tube) return reply_serr(c, MSG_INTERNAL_ERROR);
1273 do_stats(c, (fmt_fn) fmt_job_stats, j);
1274 break;
1275 case OP_STATS_TUBE:
1276 name = c->cmd + CMD_STATS_TUBE_LEN;
1277 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1279 op_ct[type]++;
1281 t = tube_find(name);
1282 if (!t) return reply_msg(c, MSG_NOTFOUND);
1284 do_stats(c, (fmt_fn) fmt_stats_tube, t);
1285 t = NULL;
1286 break;
1287 case OP_LIST_TUBES:
1288 /* don't allow trailing garbage */
1289 if (c->cmd_len != CMD_LIST_TUBES_LEN + 2) {
1290 return reply_msg(c, MSG_BAD_FORMAT);
1293 op_ct[type]++;
1294 do_list_tubes(c, &tubes);
1295 break;
1296 case OP_LIST_TUBE_USED:
1297 /* don't allow trailing garbage */
1298 if (c->cmd_len != CMD_LIST_TUBE_USED_LEN + 2) {
1299 return reply_msg(c, MSG_BAD_FORMAT);
1302 op_ct[type]++;
1303 reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name);
1304 break;
1305 case OP_LIST_TUBES_WATCHED:
1306 /* don't allow trailing garbage */
1307 if (c->cmd_len != CMD_LIST_TUBES_WATCHED_LEN + 2) {
1308 return reply_msg(c, MSG_BAD_FORMAT);
1311 op_ct[type]++;
1312 do_list_tubes(c, &c->watch);
1313 break;
1314 case OP_USE:
1315 name = c->cmd + CMD_USE_LEN;
1316 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1317 op_ct[type]++;
1319 TUBE_ASSIGN(t, tube_find_or_make(name));
1320 if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY);
1322 c->use->using_ct--;
1323 TUBE_ASSIGN(c->use, t);
1324 TUBE_ASSIGN(t, NULL);
1325 c->use->using_ct++;
1327 reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name);
1328 break;
1329 case OP_WATCH:
1330 name = c->cmd + CMD_WATCH_LEN;
1331 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1332 op_ct[type]++;
1334 TUBE_ASSIGN(t, tube_find_or_make(name));
1335 if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY);
1337 r = 1;
1338 if (!ms_contains(&c->watch, t)) r = ms_append(&c->watch, t);
1339 TUBE_ASSIGN(t, NULL);
1340 if (!r) return reply_serr(c, MSG_OUT_OF_MEMORY);
1342 reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used);
1343 break;
1344 case OP_IGNORE:
1345 name = c->cmd + CMD_IGNORE_LEN;
1346 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1347 op_ct[type]++;
1349 t = NULL;
1350 for (i = 0; i < c->watch.used; i++) {
1351 t = c->watch.items[i];
1352 if (strncmp(t->name, name, MAX_TUBE_NAME_LEN) == 0) break;
1353 t = NULL;
1356 if (t && c->watch.used < 2) return reply_msg(c, MSG_NOT_IGNORED);
1358 if (t) ms_remove(&c->watch, t); /* may free t if refcount => 0 */
1359 t = NULL;
1361 reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used);
1362 break;
1363 default:
1364 return reply_msg(c, MSG_UNKNOWN_COMMAND);
1368 /* There are three reasons this function may be called. We need to check for
1369 * all of them.
1371 * 1. A reserved job has run out of time.
1372 * 2. A waiting client's reserved job has entered the safety margin.
1373 * 3. A waiting client's requested timeout has occurred.
1375 * If any of these happen, we must do the appropriate thing. */
1376 static void
1377 h_conn_timeout(conn c)
1379 int r, should_timeout = 0;
1380 job j;
1382 /* Check if the client was trying to reserve a job. */
1383 if (conn_waiting(c) && conn_has_close_deadline(c)) should_timeout = 1;
1385 /* Check if any reserved jobs have run out of time. We should do this
1386 * whether or not the client is waiting for a new reservation. */
1387 while ((j = soonest_job(c))) {
1388 if (j->deadline > time(NULL)) break;
1390 /* This job is in the middle of being written out. If we return it to
1391 * the ready queue, someone might free it before we finish writing it
1392 * out to the socket. So we'll copy it here and free the copy when it's
1393 * done sending. */
1394 if (j == c->out_job) c->out_job = job_copy(c->out_job);
1396 timeout_ct++; /* stats */
1397 j->timeout_ct++;
1398 r = enqueue_job(remove_this_reserved_job(c, j), 0);
1399 if (!r) bury_job(j); /* there was no room in the queue, so bury it */
1400 r = conn_update_evq(c, c->evq.ev_events);
1401 if (r == -1) return twarnx("conn_update_evq() failed"), conn_close(c);
1404 if (should_timeout) {
1405 dprintf("conn_waiting(%p) = %d\n", c, conn_waiting(c));
1406 return reply_msg(remove_waiting_conn(c), MSG_DEADLINE_SOON);
1407 } else if (conn_waiting(c) && c->pending_timeout >= 0) {
1408 dprintf("conn_waiting(%p) = %d\n", c, conn_waiting(c));
1409 c->pending_timeout = -1;
1410 return reply_msg(remove_waiting_conn(c), MSG_TIMED_OUT);
1414 void
1415 enter_drain_mode(int sig)
1417 drain_mode = 1;
1420 static void
1421 do_cmd(conn c)
1423 dispatch_cmd(c);
1424 fill_extra_data(c);
1427 static void
1428 reset_conn(conn c)
1430 int r;
1432 r = conn_update_evq(c, EV_READ | EV_PERSIST);
1433 if (r == -1) return twarnx("update events failed"), conn_close(c);
1435 /* was this a peek or stats command? */
1436 if (c->out_job && !c->out_job->id) job_free(c->out_job);
1437 c->out_job = NULL;
1439 c->reply_sent = 0; /* now that we're done, reset this */
1440 c->state = STATE_WANTCOMMAND;
1443 static void
1444 h_conn_data(conn c)
1446 int r, to_read;
1447 job j;
1448 struct iovec iov[2];
1450 switch (c->state) {
1451 case STATE_WANTCOMMAND:
1452 r = read(c->fd, c->cmd + c->cmd_read, LINE_BUF_SIZE - c->cmd_read);
1453 if (r == -1) return check_err(c, "read()");
1454 if (r == 0) return conn_close(c); /* the client hung up */
1456 c->cmd_read += r; /* we got some bytes */
1458 c->cmd_len = cmd_len(c); /* find the EOL */
1460 /* yay, complete command line */
1461 if (c->cmd_len) return do_cmd(c);
1463 /* c->cmd_read > LINE_BUF_SIZE can't happen */
1465 /* command line too long? */
1466 if (c->cmd_read == LINE_BUF_SIZE) {
1467 c->cmd_read = 0; /* discard the input so far */
1468 return reply_msg(c, MSG_BAD_FORMAT);
1471 /* otherwise we have an incomplete line, so just keep waiting */
1472 break;
1473 case STATE_BITBUCKET:
1474 /* Invert the meaning of in_job_read while throwing away data -- it
1475 * counts the bytes that remain to be thrown away. */
1476 to_read = min(c->in_job_read, BUCKET_BUF_SIZE);
1477 r = read(c->fd, bucket, to_read);
1478 if (r == -1) return check_err(c, "read()");
1479 if (r == 0) return conn_close(c); /* the client hung up */
1481 c->in_job_read -= r; /* we got some bytes */
1483 /* (c->in_job_read < 0) can't happen */
1485 if (c->in_job_read == 0) return reply_serr(c, MSG_OUT_OF_MEMORY);
1486 break;
1487 case STATE_WANTDATA:
1488 j = c->in_job;
1490 r = read(c->fd, j->body + c->in_job_read, j->body_size -c->in_job_read);
1491 if (r == -1) return check_err(c, "read()");
1492 if (r == 0) return conn_close(c); /* the client hung up */
1494 c->in_job_read += r; /* we got some bytes */
1496 /* (j->in_job_read > j->body_size) can't happen */
1498 maybe_enqueue_incoming_job(c);
1499 break;
1500 case STATE_SENDWORD:
1501 r= write(c->fd, c->reply + c->reply_sent, c->reply_len - c->reply_sent);
1502 if (r == -1) return check_err(c, "write()");
1503 if (r == 0) return conn_close(c); /* the client hung up */
1505 c->reply_sent += r; /* we got some bytes */
1507 /* (c->reply_sent > c->reply_len) can't happen */
1509 if (c->reply_sent == c->reply_len) return reset_conn(c);
1511 /* otherwise we sent an incomplete reply, so just keep waiting */
1512 break;
1513 case STATE_SENDJOB:
1514 j = c->out_job;
1516 iov[0].iov_base = (void *)(c->reply + c->reply_sent);
1517 iov[0].iov_len = c->reply_len - c->reply_sent; /* maybe 0 */
1518 iov[1].iov_base = j->body + c->out_job_sent;
1519 iov[1].iov_len = j->body_size - c->out_job_sent;
1521 r = writev(c->fd, iov, 2);
1522 if (r == -1) return check_err(c, "writev()");
1523 if (r == 0) return conn_close(c); /* the client hung up */
1525 /* update the sent values */
1526 c->reply_sent += r;
1527 if (c->reply_sent >= c->reply_len) {
1528 c->out_job_sent += c->reply_sent - c->reply_len;
1529 c->reply_sent = c->reply_len;
1532 /* (c->out_job_sent > j->body_size) can't happen */
1534 /* are we done? */
1535 if (c->out_job_sent == j->body_size) return reset_conn(c);
1537 /* otherwise we sent incomplete data, so just keep waiting */
1538 break;
1539 case STATE_WAIT: /* keep an eye out in case they hang up */
1540 /* but don't hang up just because our buffer is full */
1541 if (LINE_BUF_SIZE - c->cmd_read < 1) break;
1543 r = read(c->fd, c->cmd + c->cmd_read, LINE_BUF_SIZE - c->cmd_read);
1544 if (r == -1) return check_err(c, "read()");
1545 if (r == 0) return conn_close(c); /* the client hung up */
1546 c->cmd_read += r; /* we got some bytes */
1550 #define want_command(c) ((c)->fd && ((c)->state == STATE_WANTCOMMAND))
1551 #define cmd_data_ready(c) (want_command(c) && (c)->cmd_read)
1553 static void
1554 h_conn(const int fd, const short which, conn c)
1556 if (fd != c->fd) {
1557 twarnx("Argh! event fd doesn't match conn fd.");
1558 close(fd);
1559 return conn_close(c);
1562 switch (which) {
1563 case EV_TIMEOUT:
1564 h_conn_timeout(c);
1565 event_add(&c->evq, NULL); /* seems to be necessary */
1566 break;
1567 case EV_READ:
1568 /* fall through... */
1569 case EV_WRITE:
1570 /* fall through... */
1571 default:
1572 h_conn_data(c);
1575 while (cmd_data_ready(c) && (c->cmd_len = cmd_len(c))) do_cmd(c);
1578 static void
1579 h_delay()
1581 int r;
1582 job j;
1583 time_t t;
1585 t = time(NULL);
1586 while ((j = delay_q_peek())) {
1587 if (j->deadline > t) break;
1588 j = delay_q_take();
1589 r = enqueue_job(j, 0);
1590 if (!r) bury_job(j); /* there was no room in the queue, so bury it */
1593 set_main_delay_timeout();
1596 void
1597 h_accept(const int fd, const short which, struct event *ev)
1599 conn c;
1600 int cfd, flags, r;
1601 socklen_t addrlen;
1602 struct sockaddr addr;
1604 if (which == EV_TIMEOUT) return h_delay();
1606 addrlen = sizeof addr;
1607 cfd = accept(fd, &addr, &addrlen);
1608 if (cfd == -1) {
1609 if (errno != EAGAIN && errno != EWOULDBLOCK) twarn("accept()");
1610 if (errno == EMFILE) brake();
1611 return;
1614 flags = fcntl(cfd, F_GETFL, 0);
1615 if (flags < 0) return twarn("getting flags"), close(cfd), v();
1617 r = fcntl(cfd, F_SETFL, flags | O_NONBLOCK);
1618 if (r < 0) return twarn("setting O_NONBLOCK"), close(cfd), v();
1620 c = make_conn(cfd, STATE_WANTCOMMAND, default_tube, default_tube);
1621 if (!c) return twarnx("make_conn() failed"), close(cfd), brake();
1623 dprintf("accepted conn, fd=%d\n", cfd);
1624 r = conn_set_evq(c, EV_READ | EV_PERSIST, (evh) h_conn);
1625 if (r == -1) return twarnx("conn_set_evq() failed"), close(cfd), brake();
1628 void
1629 prot_init()
1631 start_time = time(NULL);
1632 memset(op_ct, 0, sizeof(op_ct));
1634 ms_init(&tubes, NULL, NULL);
1636 TUBE_ASSIGN(default_tube, tube_find_or_make("default"));
1637 if (!default_tube) twarnx("Out of memory during startup!");
1640 void
1641 prot_replay_binlog()
1643 struct job binlog_jobs;
1644 job j, nj;
1645 unsigned int delay;
1647 binlog_jobs.prev = binlog_jobs.next = &binlog_jobs;
1648 binlog_read(&binlog_jobs);
1650 for (j = binlog_jobs.next ; j != &binlog_jobs ; j = nj) {
1651 nj = j->next;
1652 job_remove(j);
1653 delay = 0;
1654 switch (j->state) {
1655 case JOB_STATE_BURIED:
1656 bury_job(j);
1657 break;
1658 case JOB_STATE_DELAYED:
1659 if (start_time < j->deadline) delay = j->deadline - start_time;
1660 /* fall through */
1661 default:
1662 enqueue_job(j,delay);