blib/lib/MYDan/Util/TcpServer.pm untested

filter: Statementstmt 0.0% 0 / 302 Branchbran 0.0% 0 / 126 Conditioncond 0.0% 0 / 97 MC/DCmcdc 0.0% 0 / 57 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 611 CC 64 SCAR 73.1
CC
64
Cov
0%
run
2550.0
new
42.0
dfok
20.0
CRAP 1488.3
1 package MYDan::Util::TcpServer;
2  
3 use warnings;
4 use strict;
5 use Carp;
6  
7 use Data::Dumper;
8  
9 use Tie::File;
10 use Fcntl 'O_RDONLY';
11 use POSIX ":sys_wait_h";
12 use Time::HiRes qw(time sleep );
13 use AnyEvent;
14 use AnyEvent::Impl::Perl;
15 use AnyEvent::Socket;
16 use AnyEvent::Handle;
17 use Fcntl qw(:flock SEEK_END);
18 use Filesys::Df;
19 use Digest::MD5;
20  
21 use MYDan;
22 use MYDan::Agent::FileCache;
23  
24 my %index;
25  
26 sub new
27 {
28 my ( $class, %this ) = @_;
29  
30 map{ die "$_ unkown" unless $this{$_} && $this{$_} =~ /^\d+$/ }
31 qw( port max ReservedSpaceCount ReservedSpaceSize );
32  
33 $0 = 'mydan.tcpserver.'.$this{port};
34  
35 die "no file:$this{'exec'}\n" unless $this{'exec'} && -e $this{'exec'};
36  
37 map{
38 $this{$_} ||= "$MYDan::PATH/var/run/tcpserver.$this{port}/$_";
39 system( "mkdir -p '$this{$_}'" ) unless -d $this{$_};
40 map{ unlink $_ if $_ =~ /\/\d+$/ || $_ =~ /\/\d+\.out$/ || $_ =~ /\/\d+\.ext$/ }glob "$this{$_}/*";
41 }qw( tmp ReservedSpace );
42  
43  
44 my ( $c, $s, $r ) = map{ $this{$_} }qw( ReservedSpaceCount ReservedSpaceSize ReservedSpace );
45 $c = $this{max} if $c > $this{max};
46  
47 open my $H, '>', "$r/tmp" or die "Can't open '$r/tmp': $!";
48 map{ syswrite( $H, "\0" x 1024 ); } 1 .. $s;
49 close $H;
50  
51 for my $i ( 1 .. $c )
52 {
53 map{ system "cp '$r/tmp' '$r/$i$_'"; }('', '.out');
54 }
55  
56 map{ $this{$_} ||= $this{buf} }qw( rbuf wbuf );
57  
58 $this{limit} ||= 104857600; #100m
59 map{ $this{$_} ||= $this{limit}; $this{$_} /= 10; }qw( rlimit wlimit );
60 map{ $this{"${_}ctrl"}{itime} = 0; }qw( r w );
61  
62 bless \%this, ref $class || $class;
63 }
64  
65 sub run
66 {
67 my $this = shift;
68 my ( $port, $max, $exec, $tmp, $rbuf, $wbuf ) = @$this{qw( port max exec tmp rbuf wbuf )};
69  
70 my $filecache = MYDan::Agent::FileCache->new();
71 my $version = $MYDan::VERSION; $version =~ s/\./0/g;
72  
73 my $excb = sub{
74 map{ kill 'TERM', $_->{pid} if $_->{pid}; }values %index;
75 die "kill.\n";
76 };
77  
78 my $term = AnyEvent->signal (signal => "TERM", cb => $excb );
79 my $ints = AnyEvent->signal (signal => "INT", cb => $excb );
80 my $usr1 = AnyEvent->signal (signal => "USR1", cb => sub{ print Dumper \%index; } );
81  
82 my %savecb;
83 my $childcb = sub
84 {
85 my ( $pid, $code ) = @_;
86 print "chld: $pid exit $code.\n";
87  
88 my ( $index ) = grep{ $index{$_}{pid} && $index{$_}{pid} eq $pid }keys %index;
89 return unless my $data = delete $index{$index};
90  
91 kill( 15, $data->{savecbpid} ) if $data->{savecbpid} && $savecb{$data->{savecbpid}};
92  
93 if( $data->{handle}->fh )
94 {
95 $data->{handle}->push_write( "*#*MYDan_$version*#" );
96  
97 my $size = ( stat "$tmp/$index.out" )[7];
98  
99 if ( ( ! $wbuf || ( $wbuf && $size <= $wbuf ) ) && open my $tmp_handle, '<', "$tmp/$index.out" )
100 {
101 my $finish;
102 $data->{fh} = $tmp_handle;
103 $data->{handle}->on_drain(
104 sub{
105 if( $finish )
106 {
107 $data->{handle}->on_drain(undef);
108 $data->{handle}->push_shutdown;
109 $data->{handle}->destroy() unless $data->{handle}->destroyed();
110 return;
111 }
112 my ( $n, $buf );
113 if( $n = sysread( $data->{fh}, $buf, 102400 ) )
114 {
115 if( ! $data->{body} && $buf =~ s/MYDanExtractFile_::(.+)::_MYDanExtractFile// )
116 {
117 $data->{file} = $1;
118 }
119 $data->{body} = 1;
120  
121 $this->rwlimit( w => length $buf );
122 $data->{handle}->push_write($buf);
123 }
124 else
125 {
126 close $data->{fh};
127  
128 if( my $f = delete $data->{file} )
129 {
130 if( open my $tmp_handle, '<', $f )
131 {
132 $data->{fh} = $tmp_handle;
133 if( $n = sysread( $data->{fh}, $buf, 102400 ) )
134 {
135 $this->rwlimit( w => length $buf );
136 $data->{handle}->push_write($buf);
137 return;
138 }
139  
140 }
141 else
142 {
143 $code ||= 110;
144 warn "open MYDanExtractFile fail: $!";
145 }
146 }
147  
148 $data->{handle}->push_write("--- $code\n");
149 $finish = 1;
150 }
151 }
152 );
153 }
154 else
155 {
156 $data->{handle}->push_shutdown;
157 $data->{handle}->destroy() unless $data->{handle}->destroyed();
158 }
159 }
160  
161 map{ unlink "$tmp/$_" if -e "$tmp/$_" }( $index, "$index.out", "$index.ext" );
162 };
163  
164 my ( $i, $cv ) = ( 0, AnyEvent->condvar );
165  
166 my $whitelist;
167
168 tcp_server undef, $port, sub {
169 my ( $fh, $tip, $tport ) = @_ or die "tcp_server: $!";
170  
171 printf "index: %s\n", ++ $i;
172 my $index = $i;
173  
174 my $len = keys %index;
175 printf "tcpserver: status: $len/$max\n";
176  
177 if( $this->{whitelist} && ! $whitelist->{$tip} )
178 {
179 printf "connection not allow, from %s:%s\n", $tip, $tport;
180 close $fh;
181 return;
182 }
183  
184  
185 if( $len >= $max )
186 {
187 printf "connection limit reached, from %s:%s\n", $tip, $tport;
188 close $fh;
189 return;
190 }
191  
192 my $tmp_handle;
193  
194 if( $this->dfok() )
195 {
196 unless( open $tmp_handle, '>', "$tmp/$index" )
197 {
198 print "open '$tmp/$index' fail:$!\n";
199 close $fh;
200 return;
201 }
202 }
203 else
204 {
205 my $rs = $this->space();
206 unless( $rs ) { close $fh; return; }
207  
208 map{ system "ln '$this->{ReservedSpace}/$rs$_' '$tmp/$index$_'" }( '', '.out' );
209 unless( open $tmp_handle, '+<', "$tmp/$index" )
210 {
211 print "open '$tmp/$index' fail:$!\n";
212 map{ unlink "$tmp/$rs$_" if -e "$tmp/$rs$_" }( '', '.out' );
213 close $fh;
214 return;
215 }
216 }
217  
218 my $EF;
219 my $handle; $handle = new AnyEvent::Handle(
220 fh => $fh,
221 keepalive => 1,
222 rbuf_max => 1024000,
223 wbuf_max => 1024000,
224 autocork => 1,
225 on_eof => sub{
226 close $tmp_handle;
227  
228 if ( my $pid = fork() )
229 {
230 $index{$index}{pid} = $pid;
231 $index{$index}{child} = AnyEvent->child ( pid => $pid, cb => $childcb );
232 }
233 else
234 {
235 $tip = '0.0.0.0' unless $tip && $tip =~ /^\d+\.\d+\.\d+\.\d+$/;
236 $tport = '0' unless $tport && $tport =~ /^\d+$/;
237  
238 $ENV{TCPREMOTEIP} = $tip;
239 $ENV{TCPREMOTEPORT} = $tport;
240 $ENV{TCPSERVERINDEX} = $index;
241 $ENV{TCPSERVERPORT} = $port;
242 if( defined $index{$index}{extfile} )
243 {
244 $ENV{MYDanExtractFile} = $index{$index}{extfile};
245 $ENV{MYDanExtractFileAim} = $index{$index}{aim};
246 }
247
248 open STDIN, '<', "$tmp/$index" or die "Can't open '$tmp/$index': $!";
249 my $m = -f "$tmp/$index.out" ? '+<' : '>';
250 open STDOUT, $m, "$tmp/$index.out" or die "Can't open '$tmp/$index.out': $!";
251 $ENV{UseReservedSpace} = 1 if $m eq '+<';
252 exec $exec;
253 }
254 },
255 on_read => sub {
256 my $self = shift;
257  
258 if( ! $index{$index}{rbuf} && $self->{rbuf} =~ s/^MYDanExtractFile_::(\d+):(\d+):([a-zA-Z0-9]{32}):([a-zA-Z0-9\/\._\-]+)::_MYDanExtractFile// )
259 {
260 my ( $qsize, $esize, $md5, $aim ) = ( $1, $2, $3, $4 );
261 $index{$index}{querysize} = $qsize;
262 $index{$index}{aim} = $aim;
263  
264 my $cb = sub{
265 return unless $index{$index};
266 if( $index{$index}{extfile} = $filecache->check( $md5 ) )
267 {
268 $handle->push_write("MH_:0:_MH") if $handle->fh;
269 }
270 else
271 {
272 $handle->push_write("MH_:1:_MH") if $handle->fh;
273 $index{$index}{extfile} = "$tmp/$index.ext";
274 open $EF, ">$tmp/$index.ext" or die "Can't open $tmp/$index.ext";
275 }
276 };
277
278 if( $filecache->usable() && ! $filecache->check( $md5 ) && -f $aim )
279 {
280 my $size = ( stat $aim )[7];
281 if( $size eq $esize )
282 {
283 if ( my $pid = fork() )
284 {
285 $index{$index}{savecbpid} = $pid;
286 $savecb{$pid} = AnyEvent->child (pid => $pid, cb => sub
287 {
288 delete $savecb{$pid};
289 &$cb();
290 }
291 );
292 }
293 else
294 {
295 $0 = "mydan.filecache $aim";
296 die "save aim $aim fail\n" unless $filecache->save( $aim );
297 exit 0;
298 }
299 }
300 else { &$cb(); }
301 }
302 else { &$cb(); }
303  
304 $index{$index}{rbuf} = 1;
305 }
306  
307 my $len = length $self->{rbuf};
308  
309 $index{$index}{querysize} = $rbuf unless defined $index{$index}{querysize};
310 if( $index{$index}{querysize} )
311 {
312 if( $len < $index{$index}{querysize} )
313 {
314 $index{$index}{rbuf} += $len;
315 $this->rwlimit( r => $len );
316 $self->push_read (
317 chunk => $len,
318 sub { syswrite( $tmp_handle, $_[1] ) }
319 );
320 $index{$index}{querysize} -= $len;
321 $len = 0;
322 }
323 else
324 {
325 $index{$index}{rbuf} += $index{$index}{querysize};
326 $this->rwlimit( r => $index{$index}{querysize} );
327 $self->push_read(
328 chunk => $index{$index}{querysize},
329 sub { syswrite( $tmp_handle, $_[1] ) }
330 );
331 $len -= $index{$index}{querysize};
332 $index{$index}{querysize} = 0;
333 }
334 }
335  
336 return unless $len;
337
338 $this->rwlimit( r => $len );
339 $self->push_read (
340 chunk => $len,
341 sub {
342 if( $EF )
343 {
344 syswrite( $EF, $_[1] );
345 }
346 else
347 {
348 $handle->push_shutdown;
349 }
350 }
351 );
352 },
353 on_error => sub {
354 close $tmp_handle;
355  
356 close $fh;
357 delete $handle->{fh};
358  
359 $handle->destroy();
360  
361 my $pid = $index{$index}{pid} if $index{$index};
362 if( $pid ) { kill 15, $pid; }
363 else
364 {
365 delete $index{$index};
366 map{ unlink "$tmp/$_" if -e "$tmp/$_" }( $index, "$index.out", "$index.ext" );
367 }
368 },
369 );
370 $index{$index}{handle} = $handle;
371
372 };
373  
374 my $t = AnyEvent->timer(
375 after => 1,
376 interval => 1,
377 cb => sub {
378 map{
379 $_->{handle}->push_write('*') if $_->{handle} && $_->{handle}->fh;
380 }values %index;
381 }
382 );
383  
384 my $mtime = 0;
385 my $wl = AnyEvent->timer(
386 after => 1,
387 interval => 30,
388 cb => sub {
389 if( -f $this->{whitelist} )
390 {
391 my ( $mt, @ip ) = ( stat $this->{whitelist} )[9];
392 return if $mtime == $mt;
393 unless( tie @ip, 'Tie::File', $this->{whitelist}, mode => O_RDONLY )
394 {
395 print "tie fail: $!\n";
396 return;
397 }
398 $whitelist = +{ map{ $_ => 1 }@ip };
399 $mtime = $mt;
400 }
401  
402 }
403 ) if $this->{whitelist};
404
405 $cv->recv;
406 }
407  
408 sub space
409 {
410 my $path = shift->{ReservedSpace};
411  
412 for ( glob "$path/*" )
413 {
414 next unless $_ =~ /\/(\d+)$/;
415 my $id = $1;
416  
417 next unless rsok( $_ ) && rsok( "$_.out" );
418 map{ system "cp '$path/tmp' '$path/$id$_'" }( '', '.out' );
419 return $id;
420 }
421 return undef;
422 }
423  
424 sub rsok
425 {
426 my $file = shift;
427 return ( $file && -f $file && ( stat $file )[3] == 1 ) ? 1 : 0;
428 }
429  
430 sub dfok
431 {
432 my $F;
433 unless ( open( $F, shift->{tmp} ) )
434 {
435 print "df open tmp fail\n";
436 return undef;
437 }
438  
439 my $df = df($F);
440 close $F;
441  
442 return undef unless $df && ref $df eq 'HASH' && defined $df->{bfree} && defined $df->{ffree};
443 return ( $df->{bfree} > 102400 && $df->{ffree} > 4000 ) ? 1 : 0;
444 }
445  
446 sub rwlimit
447 {
448 my ( $this, $type, $len ) = @_;
449 my $limit = $this->{"${type}limit"};
450  
451 my $time = time * 10;
452 my $itime = int $time;
453  
454 if( $this->{"${type}ctrl"}{itime} eq $itime )
455 {
456 $this->{"${type}ctrl"}{time} = $time;
457 $this->{"${type}ctrl"}{len} += $len;
458  
459 if( $this->{"${type}ctrl"}{len} > $limit )
460 {
461 my $x = ( $itime + 1 - $time ) / 10;
462 sleep $x if $x > 0;
463 }
464 }
465 else
466 {
467 $this->{"${type}ctrl"} = +{ itime => $itime, time => $time, len => $len };
468 }
469  
470 }
471  
472  
473 1;