root/lang/perl/Moxy/trunk/lib/Moxy/Cmd.pm @ 22762

Revision 22762, 1.8 kB (checked in by tokuhirom, 6 years ago)

better error handling

Line 
1package Moxy::Cmd;
2use strict;
3use warnings;
4require App::Cmd::Simple;
5use base qw/App::Cmd::Simple/;
6
7use File::Spec::Functions;
8use FindBin;
9use HTTP::Engine;
10use Moxy;
11use YAML;
12
13sub opt_spec {
14    return (
15        [ 'daemonize|d' => "daemonize" ],
16        [
17            'config|c=s' => "path to configuration file",
18            { default => catfile( $FindBin::Bin, 'config.yaml' ) }
19        ],
20        [ 'help|h' => "display manual" ]
21    );
22}
23
24sub validate_args {
25    my ($self, $opt, $args) = @_;
26    die $self->usage() if $opt->{help};
27}
28
29sub run {
30    my ($self, $opt, $args) = @_;
31
32    die "missing configuration file path" unless $opt->{config};
33    die "configuration file does not exists: $opt->{config}" unless -f $opt->{config};
34    print "open configuration file: $opt->{config}\n";
35    my $config = YAML::LoadFile( $opt->{config} );
36    $config->{global}->{log} ||= { level => 'debug' };
37
38    if ($opt->{daemonize}) {
39        if (my $pid = fork) {
40            exit 0;
41        } elsif (defined $pid) {
42            $self->_stdio_close();
43            $self->_start($config);
44        } else {
45            die "fork failed: $@";
46        }
47    } else {
48        $self->_start($config);
49    }
50}
51
52sub _start {
53    my ($self, $config) = @_;
54
55    my $moxy = Moxy->new($config);
56    HTTP::Engine->new(
57        interface => {
58            module => $config->{global}->{server}->{module},
59            args =>   $config->{global}->{server}->{args},
60            request_handler => sub {
61                my $req = shift;
62                $moxy->handle_request( $req );
63            },
64        }
65    )->run;
66}
67
68sub _stdio_close {
69    close(STDIN);
70    close(STDOUT);
71    close(STDERR);
72
73    open(STDIN,  "+>/dev/null"); ## no critic.
74    open(STDOUT, "+>&STDIN");    ## no critic.
75    open(STDERR, "+>&STDIN");    ## no critic.
76}
77
781;
Note: See TracBrowser for help on using the browser.