| [93] | 1 | #!/usr/bin/perl -w |
|---|
| 2 | use strict; |
|---|
| [54] | 3 | |
|---|
| [93] | 4 | use FindBin; |
|---|
| [103] | 5 | use lib "$FindBin::RealBin/../lib"; |
|---|
| [65] | 6 | |
|---|
| [94] | 7 | use Getopt::Long; |
|---|
| 8 | use YAML; |
|---|
| [93] | 9 | use Plack::Runner; |
|---|
| [103] | 10 | use File::Pid; |
|---|
| [102] | 11 | use File::Spec::Functions qw{catfile}; |
|---|
| [93] | 12 | |
|---|
| [94] | 13 | GetOptions( |
|---|
| 14 | 'file=s' => \my $CONFIG_FILE, |
|---|
| 15 | ); |
|---|
| [93] | 16 | |
|---|
| [96] | 17 | $CONFIG_FILE ||= 'server.yml'; |
|---|
| [94] | 18 | -e $CONFIG_FILE or die "Config file $CONFIG_FILE not found\n"; |
|---|
| 19 | my $config = YAML::LoadFile($CONFIG_FILE); |
|---|
| [103] | 20 | my $command = shift or die "Usage: $0 <start|stop>\n"; |
|---|
| [94] | 21 | |
|---|
| [103] | 22 | my %run = ( |
|---|
| [104] | 23 | start => \&_start_server, |
|---|
| 24 | stop => \&_stop_server, |
|---|
| 25 | restart => sub { |
|---|
| [103] | 26 | my $config = shift; |
|---|
| [104] | 27 | _stop_server($config); |
|---|
| 28 | _start_server($config); |
|---|
| 29 | }, |
|---|
| 30 | ); |
|---|
| [94] | 31 | |
|---|
| [104] | 32 | exists $run{$command} or die "Unrecognized command $command\n"; |
|---|
| 33 | $run{$command}->($config); |
|---|
| [103] | 34 | |
|---|
| [104] | 35 | sub _start_server { |
|---|
| 36 | my $config = shift; |
|---|
| 37 | require BookmarksApp; |
|---|
| 38 | my $app = BookmarksApp->new({ config => $config })->to_app; |
|---|
| [103] | 39 | |
|---|
| [104] | 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'); |
|---|
| [103] | 45 | |
|---|
| [104] | 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 | } |
|---|
| [103] | 56 | |
|---|
| [104] | 57 | sub _stop_server { |
|---|
| 58 | my $config = shift; |
|---|
| 59 | my $server_root = $config->{server_root} || '.'; |
|---|
| [103] | 60 | |
|---|
| [104] | 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 | } |
|---|