Skip to content

Commit

Permalink
Don't allow two beanstalkds to run in one dir.
Browse files Browse the repository at this point in the history
  • Loading branch information
kr committed Dec 24, 2008
1 parent b92ee5f commit c7caf2d
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
7 changes: 7 additions & 0 deletions beanstalkd.c
Expand Up @@ -253,6 +253,13 @@ main(int argc, char **argv)
job_init();
prot_init();

/* We want to make sure that only one beanstalkd tries to use the binlog
* directory at a time. So acquire a lock now and never release it. */
if (binlog_dir) {
r = binlog_lock();
if (!r) twarnx("failed to lock binlog dir %s", binlog_dir), exit(10);
}

r = make_server_socket(host_addr, port);
if (r == -1) twarnx("make_server_socket()"), exit(111);

Expand Down
24 changes: 24 additions & 0 deletions binlog.c
Expand Up @@ -42,6 +42,7 @@ static int binlog_index = 0;
static int binlog_fd = -1;
static int binlog_version = 1;
static size_t bytes_written;
static int lock_fd;

static binlog first_binlog = NULL, last_binlog = NULL;

Expand Down Expand Up @@ -356,6 +357,29 @@ binlog_read(job binlog_jobs)
}
}

int
binlog_lock()
{
int r;
struct flock lock;
char path[PATH_MAX];

r = snprintf(path, PATH_MAX, "%s/lock", binlog_dir);
if (r > PATH_MAX) return twarnx("path too long: %s", binlog_dir), 0;

lock_fd = open(path, O_WRONLY|O_CREAT, 0600);
if (lock_fd == -1) return twarn("open"), 0;

lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
r = fcntl(lock_fd, F_SETLK, &lock);
if (r) return twarn("fcntl"), 0;

return 1;
}

void
binlog_init()
{
Expand Down
3 changes: 3 additions & 0 deletions binlog.h
Expand Up @@ -32,6 +32,9 @@ struct binlog {
extern char *binlog_dir;
extern size_t binlog_size_limit;

/* Return the number of locks acquired: either 0 or 1. */
int binlog_lock();

void binlog_write_job(job j);
void binlog_read(job binlog_jobs);
void binlog_close();
Expand Down

0 comments on commit c7caf2d

Please sign in to comment.