blib/lib/MYDan/Collector/Sock.pm untested

filter: Statementstmt 0.0% 0 / 80 Branchbran 0.0% 0 / 20 Conditioncond 0.0% 0 / 3 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 117 CC 11 SCAR 32.4
CC
11
Cov
0%
new
56.0
run
30.0
BEGIN
2.0
CRAP 25.5
1 package MYDan::Collector::Sock;
2  
3 use warnings;
4 use strict;
5 use Carp;
6  
7 use threads;
8 use Thread::Queue;
9 use Socket;
10 use IO::Select;
11  
12 use MYDan::Util::Sysrw;
13 use YAML::XS;
14 use File::Basename;
15  
16 our %MAX = ( thread => 5, maxconn => 5 );
17  
18 sub new
19 {
20 my ( $class, %this ) = @_;
21  
22 die "sock path undef" unless my $path = $this{path};
23 unlink $path if -r $path;
24 my $addr = sockaddr_un( $path );
25  
26 die "socket: $!" unless socket my $socket, PF_UNIX, SOCK_STREAM, 0;
27 die "setsockopt: $!" unless setsockopt $socket, SOL_SOCKET, SO_REUSEADDR, 1;
28 die "bind (path $path): $!\n" unless bind $socket, $addr;
29 die "listen: $!\n" unless listen $socket, SOMAXCONN;
30  
31 $this{name} = File::Basename::basename $path;
32 $this{sock} = $socket;
33  
34 bless \%this, ref $class || $class;
35 }
36  
37 sub run
38 {
39 my $this = shift;
40  
41 my $select = new IO::Select( $this->{sock} );
42 my @conn = map { Thread::Queue->new } 0 .. 1;
43 my $status = "$this->{name}: status: \%s/$MAX{thread}\n";
44 printf $status, 0;
45  
46 map
47 {
48 threads::async
49 {
50 while ( my $fileno = $conn[0]->dequeue() )
51 {
52 if( open my $client, '+<&=', $fileno )
53 {
54 eval{
55 alarm 5;
56 $this->_server( $client );
57 alarm 0;
58 };
59 alarm 0;
60 warn "_server timeout:$@\n" if $@;
61  
62 close $client;
63 }
64  
65 $conn[1]->enqueue( $fileno );
66 }
67 }->detach()
68 } 1 .. $MAX{thread};
69  
70 my %conn;
71 threads::async
72 {
73 while ( 1 )
74 {
75 while ( my $count = $conn[1]->pending )
76 {
77 map { delete $conn{$_} } $conn[1]->dequeue( $count );
78 printf $status, scalar keys %conn;
79 }
80
81 if ( my ( $server, $client ) = $select->can_read( 0.5 ) )
82 {
83 accept $client, $server;
84
85 if ( $conn[0]->pending > $MAX{maxconn} )
86 {
87 close $client;
88 warn "connection limit reached\n";
89 next;
90 }
91  
92 my $cfileno = fileno $client;
93
94 $conn{$cfileno} = $client;
95 printf $status, scalar keys %conn;
96 $conn[0]->enqueue( $cfileno );
97 }
98 }
99 }->detach();
100 }
101  
102 1;