worker: set monitor_has_run flag at initialization
[MogileFS-Server.git] / mogstored
blob11e3c44f65f638b884a31bc09077be4e7a3e5d0c
1 #!/usr/bin/perl
3 eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
4 if 0; # not running under some shell
7 # MogileFS storage node daemon
8 # (perlbal front-end)
10 # (c) 2004, Brad Fitzpatrick, <brad@danga.com>
11 # (c) 2006-2007, Six Apart, Ltd.
13 use strict;
14 use lib 'lib';
15 use Mogstored::HTTPServer;
17 use IO::Socket::INET;
18 use POSIX qw(WNOHANG);
19 use Perlbal 1.73;
20 use FindBin qw($Bin $RealScript);
22 use Mogstored::HTTPServer::Perlbal;
23 use Mogstored::HTTPServer::Lighttpd;
24 use Mogstored::HTTPServer::None;
25 use Mogstored::HTTPServer::Apache;
26 use Mogstored::SideChannelListener;
27 use Mogstored::SideChannelClient;
29 my $selfexe = "$Bin/$RealScript";
31 # State:
32 my %on_death; # pid -> subref (to run when pid dies)
33 my %devnum_to_device; # mogile device number (eg. 'dev1' would be '1') -> os device path (eg. '/dev/rd0')
34 my %osdevnum_to_device; # os device number (fetched via stat(file)[0]) -> os device path (ec. '/dev/rd0')
35 my %iostat_listeners; # fd => SideChannel client: clients interested in iostat data.
36 my $iostat_available = 1; # bool: iostat working. assume working to start.
37 my ($iostat_pipe_r, $iostat_pipe_w); # pipes for talking to iostat process
39 # Config:
40 my $opt_skipconfig;
41 my $opt_daemonize;
42 my $opt_config;
43 my $opt_iostat = 1; # default to on now
44 my $max_conns = 10000;
45 my $http_listen = "0.0.0.0:7500";
46 my $mgmt_listen = "0.0.0.0:7501";
47 my $docroot = "/var/mogdata";
48 my $default_config = "/etc/mogilefs/mogstored.conf";
49 my $server = $ENV{MOGSTORED_SERVER_TYPE} || "perlbal";
50 my $serverbin = "";
51 my $pidfile = undef;
53 # Rename binary in process list to make init scripts saner
54 $0 = "mogstored";
56 my %config_opts = (
57 'iostat' => \$opt_iostat,
58 's|skipconfig' => \$opt_skipconfig,
59 'daemonize|d' => \$opt_daemonize,
60 'config=s' => \$opt_config,
61 'httplisten=s' => \$http_listen,
62 'mgmtlisten=s' => \$mgmt_listen,
63 'docroot=s' => \$docroot,
64 'maxconns=i' => \$max_conns,
65 'server=s' => \$server,
66 'serverbin=s' => \$serverbin,
67 'pidfile=s' => \$pidfile,
69 usage() unless Getopt::Long::GetOptions(%config_opts);
71 die "Unknown server type. Valid options: --server={perlbal,lighttpd,apache,none}"
72 unless $server =~ /^perlbal|lighttpd|apache|none$/;
74 $opt_config = $default_config if ! $opt_config && -e $default_config;
75 load_config_file($opt_config => \%config_opts) if $opt_config && !$opt_skipconfig;
77 # initialize basic required Perlbal machinery, for any HTTP server
78 my $perlbal_init = qq{
79 CREATE SERVICE mogstored
80 SET role = web_server
81 SET docroot = $docroot
83 # don't listen... this is just a stub service.
84 CREATE SERVICE mgmt
85 SET role = management
86 ENABLE mgmt
88 $perlbal_init .= "\nSERVER pidfile = $pidfile" if defined($pidfile);
89 Perlbal::run_manage_commands($perlbal_init , sub { print STDERR "$_[0]\n"; });
91 # start HTTP server
92 my $httpsrv_class = "Mogstored::HTTPServer::" . ucfirst($server);
93 my $httpsrv = $httpsrv_class->new(
94 listen => $http_listen,
95 docroot => $docroot,
96 maxconns => $max_conns,
97 bin => $serverbin,
99 $httpsrv->start;
101 if ($opt_daemonize) {
102 $httpsrv->pre_daemonize;
103 Perlbal::daemonize();
104 } else {
105 print "Running.\n";
108 $httpsrv->post_daemonize;
110 # kill our children processes on exit:
111 my $parent_pid = $$;
113 $SIG{TERM} = $SIG{INT} = sub {
114 return unless $$ == $parent_pid; # don't let this be inherited
115 kill 'TERM', grep { $_ } keys %on_death;
116 POSIX::_exit(0);
119 setup_iostat_pipes();
120 start_disk_usage_process();
121 start_iostat_process() if $opt_iostat;
122 harvest_dead_children(); # every 2 seconds, it reschedules itself
123 setup_sidechannel_listener();
125 # now start the main loop
126 Perlbal::run();
128 ############################################################################
130 sub usage {
131 my $note = shift;
132 $note = $note ? "NOTE: $note\n\n" : "";
134 die "${note}Usage: mogstored [OPTS]
136 OPTS:
137 --daemonize -d Daemonize
138 --config=<file> Set config file (default is /etc/mogilefs/mogstored.conf)
139 --httplisten=<ip:port> IP/Port HTTP server listens on
140 --mgmtlisten=<ip:port> IP/Port management/sidechannel listens on
141 --docroot=<path> Docroot above device mount points. Defaults to /var/mogdata
142 --maxconns=<number> Number of simultaneous clients to serve. Default 10000
147 # accessor for SideChannelClient:
148 sub Mogstored::iostat_available {
149 return $iostat_available;
152 sub load_config_file {
153 my ($conffile, $opts) = @_;
155 # parse the mogstored config file, which is just lines of comments and
156 # "key = value" lines, where keys are just the same as command line
157 # options.
158 die "Config file $opt_config doesn't exist.\n" unless -e $conffile;
159 open my $fh, $conffile or die "Couldn't open config file for reading: $!";
160 while (<$fh>) {
161 s/\#.*//;
162 next unless /\S/;
163 if (/SERVER max_connect/i || /CREATE SERVICE/i) {
164 usage("Your $opt_config file is the old syntax. The new format is simply lines of <key> = <value> where keys are the same as mogstored's command line options.");
167 die "Unknown config syntax: $_\n" unless /^\s*(\w+)\s*=\s*(.+?)\s*$/;
168 my ($key, $val) = ($1, $2);
169 my $dest;
170 foreach my $ck (keys %$opts) {
171 next unless $ck =~ /^$key\b/;
172 $dest = $opts->{$ck};
174 die "Unknown config setting: $key\n" unless $dest;
175 $$dest = $val;
179 sub harvest_dead_children {
180 my $dead = waitpid(-1, WNOHANG);
181 if ($dead > 0) {
182 my $code = delete $on_death{$dead};
183 $code->() if $code;
185 Danga::Socket->AddTimer(2, \&harvest_dead_children);
188 sub Mogstored::on_pid_death {
189 my ($class, $pid, $code) = @_;
190 $on_death{$pid} = $code;
193 # returns $pid of child, if parent, else runs child.
194 sub start_disk_usage_process {
195 my $child = fork;
196 unless (defined $child) {
197 Perlbal::log('crit', "Fork error creating disk usage tracking process");
198 return undef;
201 # if we're the parent.
202 if ($child) {
203 $on_death{$child} = sub {
204 start_disk_usage_process(); # start a new one
206 return $child;
209 require Mogstored::ChildProcess::DiskUsage;
210 my $class = "Mogstored::ChildProcess::DiskUsage";
211 $class->pre_exec_init;
212 $class->exec;
215 sub Mogstored::iostat_subscribe {
216 my ($class, $sock) = @_;
217 $iostat_listeners{fileno($sock->sock)} = $sock;
220 sub Mogstored::iostat_unsubscribe {
221 my ($class, $sock) = @_;
222 my $fdno = fileno($sock->sock);
223 return unless defined $fdno;
224 delete $iostat_listeners{$fdno};
227 # to be honest, I have no clue why this exists. I just had to move it
228 # around for multi-server refactoring, and I felt better not
229 # understanding it but preserving than killing it. in particular, why
230 # is this "graceful"? (gets called from SideChannelClient's
231 # die_gracefully)
232 sub Mogstored::on_sidechannel_die_gracefully {
233 if ($$ == $parent_pid) {
234 kill 'TERM', grep { $_ } keys %on_death;
238 sub setup_sidechannel_listener {
239 Mogstored::SideChannelListener->new($mgmt_listen);
242 my $iostat_read_buf = "";
243 sub setup_iostat_pipes {
244 pipe ($iostat_pipe_r, $iostat_pipe_w);
245 IO::Handle::blocking($iostat_pipe_r, 0);
246 IO::Handle::blocking($iostat_pipe_w, 0);
248 Danga::Socket->AddOtherFds(fileno($iostat_pipe_r), sub {
249 read_from_iostat_child();
253 sub start_iostat_process {
254 my $pid = fork;
255 unless (defined $pid) {
256 warn "Fork for iostat failed: $!";
257 return;
260 if ($pid) {
261 # Parent
262 $on_death{$pid} = sub {
263 # Try a final read from data on the socket.
264 # Note that this doesn't internally loop... so it might miss data.
265 read_from_iostat_child();
266 # Kill any buffer so partial reads don't hurt us later.
267 drain_iostat_child_pipe();
268 start_iostat_process();
270 return;
273 require Mogstored::ChildProcess::IOStat;
274 my $class = "Mogstored::ChildProcess::IOStat";
275 $class->pre_exec_init;
276 $class->exec;
279 sub Mogstored::get_iostat_writer_pipe { $iostat_pipe_w }
281 sub drain_iostat_child_pipe {
282 my $data;
283 while (1) {
284 last unless sysread($iostat_pipe_r, $data, 10240) > 0;
286 $iostat_read_buf = '';
289 # (runs in parent event-loop process)
290 sub read_from_iostat_child {
291 my $data;
292 my $rv = sysread($iostat_pipe_r, $data, 10240);
293 return unless $rv && $rv > 0;
295 $iostat_read_buf .= $data;
297 # only write complete lines to sockets (in case for some reason we get
298 # a partial read and child process dies...)
299 while ($iostat_read_buf =~ s/(.+)\r?\n//) {
300 my $line = $1;
301 foreach my $out_sock (values %iostat_listeners) {
302 # where $line will be like "dev53\t53.23" or a "." to signal end of a group of devices.
303 # stop writing to the socket if the listener isn't picking it up.
304 next if $out_sock->{write_buf_size};
305 $out_sock->write("$line\n");
310 # Local Variables:
311 # mode: perl
312 # c-basic-indent: 4
313 # indent-tabs-mode: nil
314 # End:
316 __END__
318 =head1 NAME
320 mogstored -- MogileFS storage daemon
322 =head1 USAGE
324 This is the MogileFS storage daemon, which is just an HTTP server that
325 supports PUT, DELETE, etc. It's actually a wrapper around L<Perlbal>,
326 doing all the proper Perlbal config for you.
328 In addition, it monitors disk usage, I/O activity, etc, which are
329 checked from the L<MogileFS tracker|mogilefsd>.
331 =head1 AUTHORS
333 Brad Fitzpatrick E<lt>brad@danga.comE<gt>
335 Mark Smith E<lt>junior@danga.comE<gt>
337 Jonathan Steinert E<lt>jsteinert@sixapart.comE<gt>
339 =head1 ENVIRONMENT
341 =over 4
343 =item PERLBAL_XS_HEADERS
345 If defined and 0, Perlbal::XS::HTTPHeaders will not be used, if
346 present. Otherwise, it will be enabled by default, if installed and
347 loadable.
349 =back
351 =head1 COPYRIGHT
353 Copyright 2004, Danga Interactive
354 Copyright 2005-2006, Six Apart Ltd.
356 =head1 LICENSE
358 Same terms as Perl itself. Artistic/GPLv2, at your choosing.
360 =head1 SEE ALSO
362 L<MogileFS::Overview> -- high level overview of MogileFS
364 L<mogilefsd> -- MogileFS daemon
366 L<http://danga.com/mogilefs/>