blib/lib/Bio/Graphics/Browser2/Render/Slave.pm untested

filter: Statementstmt 0.0% 0 / 462 Branchbran 0.0% 0 / 120 Conditioncond 0.0% 0 / 91 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 62 Podpod 0.0% 0 / 38 totaltotal 0.0% 0 / 773 CC 61 SCAR 35.3
CC
61
Cov
0%
render_tracks
132.0
process_request
110.0
run
90.0
CRAP 34.2
1 package Bio::Graphics::Browser2::Render::Slave;
2  
3 use strict;
4 use HTTP::Daemon;
5 use Storable qw(nfreeze thaw lock_store lock_retrieve);
6 use CGI qw(header param escape unescape);
7 use IO::File;
8 use IO::String;
9 use File::Spec;
10 use Text::ParseWords 'shellwords';
11 use File::Basename 'basename';
12 use File::Path 'mkpath';
13 use Bio::Graphics::GBrowseFeature;
14 use Bio::Graphics::Browser2;
15 use Bio::Graphics::Browser2::I18n;
16 use Bio::Graphics::Browser2::DataSource;
17 use Bio::Graphics::Browser2::RenderPanels;
18 use Bio::Graphics::Browser2::Region;
19 use Bio::Graphics::Browser2::RegionSearch;
20 use Bio::Graphics::Browser2::DataBase;
21 use Time::HiRes 'time';
22 use POSIX 'WNOHANG','setsid','setuid';
23 use Fcntl ':flock';
24  
25 use Carp 'croak';
26  
27 use constant DEBUG => 0;
28 my %CHILDREN;
29  
30 our ($bench_message,$bench_time);
31  
32 BEGIN {
33 use Storable qw(nfreeze thaw retrieve);
34 $Storable::Deparse = 1;
35 $Storable::Eval = 1;
36 }
37  
38 sub new {
39 my $class = shift;
40 my %args = @_;
41  
42 $args{ReuseAddr} = 1 unless exists $args{ReuseAddr};
43 $args{LocalPort} ||= 8101;
44 $args{Listen} ||= 20;
45 $args{PreForkCopies} ||= 5;
46  
47 delete $args{LocalPort} if $args{LocalPort} eq 'dynamic';
48  
49 my $d = HTTP::Daemon->new(%args)
50 or croak "Could not create daemon socket: $@";
51  
52 $args{LocalPort} ||= $d->sockport;
53  
54 my $self = bless {
55 daemon => $d,
56 args => \%args,
57 debug => DEBUG,
58 },ref $class || $class;
59  
60 return $self;
61 }
62  
63 sub d {
64 my $self = shift;
65 my $d = $self->{daemon};
66 $self->{daemon} = shift if @_;
67 $d;
68 }
69 sub listen_port { shift->{args}{LocalPort} }
70 sub pidfile { shift->{args}{PidFile} }
71 sub logfile { shift->{args}{LogFile} }
72 sub user { shift->{args}{User} }
73 sub prefork_copies { shift->{args}{PreForkCopies} }
74 sub pid { shift->{pid} }
75 sub config_cache{ shift->{args}{CCacheDir} || File::Spec->catfile(File::Spec->tmpdir,'gbslave_ccache')}
76 sub kill {
77 my $self = shift;
78 my $pid = $self->pid;
79 if (!$pid && (my $pidfile = $self->pidfile)) {
80 my $fh = IO::File->new($pidfile);
81 $pid = $fh->getline;
82 chomp($pid);
83 $fh->close;
84 }
85 kill TERM=>$pid if defined $pid;
86 }
87 sub logfh {
88 my $self = shift;
89 my $d = $self->{logfh};
90 $self->{logfh} = shift if @_;
91 $d;
92 }
93  
94 sub debug {
95 my $self = shift;
96 my $d = $self->{debug};
97 $self->{debug} = shift if @_;
98 return $d;
99 }
100  
101 sub preload_databases {
102 my $self = shift;
103 my $d = $self->{preload};
104 if (@_) {
105 my $conf_file = shift;
106 $self->{preload} = Bio::Graphics::FeatureFile->new(-file=>$conf_file);
107 $self->{preload}->name($conf_file);
108 }
109 $d;
110 }
111  
112 sub do_preload {
113 my $self = shift;
114 my $conf = $self->preload_databases or return;
115  
116 $self->Info("Preloading databases from ",$conf->name);
117  
118 my @labels = $conf->configured_types;
119  
120 for my $l (@labels) {
121 my $adaptor = $conf->setting($l=>'db_adaptor') or next;
122 my $args = $conf->setting($l=>'db_args') or next;
123 (my $label = $l) =~ s/:database//; # aesthetic
124  
125 my @argv = ref $args eq 'CODE'
126 ? $args->()
127 : shellwords($args||'');
128 if (defined (my $a = $conf->setting($l => 'aggregators'))) {
129 my @aggregators = shellwords($a||'');
130 push @argv,(-aggregator => \@aggregators);
131 }
132 my $db = Bio::Graphics::Browser2::DataBase->open_database($adaptor,@argv);
133 if ($db) {
134 $self->Info("Preloaded $adaptor database $label");
135 } else {
136 $self->Warn("Failed to preload database $label");
137 }
138 }
139 }
140  
141 sub run {
142 my $self = shift;
143 $self->{pid} = $self->become_daemon;
144 return $self->{pid} if $self->{pid};
145  
146 my $quit = 0;
147 my $rotate = 0;
148  
149 $SIG{TERM} = sub { $self->Info('TERM received'); $quit = 1 };
150 $SIG{HUP} = sub { $self->Info('HUP received'); $rotate = 1 };
151  
152 my $d = $self->d;
153 $self->Info('GBrowse render slave starting on port ',$self->listen_port);
154 $self->do_preload;
155  
156 %CHILDREN = map {$_=>1} $self->prefork($self->prefork_copies);
157  
158 # parent sleeps until children need to be "taken care" of
159 if (!%CHILDREN) {
160 $self->request_loop;
161 CORE::exit 0;
162 }
163  
164 if (%CHILDREN) {
165 # $d->close;
166 SLEEP:
167 while (1) {
168 sleep;
169 if ($quit) {
170 CORE::kill TERM=>keys %CHILDREN;
171 last SLEEP;
172 }
173  
174 if ($rotate) {
175 $self->Info("Reopening log file");
176 $self->open_log;
177 $rotate = 0;
178 next SLEEP;
179 }
180  
181 $self->Info('children remaining = ', join ' ',keys %CHILDREN);
182 if (keys %CHILDREN < $self->prefork_copies) {
183 my @new_children = $self->prefork($self->prefork_copies - keys %CHILDREN);
184 unless (@new_children) {
185 $self->request_loop;
186 CORE::exit 0;
187 }
188 %CHILDREN = (%CHILDREN,map {$_=>1} @new_children);
189 next SLEEP;
190 }
191  
192 }
193 unlink $self->pidfile if $self->pidfile;
194 $self->Info('Normal termination');
195 }
196  
197 CORE::exit 0;
198 }
199  
200 sub prefork {
201 my $self = shift;
202 my $copies = shift;
203 my @children;
204  
205 for (1..$copies) {
206 my $child = fork();
207 $DB::inhibit_exit = 0;
208 die "fork() error: $!" unless defined $child;
209 if ($child) {
210 $self->Info("preforked pid $child");
211 push @children,$child;
212 } else {
213 return;
214 }
215 }
216 return @children;
217  
218 }
219  
220 sub request_loop {
221 my $self = shift;
222 my $d = $self->d;
223 $self->preload_databases;
224  
225 my $quit = 0;
226 $SIG{TERM} = sub { $quit = 1 };
227 while (!$quit) {
228 my $c = $d->accept() or next; # accept() is interruptable...
229 $self->process_connection($c);
230 }
231 }
232  
233 sub process_connection {
234 my $self = shift;
235 my $c = shift;
236 $self->Debug("Connect from ",$c->peerhost);
237  
238 while (my $r = $c->get_request) {
239 my $time = time();
240 $self->process_request($r,$c);
241 my $elapsed = time() - $time;
242 $self->Debug("Process_request time: $elapsed s");
243 }
244  
245 $self->Debug("Finished connection from ",$c->peerhost);
246 $c->close;
247 }
248  
249  
250 sub process_request {
251 my $self = shift;
252 my ($r,$c) = @_;
253  
254 $self->Bench('reading request');
255  
256 CGI::initialize_globals();
257 if ($r->method eq 'GET') {
258 $CGI::Q = CGI->new($r->uri->query);
259 } elsif ($r->method eq 'POST') {
260 # This is all to trick CGI.pm into thinking that it is getting the
261 # request from the usual CGI environment.
262 tie *STDIN,IO::String->new($r->content);
263 $ENV{REQUEST_METHOD} = 'POST';
264 $ENV{CONTENT_LENGTH} = $r->content_length;
265 $ENV{CONTENT_TYPE} = $r->content_type;
266 $CGI::Q = CGI->new();
267 }
268  
269 $self->Debug("process_request(): read ",$r->content_length," bytes");
270 $self->Bench('setting environment');
271 $self->setup_environment(param('env'));
272 my $operation = param('operation') || 'invalid';
273  
274 $self->Debug("process_request(): operation = $operation");
275  
276 # make sure databases are already open in parent process
277 $self->Bench('thawing parameters');
278 my $tracks = thaw param('tracks') if param('tracks');
279 my $settings = thaw param('settings') if param('settings');
280 my $dsn = param('datasource');
281 my $d_name = param('data_name');
282 my $d_mtime = param('data_mtime');
283 my $source = $self->get_datasource($dsn,$d_name,$d_mtime);
284 unless ($source) {
285 $self->Info('sending REQUEST DATASOURCE response');
286 $c->send_response(HTTP::Response->new(403=>"REQUEST DATASOURCE: $d_name"));
287 return;
288 }
289 $source or return (403,"REQUEST DATASOURCE: $d_name");
290  
291 $self->Bench('loading databases');
292 $self->load_databases($tracks,$source) if $tracks;
293
294 # forking version
295 if ($self->prefork_copies <= 1) {
296 $self->Bench('forking child');
297 my $child = fork();
298 $DB::inhibit_exit = 0;
299 $self->Fatal("Couldn't fork: $!") unless defined $child;
300 if ($child) {
301 $self->Info("Forked child PID $child");
302 return;
303 } else {
304 $self->d->close();
305 $self->Bench('cloning databases');
306 Bio::Graphics::Browser2::DataBase->clone_databases();
307 $self->Bench("operation $operation");
308 $self->run_operation($c,$operation,$tracks,$source,$settings);
309 $self->Bench("cleaning up");
310 exit 0;
311 }
312 }
313 # preforked version
314 else {
315 $self->Bench("operation $operation");
316 $self->run_operation($c,$operation,$tracks,$source,$settings);
317 $self->Bench("cleaning up");
318 }
319 }
320  
321 sub run_operation {
322 my $self = shift;
323 my ($c,$operation,$tracks,$source,$settings) = @_;
324  
325 my $content = $operation eq 'render_tracks' ? $self->render_tracks($tracks, $source, $settings)
326 : $operation eq 'search_features' ? $self->search_features($tracks,$source, $settings)
327 : 'invalid request';
328  
329 my ($status_code,$status_text,$content_type) =
330 $content =~ /invalid/i ? (400 => 'Bad request', 'text/plain')
331 : (200 => 'Ok', 'application/gbrowse-encoded-genome');
332  
333 $self->Bench('creating response');
334  
335 my $response = HTTP::Response->new($status_code => $status_text,
336 ['Content-type' => $content_type,
337 'Content-length' => length $content],
338 $content
339 );
340  
341 $self->Bench('sending response');
342 $c->send_response($response);
343 $self->Info("host=",$c->peerhost,"; operation=$operation; response=$status_code; bytes=",length $content);
344 }
345  
346 sub load_databases {
347 my $self = shift;
348 my ($tracks,$source,$settings) = @_;
349 for my $t (@$tracks) {
350 # this caches databases in memory
351 my $length = defined $settings->{start} ? $settings->{start}-$settings->{stop}+1 : 0;
352 my $db = $source->open_database($t,$length);
353 }
354 }
355  
356 sub Bench {
357 my $self = shift;
358 my $msg = shift;
359  
360 if ($bench_time && $bench_message) {
361 my $elapsed = time()-$bench_time;
362 $self->Debug("BENCH: $bench_message: $elapsed s");
363 }
364  
365 $bench_message = $msg;
366 $bench_time = time();
367 }
368  
369 sub get_datasource {
370 my $self = shift;
371 my ($dsn,$name,$mtime) = @_;
372  
373 $self->Bench('getting datasource');
374 mkpath $self->config_cache unless -e $self->config_cache;
375  
376 if (Storable::read_magic($dsn)) { # this is a storable image
377 my $source = Storable::thaw($dsn);
378 $name = $source->name;
379 $mtime = $source->mtime;
380 my $cachefile = File::Spec->catfile($self->config_cache,$name);
381 $self->Debug("Using transmitted version of $name");
382 lock_store($source,$cachefile);
383 return $source;
384 } elsif ($name) {
385 my $cachefile = File::Spec->catfile($self->config_cache,$name);
386 if (-e $cachefile && $mtime <= (stat(_))[9]) {
387 $self->Debug("Using cached version of $name config data");
388 my $source = lock_retrieve($cachefile);
389 return $source;
390 } else {
391 $self->Debug("Cache for $name missing or out of date; requesting frozen dsn");
392 return;
393 }
394 } else {
395 $self->Debug("Datasource name missing; requesting frozen dsn");
396 return;
397 }
398 }
399  
400 sub render_tracks {
401 my $self = shift;
402 my ($tracks,$datasource,$settings) = @_;
403  
404 my $language = thaw param('language');
405 my $panel_args = thaw param('panel_args');
406  
407 $self->do_init($datasource);
408 $self->adjust_conf($datasource);
409  
410 $self->Debug("render_tracks(): Opening database...");
411  
412 # Find the segment - it may be hiding in any of the databases.
413 $self->Bench('searching for segment');
414 my (%seenit,$segment,$db);
415 if ($panel_args->{section} and $panel_args->{section} eq 'detail') { # short cut
416 $segment = Bio::Graphics::Feature->new(-seq_id=>$settings->{'ref'},
417 -start => $settings->{'start'},
418 -end =>$settings->{'stop'});
419 } else {
420 for my $track ('general',@$tracks) {
421 $db = $datasource->open_database($track) or next;
422 next if $seenit{$db}++;
423 ($segment) = $db->segment(-name => $settings->{'ref'},
424 -start => $settings->{'start'},
425 -stop => $settings->{'stop'});
426 last if $segment;
427 }
428 }
429  
430 $self->Fatal("Can't get segment for $settings->{ref}:$settings->{start}..$settings->{stop} (1)")
431 unless $segment;
432  
433 $self->Debug("render_tracks(): Got database handle $db") if $db;
434  
435 # BUG: duplicated code from Render.pm -- move into a common place
436 $panel_args->{section} ||= ''; # prevent uninit variable warnings
437 if ($panel_args->{section} eq 'overview') {
438 $segment = Bio::Graphics::Browser2::Region->whole_segment($segment,$settings);
439 } elsif ($panel_args->{section} eq 'region') {
440 $segment = Bio::Graphics::Browser2::Region->region_segment($segment,$settings);
441 }
442  
443 $self->Fatal("Can't get segment for $settings->{ref}:$settings->{start}..$settings->{stop} (2)")
444 unless $segment;
445
446 # generate the panels
447 $self->Bench('creating renderpanel');
448 $self->Debug("calling RenderPanels->new()");
449 my $renderer = Bio::Graphics::Browser2::RenderPanels->new(-segment => $segment,
450 -source => $datasource,
451 -settings => $settings,
452 -language => $language);
453 $self->Debug("Got renderer()");
454  
455 #FIX: this is a cut and paste, and isn't fully general!
456 # hiliting should be handled in RenderPanels, not in Render
457 if ($settings->{h_feat}) {
458 $panel_args->{hilite_callback} = sub {
459 my $feature = shift;
460 # if we get here, we select the search term for highlighting
461 return unless $feature->display_name;
462 return $settings->{h_feat}{lc $feature->display_name};
463 };
464 }
465  
466 $self->Bench('calling make_requests');
467 my $requests = $renderer->make_requests({labels => $tracks,%$panel_args});
468  
469 $self->Debug("Calling run_local_requests(tracks=@$tracks)");
470 $self->Bench('calling run_local_requests');
471 $renderer->run_local_requests($requests,$panel_args);
472  
473 $self->Debug("Finished run_local_requests()");
474  
475 # we return the URL to the PNG, the image map, the width and height of the image,
476 # keyed to the requested label(s)
477 my %results;
478 for my $label (keys %$requests) {
479
480 my $response = $requests->{$label};
481 my $map = $response->map;
482 my $titles = $response->titles;
483 my $width = $response->width;
484 my $height = $response->height;
485 my $imagedata = $response->gd;
486  
487 $results{$label} = {map => $map,
488 titles => $titles,
489 width => $width,
490 height => $height,
491 imagedata => eval{$imagedata->gd2}};
492 }
493 my $content = nfreeze \%results;
494 return $content;
495 }
496  
497 sub search_features {
498 my $self = shift;
499 my ($tracks,$datasource,$settings) = @_;
500  
501 my $searchargs = thaw param('searchargs');
502  
503 # initialize a region search object
504 my $search = Bio::Graphics::Browser2::RegionSearch->new(
505 {source => $datasource,
506 state => $settings}
507 ) or return;
508 $search->init_databases($tracks,'local_search');
509  
510 warn "SERVER, dbid = ",$settings->{dbid} if DEBUG;
511  
512 my $results = $search->search_features_locally($searchargs);
513 return unless $results;
514 my @features = map { $self->clone_feature($_) } grep {defined $_} @$results;
515 return nfreeze(\@features);
516 }
517  
518 sub clone_feature {
519 my $self = shift;
520 my $f = shift;
521 my $level = shift || 0;
522 my %attributes = map {$_=>[$f->get_tag_values($_)]} eval {$f->get_all_tags};
523 my $clone = Bio::Graphics::GBrowseFeature->new(
524 -name => $f->name,
525 -primary_tag => $f->primary_tag,
526 -source_tag => eval {$f->source_tag} || 'region',
527 -seq_id => $f->seq_id,
528 -start => $f->start,
529 -end => $f->end,
530 -strand => $f->strand,
531 -score => eval{$f->score} || 0,
532 -desc => eval{$f->desc} || '',
533 -primary_id => eval{$f->primary_id} || undef,
534 -attributes => \%attributes,
535 );
536 for my $s (map {$self->clone_feature($_,$level+1)} $f->get_SeqFeatures()) {
537 $clone->add_SeqFeature($s) ;
538 }
539 $clone->gbrowse_dbid($f->gbrowse_dbid)
540 if $level == 0 && $f->can('gbrowse_dbid');
541 return $clone;
542 }
543  
544 sub setup_environment {
545 my $self = shift;
546 my $env_str = shift or return;
547  
548 my $env = thaw($env_str);
549 for my $key (keys %$env) {
550 next unless $key =~ /^(GBROWSE|HTTP)/;
551 $ENV{$key} = $env->{$key};
552 }
553 }
554  
555 sub become_daemon {
556 my $self = shift;
557  
558 my $child = fork();
559 croak "Couldn't fork: $!" unless defined $child;
560 return $child if $child; # return child PID in parent process
561  
562 # install signal handler in the master server
563 $SIG{CHLD} = sub {
564 while ((my $c = waitpid(-1,WNOHANG))>0) {
565 $self->Info("Child pid $c terminated");
566 delete $CHILDREN{$c};
567 }
568 };
569 umask(0);
570 $ENV{PATH} = '/bin:/sbin:/usr/bin:/usr/sbin';
571  
572 setsid(); # become process leader
573 chdir '/'; # don't hold open working directories
574 open STDIN, "</dev/null";
575 open STDOUT,">/dev/null";
576  
577 # write out PID file if requested
578 if (my $l = $self->pidfile) {
579 my $fh = IO::File->new($l,">")
580 or $self->Fatal("Could not open pidfile $l: $!");
581 $fh->print($$)
582 or $self->Fatal("Could not write to pidfile $l: $!");
583 $fh->close();
584 }
585  
586 $self->open_log;
587  
588 open STDERR,">&",$self->logfh if $self->logfh;
589 $self->set_user;
590 return;
591 }
592  
593 # open log file if requested
594 sub open_log {
595 my $self = shift;
596 my $l = $self->logfile or return;
597 my $fh = IO::File->new($l,">>") # append
598 or $self->Fatal("Could not open logfile $l: $!");
599 $fh->autoflush(1);
600 $self->logfh($fh);
601 }
602  
603 # change user if requested
604 sub set_user {
605 my $self = shift;
606 my $u = $self->user or return;
607 my $uid = getpwnam($u);
608 defined $uid or $self->Fatal("Cannot change uid to $u: unknown user");
609 setuid($uid) or $self->Fatal("Cannot change uid to $u: $!");
610 }
611  
612 # adjust the passed config file by overriding any options specified in the
613 # preload config file
614 sub adjust_conf {
615 my $self = shift;
616 my $datasource = shift;
617  
618 my $preload = $self->preload_databases or return;
619 my @settings = $preload->setting('general') or return;
620 my $globals = $datasource->globals;
621 $self->Debug('Overriding passed settings with slave-specific settings from preload file');
622 for my $s (@settings) {
623 my $value = $preload->setting(general=>$s);
624 $globals->setting(general=>$s,$value);
625 }
626 }
627  
628 sub do_init {
629 my $self = shift;
630 my $datasource = shift;
631 $self->Debug('do_init()');
632 $datasource->initialize_code();
633 }
634  
635 sub Debug {
636 my $self = shift;
637 my @msg = @_;
638 return unless $self->debug > 2;
639 $self->_log('debug',@msg);
640 }
641  
642 sub Info {
643 my $self = shift;
644 my @msg = @_;
645 return unless $self->debug > 1;
646 $self->_log('info',@msg);
647 }
648  
649 sub Warn {
650 my $self = shift;
651 my @msg = @_;
652 return unless $self->debug > 0;
653 $self->_log('warn',@msg);
654 }
655  
656 sub Fatal {
657 my $self = shift;
658 my @msg = @_;
659 $self->_log('fatal',@msg);
660 croak @msg;
661 }
662  
663 sub _log {
664 my $self = shift;
665 my ($level,@msg) = @_;
666 my $time = localtime();
667 my $fh = $self->logfh || \*STDERR;
668 $fh->printf("%25s %-8s %-12s","[$time]","[$level]","[pid=$$]");
669 $fh->print(@msg,"\n");
670 }
671  
672 1;