Include config.h first.
[beanstalkd.git] / prot.c
blob054e955c87f18643c71eeaa7d2784b457aefc7fd
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 "config.h"
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <sys/resource.h>
27 #include <sys/uio.h>
28 #include <stdarg.h>
29 #include <ctype.h>
31 #include "stat.h"
32 #include "prot.h"
33 #include "pq.h"
34 #include "ms.h"
35 #include "job.h"
36 #include "tube.h"
37 #include "conn.h"
38 #include "util.h"
39 #include "net.h"
40 #include "binlog.h"
42 /* job body cannot be greater than this many bytes long */
43 size_t job_data_size_limit = JOB_DATA_SIZE_LIMIT_DEFAULT;
45 #define NAME_CHARS \
46 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
47 "abcdefghijklmnopqrstuvwxyz" \
48 "0123456789-+/;.$()"
50 #define CMD_PUT "put "
51 #define CMD_PEEKJOB "peek "
52 #define CMD_PEEK_READY "peek-ready"
53 #define CMD_PEEK_DELAYED "peek-delayed"
54 #define CMD_PEEK_BURIED "peek-buried"
55 #define CMD_RESERVE "reserve"
56 #define CMD_RESERVE_TIMEOUT "reserve-with-timeout "
57 #define CMD_DELETE "delete "
58 #define CMD_RELEASE "release "
59 #define CMD_BURY "bury "
60 #define CMD_KICK "kick "
61 #define CMD_TOUCH "touch "
62 #define CMD_STATS "stats"
63 #define CMD_JOBSTATS "stats-job "
64 #define CMD_USE "use "
65 #define CMD_WATCH "watch "
66 #define CMD_IGNORE "ignore "
67 #define CMD_LIST_TUBES "list-tubes"
68 #define CMD_LIST_TUBE_USED "list-tube-used"
69 #define CMD_LIST_TUBES_WATCHED "list-tubes-watched"
70 #define CMD_STATS_TUBE "stats-tube "
72 #define CONSTSTRLEN(m) (sizeof(m) - 1)
74 #define CMD_PEEK_READY_LEN CONSTSTRLEN(CMD_PEEK_READY)
75 #define CMD_PEEK_DELAYED_LEN CONSTSTRLEN(CMD_PEEK_DELAYED)
76 #define CMD_PEEK_BURIED_LEN CONSTSTRLEN(CMD_PEEK_BURIED)
77 #define CMD_PEEKJOB_LEN CONSTSTRLEN(CMD_PEEKJOB)
78 #define CMD_RESERVE_LEN CONSTSTRLEN(CMD_RESERVE)
79 #define CMD_RESERVE_TIMEOUT_LEN CONSTSTRLEN(CMD_RESERVE_TIMEOUT)
80 #define CMD_DELETE_LEN CONSTSTRLEN(CMD_DELETE)
81 #define CMD_RELEASE_LEN CONSTSTRLEN(CMD_RELEASE)
82 #define CMD_BURY_LEN CONSTSTRLEN(CMD_BURY)
83 #define CMD_KICK_LEN CONSTSTRLEN(CMD_KICK)
84 #define CMD_TOUCH_LEN CONSTSTRLEN(CMD_TOUCH)
85 #define CMD_STATS_LEN CONSTSTRLEN(CMD_STATS)
86 #define CMD_JOBSTATS_LEN CONSTSTRLEN(CMD_JOBSTATS)
87 #define CMD_USE_LEN CONSTSTRLEN(CMD_USE)
88 #define CMD_WATCH_LEN CONSTSTRLEN(CMD_WATCH)
89 #define CMD_IGNORE_LEN CONSTSTRLEN(CMD_IGNORE)
90 #define CMD_LIST_TUBES_LEN CONSTSTRLEN(CMD_LIST_TUBES)
91 #define CMD_LIST_TUBE_USED_LEN CONSTSTRLEN(CMD_LIST_TUBE_USED)
92 #define CMD_LIST_TUBES_WATCHED_LEN CONSTSTRLEN(CMD_LIST_TUBES_WATCHED)
93 #define CMD_STATS_TUBE_LEN CONSTSTRLEN(CMD_STATS_TUBE)
95 #define MSG_FOUND "FOUND"
96 #define MSG_NOTFOUND "NOT_FOUND\r\n"
97 #define MSG_RESERVED "RESERVED"
98 #define MSG_DEADLINE_SOON "DEADLINE_SOON\r\n"
99 #define MSG_TIMED_OUT "TIMED_OUT\r\n"
100 #define MSG_DELETED "DELETED\r\n"
101 #define MSG_RELEASED "RELEASED\r\n"
102 #define MSG_BURIED "BURIED\r\n"
103 #define MSG_TOUCHED "TOUCHED\r\n"
104 #define MSG_BURIED_FMT "BURIED %llu\r\n"
105 #define MSG_INSERTED_FMT "INSERTED %llu\r\n"
106 #define MSG_NOT_IGNORED "NOT_IGNORED\r\n"
108 #define MSG_NOTFOUND_LEN CONSTSTRLEN(MSG_NOTFOUND)
109 #define MSG_DELETED_LEN CONSTSTRLEN(MSG_DELETED)
110 #define MSG_TOUCHED_LEN CONSTSTRLEN(MSG_TOUCHED)
111 #define MSG_RELEASED_LEN CONSTSTRLEN(MSG_RELEASED)
112 #define MSG_BURIED_LEN CONSTSTRLEN(MSG_BURIED)
113 #define MSG_NOT_IGNORED_LEN CONSTSTRLEN(MSG_NOT_IGNORED)
115 #define MSG_OUT_OF_MEMORY "OUT_OF_MEMORY\r\n"
116 #define MSG_INTERNAL_ERROR "INTERNAL_ERROR\r\n"
117 #define MSG_DRAINING "DRAINING\r\n"
118 #define MSG_BAD_FORMAT "BAD_FORMAT\r\n"
119 #define MSG_UNKNOWN_COMMAND "UNKNOWN_COMMAND\r\n"
120 #define MSG_EXPECTED_CRLF "EXPECTED_CRLF\r\n"
121 #define MSG_JOB_TOO_BIG "JOB_TOO_BIG\r\n"
123 #define STATE_WANTCOMMAND 0
124 #define STATE_WANTDATA 1
125 #define STATE_SENDJOB 2
126 #define STATE_SENDWORD 3
127 #define STATE_WAIT 4
128 #define STATE_BITBUCKET 5
130 #define OP_UNKNOWN 0
131 #define OP_PUT 1
132 #define OP_PEEKJOB 2
133 #define OP_RESERVE 3
134 #define OP_DELETE 4
135 #define OP_RELEASE 5
136 #define OP_BURY 6
137 #define OP_KICK 7
138 #define OP_STATS 8
139 #define OP_JOBSTATS 9
140 #define OP_PEEK_BURIED 10
141 #define OP_USE 11
142 #define OP_WATCH 12
143 #define OP_IGNORE 13
144 #define OP_LIST_TUBES 14
145 #define OP_LIST_TUBE_USED 15
146 #define OP_LIST_TUBES_WATCHED 16
147 #define OP_STATS_TUBE 17
148 #define OP_PEEK_READY 18
149 #define OP_PEEK_DELAYED 19
150 #define OP_RESERVE_TIMEOUT 20
151 #define OP_TOUCH 21
152 #define TOTAL_OPS 22
154 #define STATS_FMT "---\n" \
155 "current-jobs-urgent: %u\n" \
156 "current-jobs-ready: %u\n" \
157 "current-jobs-reserved: %u\n" \
158 "current-jobs-delayed: %u\n" \
159 "current-jobs-buried: %u\n" \
160 "cmd-put: %llu\n" \
161 "cmd-peek: %llu\n" \
162 "cmd-peek-ready: %llu\n" \
163 "cmd-peek-delayed: %llu\n" \
164 "cmd-peek-buried: %llu\n" \
165 "cmd-reserve: %llu\n" \
166 "cmd-reserve-with-timeout: %llu\n" \
167 "cmd-delete: %llu\n" \
168 "cmd-release: %llu\n" \
169 "cmd-use: %llu\n" \
170 "cmd-watch: %llu\n" \
171 "cmd-ignore: %llu\n" \
172 "cmd-bury: %llu\n" \
173 "cmd-kick: %llu\n" \
174 "cmd-touch: %llu\n" \
175 "cmd-stats: %llu\n" \
176 "cmd-stats-job: %llu\n" \
177 "cmd-stats-tube: %llu\n" \
178 "cmd-list-tubes: %llu\n" \
179 "cmd-list-tube-used: %llu\n" \
180 "cmd-list-tubes-watched: %llu\n" \
181 "job-timeouts: %llu\n" \
182 "total-jobs: %llu\n" \
183 "max-job-size: %zu\n" \
184 "current-tubes: %zu\n" \
185 "current-connections: %u\n" \
186 "current-producers: %u\n" \
187 "current-workers: %u\n" \
188 "current-waiting: %u\n" \
189 "total-connections: %u\n" \
190 "pid: %ld\n" \
191 "version: %s\n" \
192 "rusage-utime: %d.%06d\n" \
193 "rusage-stime: %d.%06d\n" \
194 "uptime: %u\n" \
195 "binlog-oldest-index: %s\n" \
196 "binlog-current-index: %s\n" \
197 "binlog-max-size: %zu\n" \
198 "\r\n"
200 #define STATS_TUBE_FMT "---\n" \
201 "name: %s\n" \
202 "current-jobs-urgent: %u\n" \
203 "current-jobs-ready: %u\n" \
204 "current-jobs-reserved: %u\n" \
205 "current-jobs-delayed: %u\n" \
206 "current-jobs-buried: %u\n" \
207 "total-jobs: %llu\n" \
208 "current-using: %u\n" \
209 "current-watching: %u\n" \
210 "current-waiting: %u\n" \
211 "\r\n"
213 #define JOB_STATS_FMT "---\n" \
214 "id: %llu\n" \
215 "tube: %s\n" \
216 "state: %s\n" \
217 "pri: %u\n" \
218 "age: %llu\n" \
219 "delay: %llu\n" \
220 "ttr: %llu\n" \
221 "time-left: %llu\n" \
222 "reserves: %u\n" \
223 "timeouts: %u\n" \
224 "releases: %u\n" \
225 "buries: %u\n" \
226 "kicks: %u\n" \
227 "\r\n"
229 /* this number is pretty arbitrary */
230 #define BUCKET_BUF_SIZE 1024
232 static char bucket[BUCKET_BUF_SIZE];
234 static unsigned int ready_ct = 0;
235 static struct stats global_stat = {0, 0, 0, 0, 0};
237 static tube default_tube;
239 static int drain_mode = 0;
240 static usec started_at;
241 static uint64_t op_ct[TOTAL_OPS], timeout_ct = 0;
244 /* Doubly-linked list of connections with at least one reserved job. */
245 static struct conn running = { &running, &running, 0 };
247 #ifdef DEBUG
248 static const char * op_names[] = {
249 "<unknown>",
250 CMD_PUT,
251 CMD_PEEKJOB,
252 CMD_RESERVE,
253 CMD_DELETE,
254 CMD_RELEASE,
255 CMD_BURY,
256 CMD_KICK,
257 CMD_STATS,
258 CMD_JOBSTATS,
259 CMD_PEEK_BURIED,
260 CMD_USE,
261 CMD_WATCH,
262 CMD_IGNORE,
263 CMD_LIST_TUBES,
264 CMD_LIST_TUBE_USED,
265 CMD_LIST_TUBES_WATCHED,
266 CMD_STATS_TUBE,
267 CMD_PEEK_READY,
268 CMD_PEEK_DELAYED,
269 CMD_RESERVE_TIMEOUT,
270 CMD_TOUCH
272 #endif
274 static job remove_buried_job(job j);
276 static int
277 buried_job_p(tube t)
279 return job_list_any_p(&t->buried);
282 static void
283 reply(conn c, const char *line, int len, int state)
285 int r;
287 if (!c) return;
289 r = conn_update_evq(c, EV_WRITE | EV_PERSIST);
290 if (r == -1) return twarnx("conn_update_evq() failed"), conn_close(c);
292 c->reply = line;
293 c->reply_len = len;
294 c->reply_sent = 0;
295 c->state = state;
296 dprintf("sending reply: %.*s", len, line);
299 #define reply_msg(c,m) reply((c),(m),CONSTSTRLEN(m),STATE_SENDWORD)
301 #define reply_serr(c,e) (twarnx("server error: %s",(e)),\
302 reply_msg((c),(e)))
304 static void
305 reply_line(conn c, int state, const char *fmt, ...)
307 int r;
308 va_list ap;
310 va_start(ap, fmt);
311 r = vsnprintf(c->reply_buf, LINE_BUF_SIZE, fmt, ap);
312 va_end(ap);
314 /* Make sure the buffer was big enough. If not, we have a bug. */
315 if (r >= LINE_BUF_SIZE) return reply_serr(c, MSG_INTERNAL_ERROR);
317 return reply(c, c->reply_buf, r, state);
320 static void
321 reply_job(conn c, job j, const char *word)
323 /* tell this connection which job to send */
324 c->out_job = j;
325 c->out_job_sent = 0;
327 return reply_line(c, STATE_SENDJOB, "%s %llu %u\r\n",
328 word, j->id, j->body_size - 2);
331 conn
332 remove_waiting_conn(conn c)
334 tube t;
335 size_t i;
337 if (!conn_waiting(c)) return NULL;
339 c->type &= ~CONN_TYPE_WAITING;
340 global_stat.waiting_ct--;
341 for (i = 0; i < c->watch.used; i++) {
342 t = c->watch.items[i];
343 t->stat.waiting_ct--;
344 ms_remove(&t->waiting, c);
346 return c;
349 static void
350 reserve_job(conn c, job j)
352 j->deadline_at = now_usec() + j->ttr;
353 global_stat.reserved_ct++; /* stats */
354 j->tube->stat.reserved_ct++;
355 j->reserve_ct++;
356 conn_insert(&running, c);
357 j->state = JOB_STATE_RESERVED;
358 job_insert(&c->reserved_jobs, j);
359 j->reserver = c;
360 if (c->soonest_job && j->deadline_at < c->soonest_job->deadline_at) {
361 c->soonest_job = j;
363 return reply_job(c, j, MSG_RESERVED);
366 static job
367 next_eligible_job()
369 tube t;
370 size_t i;
371 job j = NULL, candidate;
373 dprintf("tubes.used = %zu\n", tubes.used);
374 for (i = 0; i < tubes.used; i++) {
375 t = tubes.items[i];
376 dprintf("for %s t->waiting.used=%zu t->ready.used=%d\n",
377 t->name, t->waiting.used, t->ready.used);
378 if (t->waiting.used && t->ready.used) {
379 candidate = pq_peek(&t->ready);
380 if (!j || job_pri_cmp(candidate, j) < 0) j = candidate;
382 dprintf("i = %zu, tubes.used = %zu\n", i, tubes.used);
385 return j;
388 static void
389 process_queue()
391 job j;
393 dprintf("processing queue\n");
394 while ((j = next_eligible_job())) {
395 dprintf("got eligible job %llu in %s\n", j->id, j->tube->name);
396 j = pq_take(&j->tube->ready);
397 ready_ct--;
398 if (j->pri < URGENT_THRESHOLD) {
399 global_stat.urgent_ct--;
400 j->tube->stat.urgent_ct--;
402 reserve_job(remove_waiting_conn(ms_take(&j->tube->waiting)), j);
406 static job
407 delay_q_peek()
409 int i;
410 tube t;
411 job j = NULL, nj;
413 for (i = 0; i < tubes.used; i++) {
414 t = tubes.items[i];
415 nj = pq_peek(&t->delay);
416 if (!nj) continue;
417 if (!j || nj->deadline_at < j->deadline_at) j = nj;
420 return j;
423 static void
424 set_main_delay_timeout()
426 job j;
428 set_main_timeout((j = delay_q_peek()) ? j->deadline_at : 0);
431 static int
432 enqueue_job(job j, usec delay, char update_store)
434 int r;
436 j->reserver = NULL;
437 if (delay) {
438 j->deadline_at = now_usec() + delay;
439 r = pq_give(&j->tube->delay, j);
440 if (!r) return 0;
441 j->state = JOB_STATE_DELAYED;
442 set_main_delay_timeout();
443 } else {
444 r = pq_give(&j->tube->ready, j);
445 if (!r) return 0;
446 j->state = JOB_STATE_READY;
447 ready_ct++;
448 if (j->pri < URGENT_THRESHOLD) {
449 global_stat.urgent_ct++;
450 j->tube->stat.urgent_ct++;
454 if (update_store) {
455 r = binlog_write_job(j);
456 if (!r) return -1;
459 process_queue();
460 return 1;
463 static int
464 bury_job(job j, char update_store)
466 size_t z;
468 if (update_store) {
469 z = binlog_reserve_space_update(j);
470 if (!z) return 0;
471 j->reserved_binlog_space += z;
474 job_insert(&j->tube->buried, j);
475 global_stat.buried_ct++;
476 j->tube->stat.buried_ct++;
477 j->state = JOB_STATE_BURIED;
478 j->reserver = NULL;
479 j->bury_ct++;
481 if (update_store) return binlog_write_job(j);
483 return 1;
486 void
487 enqueue_reserved_jobs(conn c)
489 int r;
490 job j;
492 while (job_list_any_p(&c->reserved_jobs)) {
493 j = job_remove(c->reserved_jobs.next);
494 r = enqueue_job(j, 0, 0);
495 if (r < 1) bury_job(j, 0);
496 global_stat.reserved_ct--;
497 j->tube->stat.reserved_ct--;
498 c->soonest_job = NULL;
499 if (!job_list_any_p(&c->reserved_jobs)) conn_remove(c);
503 static job
504 delay_q_take()
506 job j = delay_q_peek();
507 return j ? pq_take(&j->tube->delay) : NULL;
510 static int
511 kick_buried_job(tube t)
513 int r;
514 job j;
515 size_t z;
517 if (!buried_job_p(t)) return 0;
518 j = remove_buried_job(t->buried.next);
520 z = binlog_reserve_space_update(j);
521 if (!z) return pq_give(&t->delay, j), 0; /* put it back */
522 j->reserved_binlog_space += z;
524 j->kick_ct++;
525 r = enqueue_job(j, 0, 1);
526 if (r == 1) return 1;
528 /* ready queue is full, so bury it */
529 bury_job(j, 0);
530 return 0;
533 static unsigned int
534 get_delayed_job_ct()
536 tube t;
537 size_t i;
538 unsigned int count = 0;
540 for (i = 0; i < tubes.used; i++) {
541 t = tubes.items[i];
542 count += t->delay.used;
544 return count;
547 static int
548 kick_delayed_job(tube t)
550 int r;
551 job j;
552 size_t z;
554 j = pq_take(&t->delay);
555 if (!j) return 0;
557 z = binlog_reserve_space_update(j);
558 if (!z) return pq_give(&t->delay, j), 0; /* put it back */
559 j->reserved_binlog_space += z;
561 j->kick_ct++;
562 r = enqueue_job(j, 0, 1);
563 if (r == 1) return 1;
565 /* ready queue is full, so delay it again */
566 r = enqueue_job(j, j->delay, 0);
567 if (r == 1) return 0;
569 /* last resort */
570 bury_job(j, 0);
571 return 0;
574 /* return the number of jobs successfully kicked */
575 static unsigned int
576 kick_buried_jobs(tube t, unsigned int n)
578 unsigned int i;
579 for (i = 0; (i < n) && kick_buried_job(t); ++i);
580 return i;
583 /* return the number of jobs successfully kicked */
584 static unsigned int
585 kick_delayed_jobs(tube t, unsigned int n)
587 unsigned int i;
588 for (i = 0; (i < n) && kick_delayed_job(t); ++i);
589 return i;
592 static unsigned int
593 kick_jobs(tube t, unsigned int n)
595 if (buried_job_p(t)) return kick_buried_jobs(t, n);
596 return kick_delayed_jobs(t, n);
599 static job
600 remove_buried_job(job j)
602 if (!j || j->state != JOB_STATE_BURIED) return NULL;
603 j = job_remove(j);
604 if (j) {
605 global_stat.buried_ct--;
606 j->tube->stat.buried_ct--;
608 return j;
611 static job
612 remove_ready_job(job j)
614 if (!j || j->state != JOB_STATE_READY) return NULL;
615 j = pq_remove(&j->tube->ready, j);
616 if (j) {
617 ready_ct--;
618 if (j->pri < URGENT_THRESHOLD) {
619 global_stat.urgent_ct--;
620 j->tube->stat.urgent_ct--;
623 return j;
626 static void
627 enqueue_waiting_conn(conn c)
629 tube t;
630 size_t i;
632 global_stat.waiting_ct++;
633 c->type |= CONN_TYPE_WAITING;
634 for (i = 0; i < c->watch.used; i++) {
635 t = c->watch.items[i];
636 t->stat.waiting_ct++;
637 ms_append(&t->waiting, c);
641 static job
642 find_reserved_job_in_conn(conn c, job j)
644 return (j && j->reserver == c && j->state == JOB_STATE_RESERVED) ? j : NULL;
647 static job
648 touch_job(conn c, job j)
650 j = find_reserved_job_in_conn(c, j);
651 if (j) {
652 j->deadline_at = now_usec() + j->ttr;
653 c->soonest_job = NULL;
655 return j;
658 static job
659 peek_job(uint64_t id)
661 return job_find(id);
664 static void
665 check_err(conn c, const char *s)
667 if (errno == EAGAIN) return;
668 if (errno == EINTR) return;
669 if (errno == EWOULDBLOCK) return;
671 twarn("%s", s);
672 conn_close(c);
673 return;
676 /* Scan the given string for the sequence "\r\n" and return the line length.
677 * Always returns at least 2 if a match is found. Returns 0 if no match. */
678 static int
679 scan_line_end(const char *s, int size)
681 char *match;
683 match = memchr(s, '\r', size - 1);
684 if (!match) return 0;
686 /* this is safe because we only scan size - 1 chars above */
687 if (match[1] == '\n') return match - s + 2;
689 return 0;
692 static int
693 cmd_len(conn c)
695 return scan_line_end(c->cmd, c->cmd_read);
698 /* parse the command line */
699 static int
700 which_cmd(conn c)
702 #define TEST_CMD(s,c,o) if (strncmp((s), (c), CONSTSTRLEN(c)) == 0) return (o);
703 TEST_CMD(c->cmd, CMD_PUT, OP_PUT);
704 TEST_CMD(c->cmd, CMD_PEEKJOB, OP_PEEKJOB);
705 TEST_CMD(c->cmd, CMD_PEEK_READY, OP_PEEK_READY);
706 TEST_CMD(c->cmd, CMD_PEEK_DELAYED, OP_PEEK_DELAYED);
707 TEST_CMD(c->cmd, CMD_PEEK_BURIED, OP_PEEK_BURIED);
708 TEST_CMD(c->cmd, CMD_RESERVE_TIMEOUT, OP_RESERVE_TIMEOUT);
709 TEST_CMD(c->cmd, CMD_RESERVE, OP_RESERVE);
710 TEST_CMD(c->cmd, CMD_DELETE, OP_DELETE);
711 TEST_CMD(c->cmd, CMD_RELEASE, OP_RELEASE);
712 TEST_CMD(c->cmd, CMD_BURY, OP_BURY);
713 TEST_CMD(c->cmd, CMD_KICK, OP_KICK);
714 TEST_CMD(c->cmd, CMD_TOUCH, OP_TOUCH);
715 TEST_CMD(c->cmd, CMD_JOBSTATS, OP_JOBSTATS);
716 TEST_CMD(c->cmd, CMD_STATS_TUBE, OP_STATS_TUBE);
717 TEST_CMD(c->cmd, CMD_STATS, OP_STATS);
718 TEST_CMD(c->cmd, CMD_USE, OP_USE);
719 TEST_CMD(c->cmd, CMD_WATCH, OP_WATCH);
720 TEST_CMD(c->cmd, CMD_IGNORE, OP_IGNORE);
721 TEST_CMD(c->cmd, CMD_LIST_TUBES_WATCHED, OP_LIST_TUBES_WATCHED);
722 TEST_CMD(c->cmd, CMD_LIST_TUBE_USED, OP_LIST_TUBE_USED);
723 TEST_CMD(c->cmd, CMD_LIST_TUBES, OP_LIST_TUBES);
724 return OP_UNKNOWN;
727 /* Copy up to body_size trailing bytes into the job, then the rest into the cmd
728 * buffer. If c->in_job exists, this assumes that c->in_job->body is empty.
729 * This function is idempotent(). */
730 static void
731 fill_extra_data(conn c)
733 int extra_bytes, job_data_bytes = 0, cmd_bytes;
735 if (!c->fd) return; /* the connection was closed */
736 if (!c->cmd_len) return; /* we don't have a complete command */
738 /* how many extra bytes did we read? */
739 extra_bytes = c->cmd_read - c->cmd_len;
741 /* how many bytes should we put into the job body? */
742 if (c->in_job) {
743 job_data_bytes = min(extra_bytes, c->in_job->body_size);
744 memcpy(c->in_job->body, c->cmd + c->cmd_len, job_data_bytes);
745 c->in_job_read = job_data_bytes;
746 } else if (c->in_job_read) {
747 /* we are in bit-bucket mode, throwing away data */
748 job_data_bytes = min(extra_bytes, c->in_job_read);
749 c->in_job_read -= job_data_bytes;
752 /* how many bytes are left to go into the future cmd? */
753 cmd_bytes = extra_bytes - job_data_bytes;
754 memmove(c->cmd, c->cmd + c->cmd_len + job_data_bytes, cmd_bytes);
755 c->cmd_read = cmd_bytes;
756 c->cmd_len = 0; /* we no longer know the length of the new command */
759 static void
760 enqueue_incoming_job(conn c)
762 int r;
763 job j = c->in_job;
765 c->in_job = NULL; /* the connection no longer owns this job */
766 c->in_job_read = 0;
768 /* check if the trailer is present and correct */
769 if (memcmp(j->body + j->body_size - 2, "\r\n", 2)) {
770 job_free(j);
771 return reply_msg(c, MSG_EXPECTED_CRLF);
774 if (drain_mode) {
775 job_free(j);
776 return reply_serr(c, MSG_DRAINING);
779 if (j->reserved_binlog_space) return reply_serr(c, MSG_INTERNAL_ERROR);
780 j->reserved_binlog_space = binlog_reserve_space_put(j);
781 if (!j->reserved_binlog_space) return reply_serr(c, MSG_OUT_OF_MEMORY);
783 /* we have a complete job, so let's stick it in the pqueue */
784 r = enqueue_job(j, j->delay, 1);
785 if (r < 0) return reply_serr(c, MSG_INTERNAL_ERROR);
787 op_ct[OP_PUT]++; /* stats */
788 global_stat.total_jobs_ct++;
789 j->tube->stat.total_jobs_ct++;
791 if (r == 1) return reply_line(c, STATE_SENDWORD, MSG_INSERTED_FMT, j->id);
793 /* out of memory trying to grow the queue, so it gets buried */
794 bury_job(j, 0);
795 reply_line(c, STATE_SENDWORD, MSG_BURIED_FMT, j->id);
798 static unsigned int
799 uptime()
801 return (now_usec() - started_at) / 1000000;
804 static int
805 fmt_stats(char *buf, size_t size, void *x)
807 struct rusage ru = {{0, 0}, {0, 0}};
808 getrusage(RUSAGE_SELF, &ru); /* don't care if it fails */
809 return snprintf(buf, size, STATS_FMT,
810 global_stat.urgent_ct,
811 ready_ct,
812 global_stat.reserved_ct,
813 get_delayed_job_ct(),
814 global_stat.buried_ct,
815 op_ct[OP_PUT],
816 op_ct[OP_PEEKJOB],
817 op_ct[OP_PEEK_READY],
818 op_ct[OP_PEEK_DELAYED],
819 op_ct[OP_PEEK_BURIED],
820 op_ct[OP_RESERVE],
821 op_ct[OP_RESERVE_TIMEOUT],
822 op_ct[OP_DELETE],
823 op_ct[OP_RELEASE],
824 op_ct[OP_USE],
825 op_ct[OP_WATCH],
826 op_ct[OP_IGNORE],
827 op_ct[OP_BURY],
828 op_ct[OP_KICK],
829 op_ct[OP_TOUCH],
830 op_ct[OP_STATS],
831 op_ct[OP_JOBSTATS],
832 op_ct[OP_STATS_TUBE],
833 op_ct[OP_LIST_TUBES],
834 op_ct[OP_LIST_TUBE_USED],
835 op_ct[OP_LIST_TUBES_WATCHED],
836 timeout_ct,
837 global_stat.total_jobs_ct,
838 job_data_size_limit,
839 tubes.used,
840 count_cur_conns(),
841 count_cur_producers(),
842 count_cur_workers(),
843 global_stat.waiting_ct,
844 count_tot_conns(),
845 (long) getpid(),
846 VERSION,
847 (int) ru.ru_utime.tv_sec, (int) ru.ru_utime.tv_usec,
848 (int) ru.ru_stime.tv_sec, (int) ru.ru_stime.tv_usec,
849 uptime(),
850 binlog_oldest_index(),
851 binlog_current_index(),
852 binlog_size_limit);
856 /* Read a priority value from the given buffer and place it in pri.
857 * Update end to point to the address after the last character consumed.
858 * Pri and end can be NULL. If they are both NULL, read_pri() will do the
859 * conversion and return the status code but not update any values. This is an
860 * easy way to check for errors.
861 * If end is NULL, read_pri will also check that the entire input string was
862 * consumed and return an error code otherwise.
863 * Return 0 on success, or nonzero on failure.
864 * If a failure occurs, pri and end are not modified. */
865 static int
866 read_pri(unsigned int *pri, const char *buf, char **end)
868 char *tend;
869 unsigned int tpri;
871 errno = 0;
872 while (buf[0] == ' ') buf++;
873 if (!isdigit(buf[0])) return -1;
874 tpri = strtoul(buf, &tend, 10);
875 if (tend == buf) return -1;
876 if (errno && errno != ERANGE) return -1;
877 if (!end && tend[0] != '\0') return -1;
879 if (pri) *pri = tpri;
880 if (end) *end = tend;
881 return 0;
884 /* Read a delay value from the given buffer and place it in delay.
885 * The interface and behavior are analogous to read_pri(). */
886 static int
887 read_delay(usec *delay, const char *buf, char **end)
889 int r;
890 unsigned int delay_sec;
892 r = read_pri(&delay_sec, buf, end);
893 if (r) return r;
894 *delay = delay_sec * 1000000;
895 return 0;
898 /* Read a timeout value from the given buffer and place it in ttr.
899 * The interface and behavior are the same as in read_delay(). */
900 static int
901 read_ttr(usec *ttr, const char *buf, char **end)
903 return read_delay(ttr, buf, end);
906 static void
907 wait_for_job(conn c, int timeout)
909 int r;
911 c->state = STATE_WAIT;
912 enqueue_waiting_conn(c);
914 /* Set the pending timeout to the requested timeout amount */
915 c->pending_timeout = timeout;
917 /* this conn is waiting, but we want to know if they hang up */
918 r = conn_update_evq(c, EV_READ | EV_PERSIST);
919 if (r == -1) return twarnx("update events failed"), conn_close(c);
922 typedef int(*fmt_fn)(char *, size_t, void *);
924 static void
925 do_stats(conn c, fmt_fn fmt, void *data)
927 int r, stats_len;
929 /* first, measure how big a buffer we will need */
930 stats_len = fmt(NULL, 0, data) + 16;
932 c->out_job = allocate_job(stats_len); /* fake job to hold stats data */
933 if (!c->out_job) return reply_serr(c, MSG_OUT_OF_MEMORY);
935 /* now actually format the stats data */
936 r = fmt(c->out_job->body, stats_len, data);
937 /* and set the actual body size */
938 c->out_job->body_size = r;
939 if (r > stats_len) return reply_serr(c, MSG_INTERNAL_ERROR);
941 c->out_job_sent = 0;
942 return reply_line(c, STATE_SENDJOB, "OK %d\r\n", r - 2);
945 static void
946 do_list_tubes(conn c, ms l)
948 char *buf;
949 tube t;
950 size_t i, resp_z;
952 /* first, measure how big a buffer we will need */
953 resp_z = 6; /* initial "---\n" and final "\r\n" */
954 for (i = 0; i < l->used; i++) {
955 t = l->items[i];
956 resp_z += 3 + strlen(t->name); /* including "- " and "\n" */
959 c->out_job = allocate_job(resp_z); /* fake job to hold response data */
960 if (!c->out_job) return reply_serr(c, MSG_OUT_OF_MEMORY);
962 /* now actually format the response */
963 buf = c->out_job->body;
964 buf += snprintf(buf, 5, "---\n");
965 for (i = 0; i < l->used; i++) {
966 t = l->items[i];
967 buf += snprintf(buf, 4 + strlen(t->name), "- %s\n", t->name);
969 buf[0] = '\r';
970 buf[1] = '\n';
972 c->out_job_sent = 0;
973 return reply_line(c, STATE_SENDJOB, "OK %d\r\n", resp_z - 2);
976 static int
977 fmt_job_stats(char *buf, size_t size, job j)
979 usec t;
981 t = now_usec();
982 return snprintf(buf, size, JOB_STATS_FMT,
983 j->id,
984 j->tube->name,
985 job_state(j),
986 j->pri,
987 (t - j->created_at) / 1000000,
988 j->delay / 1000000,
989 j->ttr / 1000000,
990 (j->deadline_at - t) / 1000000,
991 j->reserve_ct,
992 j->timeout_ct,
993 j->release_ct,
994 j->bury_ct,
995 j->kick_ct);
998 static int
999 fmt_stats_tube(char *buf, size_t size, tube t)
1001 return snprintf(buf, size, STATS_TUBE_FMT,
1002 t->name,
1003 t->stat.urgent_ct,
1004 t->ready.used,
1005 t->stat.reserved_ct,
1006 t->delay.used,
1007 t->stat.buried_ct,
1008 t->stat.total_jobs_ct,
1009 t->using_ct,
1010 t->watching_ct,
1011 t->stat.waiting_ct);
1014 static void
1015 maybe_enqueue_incoming_job(conn c)
1017 job j = c->in_job;
1019 /* do we have a complete job? */
1020 if (c->in_job_read == j->body_size) return enqueue_incoming_job(c);
1022 /* otherwise we have incomplete data, so just keep waiting */
1023 c->state = STATE_WANTDATA;
1026 /* j can be NULL */
1027 static job
1028 remove_this_reserved_job(conn c, job j)
1030 j = job_remove(j);
1031 if (j) {
1032 global_stat.reserved_ct--;
1033 j->tube->stat.reserved_ct--;
1034 j->reserver = NULL;
1036 c->soonest_job = NULL;
1037 if (!job_list_any_p(&c->reserved_jobs)) conn_remove(c);
1038 return j;
1041 static job
1042 remove_reserved_job(conn c, job j)
1044 return remove_this_reserved_job(c, find_reserved_job_in_conn(c, j));
1047 static int
1048 name_is_ok(const char *name, size_t max)
1050 size_t len = strlen(name);
1051 return len > 0 && len <= max &&
1052 strspn(name, NAME_CHARS) == len && name[0] != '-';
1055 void
1056 prot_remove_tube(tube t)
1058 ms_remove(&tubes, t);
1061 static void
1062 dispatch_cmd(conn c)
1064 int r, i, timeout = -1;
1065 size_t z;
1066 unsigned int count;
1067 job j;
1068 unsigned char type;
1069 char *size_buf, *delay_buf, *ttr_buf, *pri_buf, *end_buf, *name;
1070 unsigned int pri, body_size;
1071 usec delay, ttr;
1072 uint64_t id;
1073 tube t = NULL;
1075 /* NUL-terminate this string so we can use strtol and friends */
1076 c->cmd[c->cmd_len - 2] = '\0';
1078 /* check for possible maliciousness */
1079 if (strlen(c->cmd) != c->cmd_len - 2) {
1080 return reply_msg(c, MSG_BAD_FORMAT);
1083 type = which_cmd(c);
1084 dprintf("got %s command: \"%s\"\n", op_names[(int) type], c->cmd);
1086 switch (type) {
1087 case OP_PUT:
1088 r = read_pri(&pri, c->cmd + 4, &delay_buf);
1089 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1091 r = read_delay(&delay, delay_buf, &ttr_buf);
1092 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1094 r = read_ttr(&ttr, ttr_buf, &size_buf);
1095 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1097 errno = 0;
1098 body_size = strtoul(size_buf, &end_buf, 10);
1099 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1101 if (body_size > job_data_size_limit) {
1102 return reply_msg(c, MSG_JOB_TOO_BIG);
1105 /* don't allow trailing garbage */
1106 if (end_buf[0] != '\0') return reply_msg(c, MSG_BAD_FORMAT);
1108 conn_set_producer(c);
1110 c->in_job = make_job(pri, delay, ttr ? : 1, body_size + 2, c->use);
1112 /* OOM? */
1113 if (!c->in_job) {
1114 /* throw away the job body and respond with OUT_OF_MEMORY */
1116 /* Invert the meaning of in_job_read while throwing away data -- it
1117 * counts the bytes that remain to be thrown away. */
1118 c->in_job_read = body_size + 2;
1119 fill_extra_data(c);
1121 if (c->in_job_read == 0) return reply_serr(c, MSG_OUT_OF_MEMORY);
1123 c->state = STATE_BITBUCKET;
1124 return;
1127 fill_extra_data(c);
1129 /* it's possible we already have a complete job */
1130 maybe_enqueue_incoming_job(c);
1132 break;
1133 case OP_PEEK_READY:
1134 /* don't allow trailing garbage */
1135 if (c->cmd_len != CMD_PEEK_READY_LEN + 2) {
1136 return reply_msg(c, MSG_BAD_FORMAT);
1138 op_ct[type]++;
1140 j = job_copy(pq_peek(&c->use->ready));
1142 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1144 reply_job(c, j, MSG_FOUND);
1145 break;
1146 case OP_PEEK_DELAYED:
1147 /* don't allow trailing garbage */
1148 if (c->cmd_len != CMD_PEEK_DELAYED_LEN + 2) {
1149 return reply_msg(c, MSG_BAD_FORMAT);
1151 op_ct[type]++;
1153 j = job_copy(pq_peek(&c->use->delay));
1155 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1157 reply_job(c, j, MSG_FOUND);
1158 break;
1159 case OP_PEEK_BURIED:
1160 /* don't allow trailing garbage */
1161 if (c->cmd_len != CMD_PEEK_BURIED_LEN + 2) {
1162 return reply_msg(c, MSG_BAD_FORMAT);
1164 op_ct[type]++;
1166 j = job_copy(buried_job_p(c->use)? j = c->use->buried.next : NULL);
1168 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1170 reply_job(c, j, MSG_FOUND);
1171 break;
1172 case OP_PEEKJOB:
1173 errno = 0;
1174 id = strtoull(c->cmd + CMD_PEEKJOB_LEN, &end_buf, 10);
1175 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1176 op_ct[type]++;
1178 /* So, peek is annoying, because some other connection might free the
1179 * job while we are still trying to write it out. So we copy it and
1180 * then free the copy when it's done sending. */
1181 j = job_copy(peek_job(id));
1183 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1185 reply_job(c, j, MSG_FOUND);
1186 break;
1187 case OP_RESERVE_TIMEOUT:
1188 errno = 0;
1189 timeout = strtol(c->cmd + CMD_RESERVE_TIMEOUT_LEN, &end_buf, 10);
1190 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1191 case OP_RESERVE: /* FALLTHROUGH */
1192 /* don't allow trailing garbage */
1193 if (type == OP_RESERVE && c->cmd_len != CMD_RESERVE_LEN + 2) {
1194 return reply_msg(c, MSG_BAD_FORMAT);
1197 op_ct[type]++;
1198 conn_set_worker(c);
1200 if (conn_has_close_deadline(c) && !conn_ready(c)) {
1201 return reply_msg(c, MSG_DEADLINE_SOON);
1204 /* try to get a new job for this guy */
1205 wait_for_job(c, timeout);
1206 process_queue();
1207 break;
1208 case OP_DELETE:
1209 errno = 0;
1210 id = strtoull(c->cmd + CMD_DELETE_LEN, &end_buf, 10);
1211 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1212 op_ct[type]++;
1214 j = job_find(id);
1215 j = remove_reserved_job(c, j) ? :
1216 remove_ready_job(j) ? :
1217 remove_buried_job(j);
1219 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1221 j->state = JOB_STATE_INVALID;
1222 r = binlog_write_job(j);
1223 job_free(j);
1225 if (!r) return reply_serr(c, MSG_INTERNAL_ERROR);
1227 reply(c, MSG_DELETED, MSG_DELETED_LEN, STATE_SENDWORD);
1228 break;
1229 case OP_RELEASE:
1230 errno = 0;
1231 id = strtoull(c->cmd + CMD_RELEASE_LEN, &pri_buf, 10);
1232 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1234 r = read_pri(&pri, pri_buf, &delay_buf);
1235 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1237 r = read_delay(&delay, delay_buf, NULL);
1238 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1239 op_ct[type]++;
1241 j = remove_reserved_job(c, job_find(id));
1243 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1245 /* We want to update the delay deadline on disk, so reserve space for
1246 * that. */
1247 if (delay) {
1248 z = binlog_reserve_space_update(j);
1249 if (!z) return reply_serr(c, MSG_OUT_OF_MEMORY);
1250 j->reserved_binlog_space += z;
1253 j->pri = pri;
1254 j->delay = delay;
1255 j->release_ct++;
1257 r = enqueue_job(j, delay, !!delay);
1258 if (r < 0) return reply_serr(c, MSG_INTERNAL_ERROR);
1259 if (r == 1) {
1260 return reply(c, MSG_RELEASED, MSG_RELEASED_LEN, STATE_SENDWORD);
1263 /* out of memory trying to grow the queue, so it gets buried */
1264 bury_job(j, 0);
1265 reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD);
1266 break;
1267 case OP_BURY:
1268 errno = 0;
1269 id = strtoull(c->cmd + CMD_BURY_LEN, &pri_buf, 10);
1270 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1272 r = read_pri(&pri, pri_buf, NULL);
1273 if (r) return reply_msg(c, MSG_BAD_FORMAT);
1274 op_ct[type]++;
1276 j = remove_reserved_job(c, job_find(id));
1278 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1280 j->pri = pri;
1281 r = bury_job(j, 1);
1282 if (!r) return reply_serr(c, MSG_INTERNAL_ERROR);
1283 reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD);
1284 break;
1285 case OP_KICK:
1286 errno = 0;
1287 count = strtoul(c->cmd + CMD_KICK_LEN, &end_buf, 10);
1288 if (end_buf == c->cmd + CMD_KICK_LEN) {
1289 return reply_msg(c, MSG_BAD_FORMAT);
1291 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1293 op_ct[type]++;
1295 i = kick_jobs(c->use, count);
1297 return reply_line(c, STATE_SENDWORD, "KICKED %u\r\n", i);
1298 case OP_TOUCH:
1299 errno = 0;
1300 id = strtoull(c->cmd + CMD_TOUCH_LEN, &end_buf, 10);
1301 if (errno) return twarn("strtoull"), reply_msg(c, MSG_BAD_FORMAT);
1303 op_ct[type]++;
1305 j = touch_job(c, job_find(id));
1307 if (j) {
1308 reply(c, MSG_TOUCHED, MSG_TOUCHED_LEN, STATE_SENDWORD);
1309 } else {
1310 return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1312 break;
1313 case OP_STATS:
1314 /* don't allow trailing garbage */
1315 if (c->cmd_len != CMD_STATS_LEN + 2) {
1316 return reply_msg(c, MSG_BAD_FORMAT);
1319 op_ct[type]++;
1321 do_stats(c, fmt_stats, NULL);
1322 break;
1323 case OP_JOBSTATS:
1324 errno = 0;
1325 id = strtoull(c->cmd + CMD_JOBSTATS_LEN, &end_buf, 10);
1326 if (errno) return reply_msg(c, MSG_BAD_FORMAT);
1328 op_ct[type]++;
1330 j = peek_job(id);
1331 if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD);
1333 if (!j->tube) return reply_serr(c, MSG_INTERNAL_ERROR);
1334 do_stats(c, (fmt_fn) fmt_job_stats, j);
1335 break;
1336 case OP_STATS_TUBE:
1337 name = c->cmd + CMD_STATS_TUBE_LEN;
1338 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1340 op_ct[type]++;
1342 t = tube_find(name);
1343 if (!t) return reply_msg(c, MSG_NOTFOUND);
1345 do_stats(c, (fmt_fn) fmt_stats_tube, t);
1346 t = NULL;
1347 break;
1348 case OP_LIST_TUBES:
1349 /* don't allow trailing garbage */
1350 if (c->cmd_len != CMD_LIST_TUBES_LEN + 2) {
1351 return reply_msg(c, MSG_BAD_FORMAT);
1354 op_ct[type]++;
1355 do_list_tubes(c, &tubes);
1356 break;
1357 case OP_LIST_TUBE_USED:
1358 /* don't allow trailing garbage */
1359 if (c->cmd_len != CMD_LIST_TUBE_USED_LEN + 2) {
1360 return reply_msg(c, MSG_BAD_FORMAT);
1363 op_ct[type]++;
1364 reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name);
1365 break;
1366 case OP_LIST_TUBES_WATCHED:
1367 /* don't allow trailing garbage */
1368 if (c->cmd_len != CMD_LIST_TUBES_WATCHED_LEN + 2) {
1369 return reply_msg(c, MSG_BAD_FORMAT);
1372 op_ct[type]++;
1373 do_list_tubes(c, &c->watch);
1374 break;
1375 case OP_USE:
1376 name = c->cmd + CMD_USE_LEN;
1377 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1378 op_ct[type]++;
1380 TUBE_ASSIGN(t, tube_find_or_make(name));
1381 if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY);
1383 c->use->using_ct--;
1384 TUBE_ASSIGN(c->use, t);
1385 TUBE_ASSIGN(t, NULL);
1386 c->use->using_ct++;
1388 reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name);
1389 break;
1390 case OP_WATCH:
1391 name = c->cmd + CMD_WATCH_LEN;
1392 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1393 op_ct[type]++;
1395 TUBE_ASSIGN(t, tube_find_or_make(name));
1396 if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY);
1398 r = 1;
1399 if (!ms_contains(&c->watch, t)) r = ms_append(&c->watch, t);
1400 TUBE_ASSIGN(t, NULL);
1401 if (!r) return reply_serr(c, MSG_OUT_OF_MEMORY);
1403 reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used);
1404 break;
1405 case OP_IGNORE:
1406 name = c->cmd + CMD_IGNORE_LEN;
1407 if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT);
1408 op_ct[type]++;
1410 t = NULL;
1411 for (i = 0; i < c->watch.used; i++) {
1412 t = c->watch.items[i];
1413 if (strncmp(t->name, name, MAX_TUBE_NAME_LEN) == 0) break;
1414 t = NULL;
1417 if (t && c->watch.used < 2) return reply_msg(c, MSG_NOT_IGNORED);
1419 if (t) ms_remove(&c->watch, t); /* may free t if refcount => 0 */
1420 t = NULL;
1422 reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used);
1423 break;
1424 default:
1425 return reply_msg(c, MSG_UNKNOWN_COMMAND);
1429 /* There are three reasons this function may be called. We need to check for
1430 * all of them.
1432 * 1. A reserved job has run out of time.
1433 * 2. A waiting client's reserved job has entered the safety margin.
1434 * 3. A waiting client's requested timeout has occurred.
1436 * If any of these happen, we must do the appropriate thing. */
1437 static void
1438 h_conn_timeout(conn c)
1440 int r, should_timeout = 0;
1441 job j;
1443 /* Check if the client was trying to reserve a job. */
1444 if (conn_waiting(c) && conn_has_close_deadline(c)) should_timeout = 1;
1446 /* Check if any reserved jobs have run out of time. We should do this
1447 * whether or not the client is waiting for a new reservation. */
1448 while ((j = soonest_job(c))) {
1449 if (j->deadline_at >= now_usec()) break;
1451 /* This job is in the middle of being written out. If we return it to
1452 * the ready queue, someone might free it before we finish writing it
1453 * out to the socket. So we'll copy it here and free the copy when it's
1454 * done sending. */
1455 if (j == c->out_job) {
1456 c->out_job = job_copy(c->out_job);
1459 timeout_ct++; /* stats */
1460 j->timeout_ct++;
1461 r = enqueue_job(remove_this_reserved_job(c, j), 0, 0);
1462 if (r < 1) bury_job(j, 0); /* out of memory, so bury it */
1463 r = conn_update_evq(c, c->evq.ev_events);
1464 if (r == -1) return twarnx("conn_update_evq() failed"), conn_close(c);
1467 if (should_timeout) {
1468 dprintf("conn_waiting(%p) = %d\n", c, conn_waiting(c));
1469 return reply_msg(remove_waiting_conn(c), MSG_DEADLINE_SOON);
1470 } else if (conn_waiting(c) && c->pending_timeout >= 0) {
1471 dprintf("conn_waiting(%p) = %d\n", c, conn_waiting(c));
1472 c->pending_timeout = -1;
1473 return reply_msg(remove_waiting_conn(c), MSG_TIMED_OUT);
1477 void
1478 enter_drain_mode(int sig)
1480 drain_mode = 1;
1483 static void
1484 do_cmd(conn c)
1486 dispatch_cmd(c);
1487 fill_extra_data(c);
1490 static void
1491 reset_conn(conn c)
1493 int r;
1495 r = conn_update_evq(c, EV_READ | EV_PERSIST);
1496 if (r == -1) return twarnx("update events failed"), conn_close(c);
1498 /* was this a peek or stats command? */
1499 if (c->out_job && c->out_job->state == JOB_STATE_COPY) job_free(c->out_job);
1500 c->out_job = NULL;
1502 c->reply_sent = 0; /* now that we're done, reset this */
1503 c->state = STATE_WANTCOMMAND;
1506 static void
1507 h_conn_data(conn c)
1509 int r, to_read;
1510 job j;
1511 struct iovec iov[2];
1513 switch (c->state) {
1514 case STATE_WANTCOMMAND:
1515 r = read(c->fd, c->cmd + c->cmd_read, LINE_BUF_SIZE - c->cmd_read);
1516 if (r == -1) return check_err(c, "read()");
1517 if (r == 0) return conn_close(c); /* the client hung up */
1519 c->cmd_read += r; /* we got some bytes */
1521 c->cmd_len = cmd_len(c); /* find the EOL */
1523 /* yay, complete command line */
1524 if (c->cmd_len) return do_cmd(c);
1526 /* c->cmd_read > LINE_BUF_SIZE can't happen */
1528 /* command line too long? */
1529 if (c->cmd_read == LINE_BUF_SIZE) {
1530 c->cmd_read = 0; /* discard the input so far */
1531 return reply_msg(c, MSG_BAD_FORMAT);
1534 /* otherwise we have an incomplete line, so just keep waiting */
1535 break;
1536 case STATE_BITBUCKET:
1537 /* Invert the meaning of in_job_read while throwing away data -- it
1538 * counts the bytes that remain to be thrown away. */
1539 to_read = min(c->in_job_read, BUCKET_BUF_SIZE);
1540 r = read(c->fd, bucket, to_read);
1541 if (r == -1) return check_err(c, "read()");
1542 if (r == 0) return conn_close(c); /* the client hung up */
1544 c->in_job_read -= r; /* we got some bytes */
1546 /* (c->in_job_read < 0) can't happen */
1548 if (c->in_job_read == 0) return reply_serr(c, MSG_OUT_OF_MEMORY);
1549 break;
1550 case STATE_WANTDATA:
1551 j = c->in_job;
1553 r = read(c->fd, j->body + c->in_job_read, j->body_size -c->in_job_read);
1554 if (r == -1) return check_err(c, "read()");
1555 if (r == 0) return conn_close(c); /* the client hung up */
1557 c->in_job_read += r; /* we got some bytes */
1559 /* (j->in_job_read > j->body_size) can't happen */
1561 maybe_enqueue_incoming_job(c);
1562 break;
1563 case STATE_SENDWORD:
1564 r= write(c->fd, c->reply + c->reply_sent, c->reply_len - c->reply_sent);
1565 if (r == -1) return check_err(c, "write()");
1566 if (r == 0) return conn_close(c); /* the client hung up */
1568 c->reply_sent += r; /* we got some bytes */
1570 /* (c->reply_sent > c->reply_len) can't happen */
1572 if (c->reply_sent == c->reply_len) return reset_conn(c);
1574 /* otherwise we sent an incomplete reply, so just keep waiting */
1575 break;
1576 case STATE_SENDJOB:
1577 j = c->out_job;
1579 iov[0].iov_base = (void *)(c->reply + c->reply_sent);
1580 iov[0].iov_len = c->reply_len - c->reply_sent; /* maybe 0 */
1581 iov[1].iov_base = j->body + c->out_job_sent;
1582 iov[1].iov_len = j->body_size - c->out_job_sent;
1584 r = writev(c->fd, iov, 2);
1585 if (r == -1) return check_err(c, "writev()");
1586 if (r == 0) return conn_close(c); /* the client hung up */
1588 /* update the sent values */
1589 c->reply_sent += r;
1590 if (c->reply_sent >= c->reply_len) {
1591 c->out_job_sent += c->reply_sent - c->reply_len;
1592 c->reply_sent = c->reply_len;
1595 /* (c->out_job_sent > j->body_size) can't happen */
1597 /* are we done? */
1598 if (c->out_job_sent == j->body_size) return reset_conn(c);
1600 /* otherwise we sent incomplete data, so just keep waiting */
1601 break;
1602 case STATE_WAIT: /* keep an eye out in case they hang up */
1603 /* but don't hang up just because our buffer is full */
1604 if (LINE_BUF_SIZE - c->cmd_read < 1) break;
1606 r = read(c->fd, c->cmd + c->cmd_read, LINE_BUF_SIZE - c->cmd_read);
1607 if (r == -1) return check_err(c, "read()");
1608 if (r == 0) return conn_close(c); /* the client hung up */
1609 c->cmd_read += r; /* we got some bytes */
1613 #define want_command(c) ((c)->fd && ((c)->state == STATE_WANTCOMMAND))
1614 #define cmd_data_ready(c) (want_command(c) && (c)->cmd_read)
1616 static void
1617 h_conn(const int fd, const short which, conn c)
1619 if (fd != c->fd) {
1620 twarnx("Argh! event fd doesn't match conn fd.");
1621 close(fd);
1622 return conn_close(c);
1625 switch (which) {
1626 case EV_TIMEOUT:
1627 h_conn_timeout(c);
1628 event_add(&c->evq, NULL); /* seems to be necessary */
1629 break;
1630 case EV_READ:
1631 /* fall through... */
1632 case EV_WRITE:
1633 /* fall through... */
1634 default:
1635 h_conn_data(c);
1638 while (cmd_data_ready(c) && (c->cmd_len = cmd_len(c))) do_cmd(c);
1641 static void
1642 h_delay()
1644 int r;
1645 job j;
1646 usec t;
1648 t = now_usec();
1649 while ((j = delay_q_peek())) {
1650 if (j->deadline_at > t) break;
1651 j = delay_q_take();
1652 r = enqueue_job(j, 0, 0);
1653 if (r < 1) bury_job(j, 0); /* out of memory, so bury it */
1656 set_main_delay_timeout();
1659 void
1660 h_accept(const int fd, const short which, struct event *ev)
1662 conn c;
1663 int cfd, flags, r;
1664 socklen_t addrlen;
1665 struct sockaddr addr;
1667 if (which == EV_TIMEOUT) return h_delay();
1669 addrlen = sizeof addr;
1670 cfd = accept(fd, &addr, &addrlen);
1671 if (cfd == -1) {
1672 if (errno != EAGAIN && errno != EWOULDBLOCK) twarn("accept()");
1673 if (errno == EMFILE) brake();
1674 return;
1677 flags = fcntl(cfd, F_GETFL, 0);
1678 if (flags < 0) return twarn("getting flags"), close(cfd), v();
1680 r = fcntl(cfd, F_SETFL, flags | O_NONBLOCK);
1681 if (r < 0) return twarn("setting O_NONBLOCK"), close(cfd), v();
1683 c = make_conn(cfd, STATE_WANTCOMMAND, default_tube, default_tube);
1684 if (!c) return twarnx("make_conn() failed"), close(cfd), brake();
1686 dprintf("accepted conn, fd=%d\n", cfd);
1687 r = conn_set_evq(c, EV_READ | EV_PERSIST, (evh) h_conn);
1688 if (r == -1) return twarnx("conn_set_evq() failed"), close(cfd), brake();
1691 void
1692 prot_init()
1694 started_at = now_usec();
1695 memset(op_ct, 0, sizeof(op_ct));
1697 ms_init(&tubes, NULL, NULL);
1699 TUBE_ASSIGN(default_tube, tube_find_or_make("default"));
1700 if (!default_tube) twarnx("Out of memory during startup!");
1703 void
1704 prot_replay_binlog(job binlog_jobs)
1706 job j, nj;
1707 usec delay;
1708 int r;
1710 for (j = binlog_jobs->next ; j != binlog_jobs ; j = nj) {
1711 nj = j->next;
1712 job_remove(j);
1713 binlog_reserve_space_update(j); /* reserve space for a delete */
1714 delay = 0;
1715 switch (j->state) {
1716 case JOB_STATE_BURIED:
1717 bury_job(j, 0);
1718 break;
1719 case JOB_STATE_DELAYED:
1720 if (started_at < j->deadline_at) {
1721 delay = j->deadline_at - started_at;
1723 /* fall through */
1724 default:
1725 r = enqueue_job(j, delay, 0);
1726 if (r < 1) twarnx("error processing binlog job %llu", j->id);