Fix build on FreeBSD.
[beanstalkd.git] / binlog.c
blob34bd778fcec175407d4ead3aa4a0140f58beaf16
1 /* binlog.c - binary log implementation */
3 /* Copyright (C) 2008 Graham Barr
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 #if HAVE_STDINT_H
22 # include <stdint.h>
23 #endif /* else we get int types from config.h */
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <dirent.h>
32 #include <sys/resource.h>
33 #include <sys/param.h>
34 #include <sys/uio.h>
35 #include <sys/stat.h>
36 #include <stdarg.h>
37 #include <limits.h>
38 #include <stddef.h>
40 #include "tube.h"
41 #include "job.h"
42 #include "binlog.h"
43 #include "util.h"
44 #include "port.h"
46 typedef struct binlog *binlog;
48 struct binlog {
49 binlog next;
50 unsigned int refs;
51 int fd;
52 size_t free;
53 size_t reserved;
54 char path[];
57 /* max size we will create a log file */
58 size_t binlog_size_limit = BINLOG_SIZE_LIMIT_DEFAULT;
60 int enable_fsync = 0;
61 size_t fsync_throttle_ms = 0;
62 uint64_t last_fsync = 0;
64 char *binlog_dir = NULL;
65 static int binlog_index = 0;
66 static int binlog_version = 5;
67 static int lock_fd;
69 static binlog oldest_binlog = 0,
70 current_binlog = 0,
71 newest_binlog = 0;
73 static const size_t job_record_size = offsetof(struct job, pad);
75 static int
76 binlog_scan_dir()
78 DIR *dirp;
79 struct dirent *dp;
80 long min = 0;
81 long max = 0;
82 long val;
83 char *endptr;
84 size_t name_len;
86 dirp = opendir(binlog_dir);
87 if (!dirp) return 0;
89 while ((dp = readdir(dirp)) != NULL) {
90 name_len = strlen(dp->d_name);
91 if (name_len > 7 && !strncmp("binlog.", dp->d_name, 7)) {
92 val = strtol(dp->d_name + 7, &endptr, 10);
93 if (endptr && *endptr == 0) {
94 if (max == 0 || val > max) max = val;
95 if (min == 0 || val < min) min = val;
100 closedir(dirp);
101 binlog_index = (int) max;
102 return (int) min;
105 static void
106 binlog_remove_oldest()
108 binlog b = oldest_binlog;
110 if (!b) return;
112 oldest_binlog = b->next;
114 unlink(b->path);
115 free(b);
118 static binlog
119 binlog_iref(binlog b)
121 if (b) b->refs++;
122 return b;
125 static void
126 binlog_dref(binlog b)
128 if (!b) return;
129 if (b->refs < 1) return twarnx("refs is zero for binlog: %s", b->path);
131 --b->refs;
132 if (b->refs < 1) {
133 while (oldest_binlog && oldest_binlog->refs == 0) {
134 binlog_remove_oldest();
140 static void
141 binlog_warn(int fd, const char* path, const char *msg)
143 warnx("WARNING, %s at %s:%u.\n%s", msg, path, lseek(fd, 0, SEEK_CUR),
144 " Continuing. You may be missing data.");
148 #define binlog_warn(b, fmt, args...) \
149 warnx("WARNING, " fmt " at %s:%u. %s: ", \
150 ##args, b->path, lseek(b->fd, 0, SEEK_CUR), \
151 "Continuing. You may be missing data.")
153 static void
154 binlog_read_log_file(binlog b, job binlog_jobs)
156 struct job js;
157 tube t;
158 job j;
159 char tubename[MAX_TUBE_NAME_LEN];
160 size_t namelen;
161 ssize_t r;
162 int version;
164 r = read(b->fd, &version, sizeof(version));
165 if (r == -1) return twarn("read()");
166 if (r < sizeof(version)) {
167 return binlog_warn(b, "EOF while reading version record");
170 if (version != binlog_version) {
171 return warnx("%s: binlog version mismatch %d %d", b->path, version,
172 binlog_version);
175 while (read(b->fd, &namelen, sizeof(size_t)) == sizeof(size_t)) {
176 if (namelen > 0) {
177 r = read(b->fd, tubename, namelen);
178 if (r == -1) return twarn("read()");
179 if (r < namelen) {
180 lseek(b->fd, SEEK_CUR, 0);
181 return binlog_warn(b, "EOF while reading tube name");
185 tubename[namelen] = '\0';
186 r = read(b->fd, &js, job_record_size);
187 if (r == -1) return twarn("read()");
188 if (r < job_record_size) {
189 return binlog_warn(b, "EOF while reading job record");
192 if (!js.id) break;
194 j = job_find(js.id);
195 switch (js.state) {
196 case JOB_STATE_INVALID:
197 if (j) {
198 job_remove(j);
199 binlog_dref(j->binlog);
200 job_free(j);
201 j = NULL;
203 break;
204 case JOB_STATE_READY:
205 case JOB_STATE_DELAYED:
206 if (!j && namelen > 0) {
207 t = tube_find_or_make(tubename);
208 j = make_job_with_id(js.pri, js.delay, js.ttr, js.body_size,
209 t, js.id);
210 j->next = j->prev = j;
211 j->created_at = js.created_at;
212 job_insert(binlog_jobs, j);
214 if (js.body_size) {
215 if (js.body_size > j->body_size) {
216 warnx("job size increased from %zu to %zu", j->body_size,
217 js.body_size);
218 job_remove(j);
219 binlog_dref(j->binlog);
220 job_free(j);
221 return binlog_warn(b, "EOF while reading job body");
223 r = read(b->fd, j->body, js.body_size);
224 if (r == -1) return twarn("read()");
225 if (r < js.body_size) {
226 warnx("dropping incomplete job %llu", j->id);
227 job_remove(j);
228 binlog_dref(j->binlog);
229 job_free(j);
230 return binlog_warn(b, "EOF while reading job body");
233 break;
235 if (j) {
236 j->state = js.state;
237 j->deadline_at = js.deadline_at;
238 j->pri = js.pri;
239 j->delay = js.delay;
240 j->ttr = js.ttr;
241 j->timeout_ct = js.timeout_ct;
242 j->release_ct = js.release_ct;
243 j->bury_ct = js.bury_ct;
244 j->kick_ct = js.kick_ct;
246 /* this is a complete record, so we can move the binlog ref */
247 if (namelen && js.body_size) {
248 binlog_dref(j->binlog);
249 j->binlog = binlog_iref(b);
255 static void
256 binlog_close(binlog b)
258 if (!b) return;
259 if (b->fd < 0) return;
260 close(b->fd);
261 b->fd = -1;
262 binlog_dref(b);
265 static binlog
266 make_binlog(char *path)
268 binlog b;
270 b = (binlog) malloc(sizeof(struct binlog) + strlen(path) + 1);
271 if (!b) return twarnx("OOM"), (binlog) 0;
272 strcpy(b->path, path);
273 b->refs = 0;
274 b->next = NULL;
275 b->fd = -1;
276 b->free = 0;
277 b->reserved = 0;
278 return b;
281 static binlog
282 make_next_binlog()
284 int r;
285 char path[PATH_MAX];
287 if (!binlog_dir) return NULL;
289 r = snprintf(path, PATH_MAX, "%s/binlog.%d", binlog_dir, ++binlog_index);
290 if (r > PATH_MAX) return twarnx("path too long: %s", binlog_dir), (binlog)0;
292 return make_binlog(path);
295 static binlog
296 add_binlog(binlog b)
298 if (newest_binlog) newest_binlog->next = b;
299 newest_binlog = b;
300 if (!oldest_binlog) oldest_binlog = b;
302 return b;
305 static int
306 beanstalkd_fallocate(int fd, off_t offset, off_t len)
308 off_t i;
309 ssize_t w;
310 off_t p;
311 #define ZERO_BUF_SIZE 512
312 char buf[ZERO_BUF_SIZE] = {}; /* initialize to zero */
314 /* we only support a 0 offset */
315 if (offset != 0) return EINVAL;
317 if (len <= 0) return EINVAL;
319 for (i = 0; i < len; i += w) {
320 w = write(fd, &buf, ZERO_BUF_SIZE);
321 if (w == -1) return errno;
324 p = lseek(fd, 0, SEEK_SET);
325 if (p == -1) return errno;
327 return 0;
330 static void
331 binlog_open(binlog log, size_t *written)
333 int fd;
334 size_t bytes_written;
336 if (written) *written = 0;
338 if (!binlog_iref(log)) return;
340 fd = open(log->path, O_WRONLY | O_CREAT, 0400);
342 if (fd < 0) return twarn("Cannot open binlog %s", log->path);
344 #ifdef HAVE_POSIX_FALLOCATE
346 int r;
347 r = posix_fallocate(fd, 0, binlog_size_limit);
348 if (r == EINVAL) {
349 r = beanstalkd_fallocate(fd, 0, binlog_size_limit);
351 if (r) {
352 close(fd);
353 binlog_dref(log);
354 errno = r;
355 return twarn("Cannot allocate space for binlog %s", log->path);
358 #else
359 /* Allocate space in a slow but portable way. */
361 int r;
362 r = beanstalkd_fallocate(fd, 0, binlog_size_limit);
363 if (r) {
364 close(fd);
365 binlog_dref(log);
366 errno = r;
367 return twarn("Cannot allocate space for binlog %s", log->path);
370 #endif
372 bytes_written = write(fd, &binlog_version, sizeof(int));
373 if (written) *written = bytes_written;
375 if (bytes_written < sizeof(int)) {
376 twarn("Cannot write to binlog");
377 close(fd);
378 binlog_dref(log);
379 return;
382 log->fd = fd;
385 /* returns 1 on success, 0 on error. */
386 static int
387 binlog_use_next()
389 binlog next;
391 if (!current_binlog) return 0;
393 next = current_binlog->next;
395 if (!next) return 0;
397 /* assert(current_binlog->reserved == 0); */
399 binlog_close(current_binlog);
400 current_binlog = next;
402 return 1;
405 void
406 binlog_shutdown()
408 binlog_use_next();
409 binlog_close(current_binlog);
412 /* Returns the number of jobs successfully written (either 0 or 1).
414 If this fails, something is seriously wrong. It should never fail because of
415 a full disk. (The binlog_reserve_space_* functions, on the other hand, can
416 fail because of a full disk.)
418 If we are not using the binlog at all (!current_binlog), then we pretend to
419 have made a successful write and return 1. */
421 binlog_write_job(job j)
423 ssize_t written;
424 size_t tube_namelen, to_write = 0;
425 struct iovec vec[4], *vptr;
426 int vcnt = 3, r;
427 uint64_t now;
429 if (!current_binlog) return 1;
430 tube_namelen = 0;
432 vec[0].iov_base = (char *) &tube_namelen;
433 to_write += vec[0].iov_len = sizeof(size_t);
435 vec[1].iov_base = j->tube->name;
436 vec[1].iov_len = 0;
438 vec[2].iov_base = (char *) j;
439 to_write += vec[2].iov_len = job_record_size;
441 if (j->state == JOB_STATE_READY || j->state == JOB_STATE_DELAYED) {
442 if (!j->binlog) {
443 tube_namelen = strlen(j->tube->name);
444 to_write += vec[1].iov_len = tube_namelen;
445 vcnt = 4;
446 vec[3].iov_base = j->body;
447 to_write += vec[3].iov_len = j->body_size;
449 } else if (j->state == JOB_STATE_INVALID) {
450 if (j->binlog) binlog_dref(j->binlog);
451 j->binlog = NULL;
452 } else {
453 return twarnx("unserializable job state: %d", j->state), 0;
456 if (to_write > current_binlog->reserved) {
457 r = binlog_use_next();
458 if (!r) return twarnx("failed to use next binlog"), 0;
461 if (j->state && !j->binlog) j->binlog = binlog_iref(current_binlog);
463 while (to_write > 0) {
464 written = writev(current_binlog->fd, vec, vcnt);
466 if (written < 0) {
467 if (errno == EAGAIN) continue;
468 if (errno == EINTR) continue;
470 twarn("writev");
471 binlog_close(current_binlog);
472 current_binlog = 0;
473 return 0;
476 to_write -= written;
477 if (to_write > 0 && written > 0) {
478 for (vptr = vec; written >= vptr->iov_len; vptr++) {
479 written -= vptr->iov_len;
480 vptr->iov_len = 0;
482 vptr->iov_base = (char *) vptr->iov_base + written;
483 vptr->iov_len -= written;
485 current_binlog->reserved -= written;
486 j->reserved_binlog_space -= written;
489 now = now_usec() / 1000; /* usec -> msec */
490 if (enable_fsync && now - last_fsync >= fsync_throttle_ms) {
491 r = fdatasync(current_binlog->fd);
492 if (r == -1) return twarn("fdatasync"), 0;
493 last_fsync = now;
496 return 1;
499 static binlog
500 make_future_binlog()
502 binlog b;
503 size_t header;
505 /* open a new binlog with more space to reserve */
506 b = make_next_binlog();
507 if (!b) return twarnx("error making next binlog"), (binlog) 0;
508 binlog_open(b, &header);
510 /* open failed, so we can't reserve any space */
511 if (b->fd < 0) {
512 free(b);
513 return 0;
516 b->free = binlog_size_limit - header;
517 b->reserved = 0;
518 return b;
521 static int
522 can_move_reserved(size_t n, binlog from, binlog to)
524 return from->reserved >= n && to->free >= n;
527 static void
528 move_reserved(size_t n, binlog from, binlog to)
530 from->reserved -= n;
531 from->free += n;
532 to->reserved += n;
533 to->free -= n;
536 static size_t
537 ensure_free_space(size_t n)
539 binlog fb;
541 if (newest_binlog && newest_binlog->free >= n) return n;
543 /* open a new binlog */
544 fb = make_future_binlog();
545 if (!fb) return twarnx("make_future_binlog"), 0;
547 add_binlog(fb);
548 return n;
551 /* Preserve some invariants immediately after any space reservation.
552 * Invariant 1: current_binlog->reserved >= n.
553 * Invariant 2: current_binlog->reserved is congruent to n (mod z), where z
554 * is the size of a delete record in the binlog. */
555 static size_t
556 maintain_invariant(size_t n)
558 size_t reserved_later, remainder, complement, z, r;
560 /* In this function, reserved bytes are conserved (they are neither created
561 * nor destroyed). We just move them around to preserve the invariant. We
562 * might have to create new free space (i.e. allocate a new binlog file),
563 * though. */
565 /* Invariant 1. */
566 /* This is a loop, but it's guaranteed to run at most once. The proof is
567 * left as an exercise for the reader. */
568 while (current_binlog->reserved < n) {
569 size_t to_move = current_binlog->reserved;
571 r = ensure_free_space(to_move);
572 if (r != to_move) {
573 twarnx("ensure_free_space");
574 if (newest_binlog->reserved >= n) {
575 newest_binlog->reserved -= n;
576 } else {
577 twarnx("failed to unreserve %zd bytes", n); /* can't happen */
579 return 0;
582 move_reserved(to_move, current_binlog, newest_binlog);
583 binlog_use_next();
587 /* Invariant 2. */
589 z = sizeof(size_t) + job_record_size;
590 reserved_later = current_binlog->reserved - n;
591 remainder = reserved_later % z;
592 if (remainder == 0) return n;
593 complement = z - remainder;
594 if (can_move_reserved(complement, newest_binlog, current_binlog)) {
595 move_reserved(complement, newest_binlog, current_binlog);
596 return n;
599 r = ensure_free_space(remainder);
600 if (r != remainder) {
601 twarnx("ensure_free_space");
602 if (newest_binlog->reserved >= n) {
603 newest_binlog->reserved -= n;
604 } else {
605 twarnx("failed to unreserve %zd bytes", n); /* can't happen */
607 return 0;
609 move_reserved(remainder, current_binlog, newest_binlog);
611 return n;
614 /* Returns the number of bytes successfully reserved: either 0 or n. */
615 static size_t
616 binlog_reserve_space(size_t n)
618 size_t r;
620 /* This return value must be nonzero but is otherwise ignored. */
621 if (!current_binlog) return 1;
623 if (current_binlog->free >= n) {
624 current_binlog->free -= n;
625 current_binlog->reserved += n;
626 return maintain_invariant(n);
629 r = ensure_free_space(n);
630 if (r != n) return twarnx("ensure_free_space"), 0;
632 newest_binlog->free -= n;
633 newest_binlog->reserved += n;
634 return maintain_invariant(n);
637 /* Returns the number of bytes reserved. */
638 size_t
639 binlog_reserve_space_put(job j)
641 size_t z = 0;
643 /* reserve space for the initial job record */
644 z += sizeof(size_t);
645 z += strlen(j->tube->name);
646 z += job_record_size;
647 z += j->body_size;
649 /* plus space for a delete to come later */
650 z += sizeof(size_t);
651 z += job_record_size;
653 return binlog_reserve_space(z);
656 size_t
657 binlog_reserve_space_update(job j)
659 size_t z = 0;
661 z += sizeof(size_t);
662 z += job_record_size;
663 return binlog_reserve_space(z);
667 binlog_lock()
669 int r;
670 struct flock lock;
671 char path[PATH_MAX];
673 r = snprintf(path, PATH_MAX, "%s/lock", binlog_dir);
674 if (r > PATH_MAX) return twarnx("path too long: %s", binlog_dir), 0;
676 lock_fd = open(path, O_WRONLY|O_CREAT, 0600);
677 if (lock_fd == -1) return twarn("open"), 0;
679 lock.l_type = F_WRLCK;
680 lock.l_whence = SEEK_SET;
681 lock.l_start = 0;
682 lock.l_len = 0;
683 r = fcntl(lock_fd, F_SETLK, &lock);
684 if (r) return twarn("fcntl"), 0;
686 return 1;
689 void
690 binlog_init(job binlog_jobs)
692 int binlog_index_min;
693 struct stat sbuf;
694 int fd, idx, r;
695 size_t n;
696 char path[PATH_MAX];
697 binlog b;
699 if (!binlog_dir) return;
701 /* Recover any jobs in old binlogs */
703 if (stat(binlog_dir, &sbuf) < 0) {
704 if (mkdir(binlog_dir, 0700) < 0) return twarn("%s", binlog_dir);
705 } else if (!(sbuf.st_mode & S_IFDIR)) {
706 twarnx("%s", binlog_dir);
707 return;
710 binlog_index_min = binlog_scan_dir();
712 if (binlog_index_min) {
713 for (idx = binlog_index_min; idx <= binlog_index; idx++) {
714 r = snprintf(path, PATH_MAX, "%s/binlog.%d", binlog_dir, idx);
715 if (r > PATH_MAX) return twarnx("path too long: %s", binlog_dir);
717 fd = open(path, O_RDONLY);
719 if (fd < 0) {
720 twarn("%s", path);
721 } else {
722 b = binlog_iref(add_binlog(make_binlog(path)));
723 b->fd = fd;
724 binlog_read_log_file(b, binlog_jobs);
725 close(fd);
726 b->fd = -1;
727 binlog_dref(b);
734 /* Set up for writing out new jobs */
735 n = ensure_free_space(1);
736 if (!n) return twarnx("error making first writable binlog");
738 current_binlog = newest_binlog;
741 const char *
742 binlog_oldest_index()
744 if (!oldest_binlog) return "0";
746 return strrchr(oldest_binlog->path, '.') + 1;
749 const char *
750 binlog_current_index()
752 if (!newest_binlog) return "0";
754 return strrchr(newest_binlog->path, '.') + 1;