Docker/RequestRawStream.pm untested

filter: Statementstmt 0.0% 0 / 197 Branchbran 0.0% 0 / 56 Conditioncond 0.0% 0 / 20 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 323 CC 29 SCAR 32.2
CC
29
Cov
0%
wait_for_job
56.0
block
56.0
process_socket_stream
42.0
CRAP 25.0
1 package Eixo::Docker::RequestRawStream;
2  
3 use strict;
4 use warnings;
5  
6 use Eixo::Base::Clase;
7  
8 use Net::HTTP;
9 use Data::Dumper;
10  
11 use POSIX qw(:errno_h);
12 use Fcntl;
13 use IO::Select;
14  
15 use threads;
16 use Thread::Queue;
17 use Eixo::Docker::Job;
18 use Eixo::Docker;
19  
20 use Carp;
21  
22 my $JOB_ID = 0;
23  
24 has(
25  
26 entity=>undef,
27  
28 id=>undef,
29  
30 action=>undef,
31  
32 host=>undef,
33  
34 method=>undef,
35  
36 url_args=>[],
37  
38 query_args=>[],
39  
40 args=>{},
41  
42 f_process=>$Eixo::Docker::IDENTITY_FUNC,
43  
44 f_line=> $Eixo::Docker::IDENTITY_FUNC,
45  
46 f_stdin=>undef,
47  
48 f_stdout=>undef,
49  
50 f_stderr=>undef,
51  
52 f_end=>undef,
53  
54 queue_in=>undef,
55  
56 queue_out=>undef,
57  
58 jobs => [],
59  
60 line_termination => "\n",
61  
62 timeout => 60,
63  
64 tty_mode => undef,
65 );
66  
67  
68 sub process{
69 my ($self,$multiplexed) = @_;
70  
71 #
72 # We create a queue to handle communication
73 #
74 $self->queue_in(Thread::Queue->new);
75 $self->queue_out(Thread::Queue->new);
76  
77 threads->new(sub {
78 my ($self, $multiplexed) = @_;
79  
80 $self->_process($multiplexed);
81  
82 }, $self,$multiplexed)->detach;
83  
84 #
85 # We encapsulate a callback to send commands
86 #
87 if($self->args->{stdin}){
88
89 # return 2 callbacks,
90 # 1 to send messages to docker ,
91 # 2 to receive response|ack
92 (
93 sub {
94  
95 $self->queue_in->enqueue([++$JOB_ID, $_[0]]);
96  
97 push @{$self->jobs}, Eixo::Docker::Job->new(
98
99 id => $JOB_ID,
100 params => $_[0],
101 status => 'SEND',
102 wait_for_results => ($self->args->{stdout} || $self->args->{stderr})
103 );
104  
105 $JOB_ID;
106 },
107  
108 sub {
109 $self->wait_for_job($_[0])
110 }
111 )
112 }
113 else{
114
115 # callback to take messages from container
116 sub {
117 my $return = undef;
118  
119 while(defined(my $res = $self->queue_out->dequeue())){
120 # print "resposta".Dumper($res);use Data::Dumper;
121 # in perl 5.18 there is a q->end
122 last if($res eq "END");
123  
124 # call f_process callback (for stream mode)
125 $self->f_process->($res->[1]);
126 $return = $res->[1];
127 }
128  
129 $return;
130 }
131 }
132 }
133  
134  
135 sub wait_for_job{
136 my ($self, $job_id) = @_;
137  
138 # if no job_id was passed, wait for all
139 $job_id = '' unless(defined($job_id));
140  
141 # job could be finished before wait
142 if(my ($job) = grep {$_->finished && $_->id eq $job_id} @{$self->jobs}){
143  
144 return $job->results;
145 }
146  
147  
148 # wait to finish the job
149 while(grep { !$_->finished } @{$self->jobs}){
150  
151 #if(defined(my $res = $self->queue_out->dequeue_nb)){
152 if(defined(my $res = $self->queue_out->dequeue)){
153  
154 #print "Recibimos:".Dumper($res);use Data::Dumper;
155  
156 my ($id, $result) = @$res;
157  
158 my $j = $self->getJob($id);
159  
160 croak("Job not found : $id") unless($j);
161
162 $j->process($result);
163  
164 # if we found the job searched return with results
165 return $j->results if($j->id eq $job_id && $j->finished);
166 }
167  
168 # print "En wait_for_job\n";
169 # print Dumper($self->jobs)."\n";
170  
171 select(undef,undef,undef,0.25);
172 }
173  
174 # if no job_id was passed returns all results
175 if($job_id eq ''){
176
177 return map {$_->results} @{$self->jobs};
178 # return map {$_->id => $_->results} @{$self->jobs};
179 }
180 else{
181 die("task not found in job list ($job_id)");
182 }
183 }
184  
185  
186 sub getJob {
187 my ($self, $job_id) = @_;
188  
189 (grep {$_->id eq $job_id} @{$self->jobs})[0];
190  
191 }
192  
193  
194 sub _process{
195 my ($self,$multiplexed) = @_;
196  
197 my ($host) = $self->host =~ /http\:\/\/(.+)$/;
198  
199 my $uri = $self->__buildUri();
200  
201 my $socket = Net::HTTP->new(
202  
203 Host=>$host,
204 Timeout => $self->timeout,
205  
206 ) || die( ref($self) . '::process: error ' . $!);
207  
208 $socket->write_request($self->method => $uri);
209  
210 my($code, $mess, %h) = $socket->read_response_headers;
211  
212 # check response headers
213 confess("Error in http request: $mess (code = $code)") unless($code == 200);
214  
215 if($self->args->{stream}){
216
217 $self->block($socket);
218  
219 }
220 else{
221  
222 $self->process_request_body($socket);
223 }
224  
225 threads->exit();
226 }
227  
228  
229 sub block{
230 my ($self, $socket) = @_;
231  
232 my $job_id = 0;
233  
234 my $select = IO::Select->new($socket);
235
236 while(1){
237  
238 # send message for stdin
239 if($self->args->{stdin}){
240
241 # block till receive message from q_in
242 my $msg = $self->queue_in->dequeue;
243
244 $job_id = $msg->[0];
245  
246 #
247 # job_id = -1 indicates detach
248 #
249 last if($job_id == -1);
250
251 my $send_status = $self->__sendCmd($msg->[1], $socket);
252  
253 # enqueue ACK
254 $self->queue_out->enqueue([$job_id, $send_status]);
255 }
256  
257 # get response from stdout|stderrr
258 if($self->args->{stdout} || $self->args->{stderr}){
259
260 # set a timeout to read
261 my @ready = $select->can_read($self->timeout);
262  
263 # if no response from socket in time, enqueue a empty string response
264 # and jump to next job
265 unless(@ready){
266  
267 # close thread if not using stdin
268 unless($self->args->{stdin}){
269 # print "Timeout superado, encolando END\n";
270 $self->queue_out->enqueue("END");
271 last;
272 }
273 else{
274 # print "Timeout superado, encolando ''\n";
275 $self->queue_out->enqueue([$job_id,""]);
276 next;
277 }
278 }
279  
280  
281 my $data = $self->process_socket_stream($select);
282  
283 # if read socket return undef, and no stdin stream connected, close thread
284 if(!defined($data) && !$self->args->{stdin}){
285
286 $self->queue_out->enqueue("END");
287 last;
288 }
289
290  
291 $self->queue_out->enqueue([$job_id,$data]);
292  
293 }
294  
295 }
296  
297 }
298  
299  
300  
301 sub process_socket_stream{
302  
303 my ($self,$select) = @_;
304 my $STREAM_HEADER_SIZE_BYTES = 8;
305  
306 # socket stream may be chunked
307 my $data = '';
308 my $buf = '';
309 while(my @ready = $select->can_read(0.25)){
310 # print "hay algo no socket\n";
311 my $socket = $ready[0];
312  
313 if($self->tty_mode){
314 # in tty mode, data comes in a shot, without header
315 $buf = $self->__recvAll($socket);
316 return unless($buf);
317 $data .= $buf;
318 # print "leemos en tty_mode '$data'\n";
319 }
320 else{
321 # print "vamos a leer a cabeceira\n";
322 my $header = __recvSize($socket, $STREAM_HEADER_SIZE_BYTES);
323 # print "leendo a cabeceira: $header\n";
324 return unless($header);
325
326 my($stream_type, $length) = unpack('BxxxL>', $header);
327
328 return unless($length > 0);
329
330 # print "Vamos a leer do socket $length bytes que venhen do stream $stream_type\n";
331
332 $data .= __recvSize($socket, $length);
333 }
334
335 return unless($data);
336 }
337  
338 # print "leemos $data\n";
339 # print "leemos en total " . length($data)." bytes\n";
340  
341 $data;
342  
343 }
344  
345  
346  
347 sub process_request_body{
348 my ($self, $socket) = @_;
349  
350 my $data = $self->__recvAll($socket);
351  
352 my $result = (length($data) > 8)?
353 $self->unpack_response_content($data):
354 "";
355  
356 $self->queue_out->enqueue([0,$result]);
357 $self->queue_out->enqueue("END");
358 }
359  
360  
361  
362  
363 sub unpack_response_content{
364  
365 my ($self, $data) = @_;
366  
367 my $line_termination = $self->line_termination;
368  
369 my $result = '';
370  
371 if($data =~ /$line_termination/){
372  
373 foreach my $line (split($line_termination,$data)){
374  
375 my($stream_type,$length,$rest) = unpack('BxxxNA*', $line);
376 # print "tipo:$stream_type|longitud:$length|resto_cadena:$rest\n";
377 $result .= $rest.$line_termination;
378 }
379 }
380 else{
381 my($stream_type,$length,$rest) = unpack('BxxxNA*', $data);
382 # print "NON HAI FIN DE LINEA:tipo:$stream_type|longitud:$length|resto_cadena:$rest\n";
383 $result .= $rest;
384  
385 }
386  
387 $result;
388 }
389  
390  
391  
392 sub __recvSize{
393 my ($socket, $size) = @_;
394  
395 my $data = '';
396 my $buf = '';
397  
398 while($size > 0){
399
400 # $socket->sysread($buf, $size);
401 $socket->read_entity_body($buf, $size);
402  
403 return undef if($buf eq '');
404  
405 # print "pillamos buffer con '$buf', queda $size\n";
406  
407 $data .= $buf;
408 $size -= length($buf);
409
410 }
411  
412 $data;
413  
414 }
415  
416  
417 sub __recvAll{
418 my ($self, $socket) = @_;
419  
420 my $data = '';
421 my $buf = '';
422  
423 while (1) {
424  
425 $buf = '';
426  
427 my $n = $socket->read_entity_body($buf, 1024);
428  
429 # print "leemos $buf ($n bytes) do body da request\n";
430  
431 if(!defined($n)){
432  
433 if($! != EAGAIN || $! != EINTR){
434  
435 die("Read failed: $!");
436 }
437 }
438  
439 last unless($n > 0);
440  
441 $data .= $buf;
442  
443 # in tty mode data comes in a shot, block til next input
444 last if($self->tty_mode);
445  
446 }
447  
448 $data;
449  
450 }
451  
452  
453 sub __sendCmd{
454 my ($self, $cmd, $socket) = @_;
455  
456 $socket->syswrite($cmd . $self->line_termination);
457 }
458  
459 sub __buildUri{
460 my ($self) = @_;
461  
462 '/' . join('/',
463  
464 grep {
465  
466 defined($_)
467  
468 } ( $self->entity, $self->id, $self->action)
469 ) .
470  
471 '?'
472  
473 . join('&', map {
474  
475 $_ . '=' . $self->args->{$_}
476
477 } @{$self->url_args});
478 }
479  
480  
481  
482 1;