1 | #!/usr/bin/perl -w |
---|
2 | use strict; |
---|
3 | |
---|
4 | use FindBin; |
---|
5 | use lib "$FindBin::RealBin/../lib"; |
---|
6 | |
---|
7 | use Getopt::Long; |
---|
8 | use YAML; |
---|
9 | use Plack::Runner; |
---|
10 | use File::Pid; |
---|
11 | use File::Spec::Functions qw{catfile}; |
---|
12 | |
---|
13 | GetOptions( |
---|
14 | 'file=s' => \my $CONFIG_FILE, |
---|
15 | ); |
---|
16 | |
---|
17 | $CONFIG_FILE ||= 'server.yml'; |
---|
18 | -e $CONFIG_FILE or die "Config file $CONFIG_FILE not found\n"; |
---|
19 | my $config = YAML::LoadFile($CONFIG_FILE); |
---|
20 | my $command = shift or die "Usage: $0 <start|stop>\n"; |
---|
21 | |
---|
22 | my %run = ( |
---|
23 | start => \&_start_server, |
---|
24 | stop => \&_stop_server, |
---|
25 | restart => sub { |
---|
26 | my $config = shift; |
---|
27 | _stop_server($config); |
---|
28 | _start_server($config); |
---|
29 | }, |
---|
30 | ); |
---|
31 | |
---|
32 | exists $run{$command} or die "Unrecognized command $command\n"; |
---|
33 | $run{$command}->($config); |
---|
34 | |
---|
35 | sub _start_server { |
---|
36 | my $config = shift; |
---|
37 | require BookmarksApp; |
---|
38 | my $app = BookmarksApp->new({ config => $config })->to_app; |
---|
39 | |
---|
40 | my $server_root = $config->{server_root} || '.'; |
---|
41 | my $listen = ':' . ($config->{port} || 5000); |
---|
42 | my $access_log = catfile($server_root, 'access'); |
---|
43 | my $error_log = catfile($server_root, 'errors'); |
---|
44 | my $pid_file = catfile($server_root, 'pid'); |
---|
45 | |
---|
46 | my $runner = Plack::Runner->new(server => 'Starman'); |
---|
47 | $runner->parse_options( |
---|
48 | '--daemonize', |
---|
49 | '--listen', $listen, |
---|
50 | '--pid', $pid_file, |
---|
51 | '--error-log', $error_log, |
---|
52 | '--access-log', $access_log, |
---|
53 | ); |
---|
54 | $runner->run($app); |
---|
55 | } |
---|
56 | |
---|
57 | sub _stop_server { |
---|
58 | my $config = shift; |
---|
59 | my $server_root = $config->{server_root} || '.'; |
---|
60 | |
---|
61 | my $pid_path = catfile($server_root, 'pid'); |
---|
62 | unless (-e $pid_path) { |
---|
63 | warn "$pid_path does not exist\n"; |
---|
64 | return; |
---|
65 | } |
---|
66 | |
---|
67 | my $pid_file = File::Pid->new({ |
---|
68 | file => $pid_path, |
---|
69 | }); |
---|
70 | |
---|
71 | if (my $pid = $pid_file->running) { |
---|
72 | kill 'TERM', $pid; |
---|
73 | } |
---|
74 | } |
---|