Debian Codegraph @

bin/circle-be

raw
1 #!/usr/bin/perl
2
3 # You may distribute under the terms of the GNU General Public License
4 #
5 # (C) Paul Evans, 2008-2010 -- [email protected]
6
7 use strict;
8 use warnings;
9
10 use Circle;
11 use IO::Async::Loop 0.37;
12 use IO::Async::Stream;
13
14 use Errno qw( ECONNREFUSED );
15 use Getopt::Long;
16
17 # Optional but handy
18 eval { require Devel::Confess } and Devel::Confess->import;
19
20 GetOptions(
21 'p|port=i' => \my $PORT,
22 's|socket=s' => \my $SOCKPATH,
23 'stdio' => \my $STDIO,
24 'C|config=s' => \my $CONFIG,
25 'help' => sub { usage(0) },
26 ) or usage(1);
27
28 sub usage
29 {
30 my ( $exitcode ) = @_;
31
32 print { $exitcode ? \*STDERR : \*STDOUT } <<'EOF';
33 circle-be [options...]
34
35 Options:
36
37 --port, -p PORT Listen on given TCP port
38
39 --socket, -s SOCKET Listen on given UNIX socket path
40
41 --stdio Listen on STDIN/STDOUT
42
43 --config, -C FILE Override path to config file
44
45 EOF
46
47 exit $exitcode;
48 }
49
50 defined($PORT) + defined($SOCKPATH) + defined($STDIO) > 1 and
51 die "Cannot specify more than one of --port, --socket and --stdio\n";
52
53 defined($PORT) or defined($SOCKPATH) or defined($STDIO) or
54 usage(1);
55
56 my $loop = IO::Async::Loop->new();
57
58 my $circle = Circle->new(
59 loop => $loop,
60 config => $CONFIG,
61 );
62
63 if( defined $PORT ) {
64 $circle->listen(
65 addr => {
66 family => 'inet',
67 socktype => 'stream',
68 port => $PORT,
69 ip => '0.0.0.0', # fscking....
70 },
71 on_fail => sub { print STDERR "Cannot $_[0] - $_[-1]\n"; },
72 on_listen_error => sub { print STDERR "Cannot listen\n"; },
73 );
74 }
75 elsif( defined $SOCKPATH ) {
76 if( -e $SOCKPATH ) {
77 if( IO::Socket::UNIX->new( Peer => $SOCKPATH ) ) {
78 # success - existing server running
79 die "Unable to listen on $SOCKPATH - an existing server is running\n";
80 }
81 elsif( $! == ECONNREFUSED ) {
82 # OK - no server listening
83 unlink $SOCKPATH or die "Cannot unlink $SOCKPATH - $!\n";
84 }
85 else {
86 die "Unable to probe if $SOCKPATH is in use - $!\n";
87 }
88 }
89 $circle->listen(
90 addr => {
91 family => 'unix',
92 socktype => 'stream',
93 path => $SOCKPATH,
94 },
95 on_fail => sub { print STDERR "Cannot $_[0] - $_[-1]\n"; },
96 on_listen_error => sub { print STDERR "Cannot listen\n"; },
97 );
98 }
99 elsif( $STDIO ) {
100 $circle->on_stream( IO::Async::Stream->new_for_stdio );
101 }
102
103 $SIG{__WARN__} = sub {
104 local $SIG{__WARN__}; # disable during itself to avoid looping
105 $circle->warn( @_ );
106 };
107
108 $SIG{PIPE} = "IGNORE";
109
110 $loop->run;