1#!/usr/bin/perl -w
2
3# start-memcached
4# 2003/2004 - Jay Bonci <[email protected]>
5# This script handles the parsing of the /etc/memcached.conf file
6# and was originally created for the Debian distribution.
7# Anyone may use this little script under the same terms as
8# memcached itself.
9
10use strict;
11
12if($> != 0 and $< != 0)
13{
14    print STDERR "Only root wants to run start-memcached.\n";
15    exit;
16}
17
18my $params; my $etchandle; my $etcfile = "/etc/memcached.conf";
19
20# This script assumes that memcached is located at /usr/bin/memcached, and
21# that the pidfile is writable at /var/run/memcached.pid
22
23my $memcached = "/usr/bin/memcached";
24my $pidfile = "/var/run/memcached.pid";
25
26# If we don't get a valid logfile parameter in the /etc/memcached.conf file,
27# we'll just throw away all of our in-daemon output. We need to re-tie it so
28# that non-bash shells will not hang on logout. Thanks to Michael Renner for
29# the tip
30my $fd_reopened = "/dev/null";
31
32sub handle_logfile
33{
34    my ($logfile) = @_;
35    $fd_reopened = $logfile;
36}
37
38sub reopen_logfile
39{
40    my ($logfile) = @_;
41
42    open *STDERR, ">>$logfile";
43    open *STDOUT, ">>$logfile";
44    open *STDIN, ">>/dev/null";
45    $fd_reopened = $logfile;
46}
47
48# This is set up in place here to support other non -[a-z] directives
49
50my $conf_directives = {
51    "logfile" => \&handle_logfile,
52};
53
54if(open $etchandle, $etcfile)
55{
56    foreach my $line (<$etchandle>)
57    {
58        $line ||= "";
59        $line =~ s/\#.*//g;
60        $line =~ s/\s+$//g;
61        $line =~ s/^\s+//g;
62        next unless $line;
63        next if $line =~ /^\-[dh]/;
64
65        if($line =~ /^[^\-]/)
66        {
67            my ($directive, $arg) = $line =~ /^(.*?)\s+(.*)/;
68            $conf_directives->{$directive}->($arg);
69            next;
70        }
71
72        push @$params, $line;
73    }
74
75}else{
76    $params = [];
77}
78
79push @$params, "-u root" unless(grep "-u", @$params);
80$params = join " ", @$params;
81
82if(-e $pidfile)
83{
84    open PIDHANDLE, "$pidfile";
85    my $localpid = <PIDHANDLE>;
86    close PIDHANDLE;
87
88    chomp $localpid;
89    if(-d "/proc/$localpid")
90    {
91        print STDERR "memcached is already running.\n";
92        exit;
93    }else{
94        `rm -f $localpid`;
95    }
96
97}
98
99my $pid = fork();
100
101if($pid == 0)
102{
103    reopen_logfile($fd_reopened);
104    exec "$memcached $params";
105    exit(0);
106
107}else{
108    if(open PIDHANDLE,">$pidfile")
109    {
110        print PIDHANDLE $pid;
111        close PIDHANDLE;
112    }else{
113
114        print STDERR "Can't write pidfile to $pidfile.\n";
115    }
116}
117
118