forked from beanstalkd/beanstalkd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
110 lines (90 loc) · 2.5 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <stdint.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <fcntl.h>
#include "dat.h"
static void
su(const char *user)
{
int r;
struct passwd *pwent;
errno = 0;
pwent = getpwnam(user);
if (errno) twarn("getpwnam(\"%s\")", user), exit(32);
if (!pwent) twarnx("getpwnam(\"%s\"): no such user", user), exit(33);
r = setgid(pwent->pw_gid);
if (r == -1) twarn("setgid(%d \"%s\")", pwent->pw_gid, user), exit(34);
r = setuid(pwent->pw_uid);
if (r == -1) twarn("setuid(%d \"%s\")", pwent->pw_uid, user), exit(34);
}
void enter_disable_binlog(int sig) {
srv.wal.use = 0; // 直接动态取消wal: binlog
twarn("disable binlog");
}
static void
set_sig_handlers()
{
int r;
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sa.sa_flags = 0;
r = sigemptyset(&sa.sa_mask);
if (r == -1) twarn("sigemptyset()"), exit(111);
r = sigaction(SIGPIPE, &sa, 0);
if (r == -1) twarn("sigaction(SIGPIPE)"), exit(111);
// 进入drain mode
sa.sa_handler = enter_drain_mode;
r = sigaction(SIGUSR1, &sa, 0);
if (r == -1) twarn("sigaction(SIGUSR1)"), exit(111);
// 动态取消 binlog
sa.sa_handler = enter_disable_binlog;
r = sigaction(SIGUSR2, &sa, 0);
if (r == -1) twarn("sigaction(SIGUSR2)"), exit(111);
}
int
main(int argc, char **argv)
{
int r;
struct job list = {};
progname = argv[0];
setlinebuf(stdout);
optparse(&srv, argv+1);
if (verbose) {
printf("pid %d\n", getpid());
}
r = make_server_socket(srv.addr, srv.port);
if (r == -1) twarnx("make_server_socket()"), exit(111);
srv.sock.fd = r;
prot_init();
if (srv.user) su(srv.user);
set_sig_handlers();
// 如果启动binlog
if (srv.wal.use) {
// We want to make sure that only one beanstalkd tries
// to use the wal directory at a time. So acquire a lock
// now and never release it.
if (!waldirlock(&srv.wal)) {
twarnx("failed to lock wal dir %s", srv.wal.dir);
exit(10);
}
list.prev = list.next = &list;
walinit(&srv.wal, &list);
r = prot_replay(&srv, &list);
if (!r) {
twarnx("failed to replay log");
return 1;
}
r = prot_load_fanout(srv.wal.dir);
if (r) {
twarnx("failed to load fanout log");
return 1;
}
}
srvserve(&srv);
return 0;
}