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

filter: Statementstmt 0.0% 0 / 616 Branchbran 0.0% 0 / 118 Conditioncond 0.0% 0 / 180 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 98 Podpod 0.0% 0 / 81 totaltotal 0.0% 0 / 1093 CC 60 SCAR 24.5
CC
60
Cov
0%
cleanup
56.0
adjust_instances
42.0
become_daemon
30.0
CRAP 11.6
1 package Bio::Graphics::Browser2::Render::Slave::AWS_Balancer;
2  
3 # This module is used to manage GBrowse slaves in an on-demand Amazon EC2
4 # environment.
5  
6 use strict;
7 use Parse::Apache::ServerStatus;
8 use VM::EC2 1.22;
9 use VM::EC2::Instance::Metadata;
10 use VM::EC2::Staging::Manager;
11 use LWP::Simple 'get','head';
12 use LWP::UserAgent;
13 use Parse::Apache::ServerStatus;
14 use IO::File;
15 use POSIX 'strftime','setsid','setuid';
16 use Carp 'croak';
17 use FindBin '$Bin';
18  
19 use constant CONFIGURE_SLAVES => "$Bin/gbrowse_configure_slaves.pl";
20  
21 # arguments:
22 # ( -conf => $config_path,
23 # -access_key => $aws_access_key,
24 # -secret_key => $aws_secret_key,
25 # -logfile => $path_to_logfile,
26 # -pidfile => $path_to_pidfile,
27 # -user => $user_name_to_run_under,# (root only)
28 # -daemon => $daemon_mode,
29 # -ssh_key => $ssh_login_key (optional)
30 # )
31  
32 sub new {
33 my $class = shift;
34 my %args = @_;
35 $args{-conf} or croak "-conf argument required";
36 -e $args{-conf} or croak "$args{-conf} not found";
37  
38 #setup EC2 environment
39 $args{-access_key} ||= $ENV{EC2_ACCESS_KEY};
40 $args{-secret_key} ||= $ENV{EC2_SECRET_KEY};
41  
42 my $self = bless {
43 access_key => $args{-access_key},
44 secret_key => $args{-secret_key},
45 logfile => $args{-logfile},
46 pidfile => $args{-pidfile},
47 user => $args{-user},
48 conf_file => $args{-conf},
49 daemon => $args{-daemon},
50 ssh_key => $args{-ssh_key},
51 verbosity => 2,
52 },ref $class || $class;
53 $self->initialize();
54 return $self;
55 }
56  
57 sub logfile {shift->{logfile}}
58 sub pidfile {shift->{pidfile}}
59 sub pid {shift->{pid}}
60 sub user {shift->{user}}
61 sub daemon {shift->{daemon}}
62 sub ssh_key {shift->{ssh_key}}
63 sub ec2_credentials {
64 my $self = shift;
65 if ($self->running_as_instance) {
66 my $credentials = $self->{instance_metadata}->iam_credentials;
67 return (-security_token => $credentials) if $credentials;
68 $self->log_debug('No instance security credentials. Does this instance have an IAM role?');
69 }
70 $self->{access_key} ||= $self->_prompt('Enter your EC2 access key:');
71 $self->{secret_key} ||= $self->_prompt('Enter your EC2 secret key:');
72 return (-access_key => $self->{access_key},
73 -secret_key => $self->{secret_key})
74 }
75 sub logfh {
76 my $self = shift;
77 my $d = $self->{logfh};
78 $self->{logfh} = shift if @_;
79 $d;
80 }
81  
82 sub verbosity {
83 my $self = shift;
84 my $d = $self->{verbosity};
85 $self->{verbosity} = shift if @_;
86 $d;
87 }
88  
89 sub initialize {
90 my $self = shift;
91 $self->_parse_conf_file;
92 $self->_parse_instance_metadata;
93 }
94  
95 sub DESTROY {
96 my $self = shift;
97 $self->cleanup;
98 }
99  
100 sub run {
101 my $self = shift;
102 $self->become_daemon && return
103 if $self->daemon;
104  
105 my $killed;
106 local $SIG{INT} = local $SIG{TERM} = sub {$self->log_info('Termination signal received');
107 $killed++; };
108 $self->{pid} = $$;
109  
110 my $poll = $self->master_poll;
111 eval {$self->ec2} or croak $@;
112 $self->log_info("Monitoring load at intervals of $poll sec\n");
113 while (sleep $poll) {
114 last if $killed;
115 my $load = $self->get_load();
116 $self->log_debug("Current load: $load req/s\n");
117 $self->adjust_instances($load);
118 $self->update_requests();
119 }
120  
121 $self->log_info('Normal termination');
122 }
123  
124 sub stop_daemon {
125 my $self = shift;
126 my $pid = $self->pid;
127 if (!$pid && (my $pidfile = $self->pidfile)) {
128 my $fh = IO::File->new($pidfile) or croak "No PID file; is daemon runnning?";
129 $pid = $fh->getline;
130 chomp($pid);
131 $fh->close;
132 }
133 unlink $self->pidfile if -e $self->pidfile;
134 kill TERM=>$pid if defined $pid;
135 }
136  
137 #######################
138 # configuration
139 ######################
140  
141 sub conf_file {shift->{conf_file}}
142  
143 sub load_table {
144 return shift->{options}{'LOAD TABLE'};
145 }
146  
147 sub option {
148 my $self = shift;
149 my ($stanza,$option) = @_;
150 return $self->{options}{uc $stanza}{$option};
151 }
152  
153 # given load, returns two element list of min_instances, max_instances
154 sub slaves_wanted {
155 my $self = shift;
156 my $load = shift;
157  
158 my $lt = $self->load_table or croak 'no load table!';
159 my ($min,$max) = (0,0);
160 for my $l (sort {$a<=>$b} keys %$lt) {
161 ($min,$max) = @{$lt->{$l}} if $load >= $l;
162 }
163 return ($min,$max);
164 }
165  
166 sub slave_instance_type { shift->option('SLAVE','instance_type') || 'm1.large' }
167 sub slave_spot_bid { shift->option('SLAVE','spot_bid') || 0.08 }
168 sub slave_ports { my $p = shift->option('SLAVE','ports');
169 my @p = split /\s+/,$p;
170 return @p ? @p : (8101); }
171 sub slave_endpoint {
172 my $self = shift;
173 if ($self->running_as_instance) {
174 my $zone = $self->{instance_metadata}->endpoint;
175 return $zone;
176 } else {
177 my $region = $self->option('SLAVE','region') || 'us-east-1';
178 return "http://ec2.$region.amazonaws.com";
179 }
180 }
181  
182 sub slave_zone {
183 my $self = shift;
184 if ($self->running_as_instance) {
185 return $self->{instance_metadata}->availabilityZone;
186 } else {
187 $self->option('SLAVE','availability_zone');
188 }
189 }
190  
191 sub slave_image_id {
192 my $self = shift;
193 if ($self->running_as_instance) {
194 return $self->{instance_metadata}->imageId;
195 } else {
196 $self->option('SLAVE','image_id');
197 }
198 }
199  
200 sub slave_data_snapshots {
201 my $self = shift;
202 return split /\s+/,$self->option('SLAVE','data_snapshots');
203 }
204  
205 sub slave_block_device_mapping {
206 my $self = shift;
207 my $image = $self->ec2->describe_images($self->slave_image_id)
208 or die "Could not find image ",$self->slave_image_id;
209 my $root = $image->rootDeviceName;
210 my @root = grep {$_->deviceName eq $root} $image->blockDeviceMapping;
211
212 my @snaps = $self->slave_data_snapshots;
213 my @bdm;
214 DEVICE:
215 for my $major ('g'..'z') {
216 for my $minor (1..15) {
217 my $snap = shift @snaps or last DEVICE;
218 push @bdm,"/dev/sd${major}${minor}=${snap}::true";
219 }
220 }
221 return [@root,@bdm];
222 }
223  
224 sub slave_subnet {
225 my $self = shift;
226 if ($self->running_as_instance) {
227 return eval {(values %{$self->{instance_metadata}->interfaces})[0]{subnetId}};
228 } else {
229 $self->option('SLAVE','subnet');
230 }
231 }
232  
233 sub slave_ssh_key {
234 my $self = shift;
235 my $key = $self->ssh_key;
236 $key ||= $self->option('SLAVE','ssh_key');
237 return $key;
238 }
239  
240 sub slave_security_group {
241 my $self = shift;
242 my $sg = $self->{slave_security_group};
243 return $sg if $sg;
244 my $ec2 = $self->ec2;
245 $sg = eval {$ec2->describe_security_groups(-name => "GBROWSE_SLAVE_$$")};
246 $sg ||= $ec2->create_security_group(-name => "GBROWSE_SLAVE_$$",
247 -description => 'Temporary security group for slave communications');
248 my $ip = $self->running_as_instance ? $self->internal_ip : $self->master_ip;
249
250 $self->log_debug(
251 $sg->authorize_incoming(-protocol => 'tcp',
252 -port => $_,
253 -source_ip => "$ip/32")
254 ) foreach $self->slave_ports;
255 $self->log_debug(
256 $sg->authorize_incoming(-protocol => 'tcp',
257 -port => 22,
258 -source_ip=> "$ip/32"))
259 if $self->slave_ssh_key;
260
261 $sg->update or croak $ec2->error_str;
262 return $self->{slave_security_group} = $sg;
263 }
264  
265 sub ec2 {
266 my $self = shift;
267 # create a new ec2 each time because security credentials may expire
268 my @credentials = $self->ec2_credentials;
269 return $self->{ec2} = VM::EC2->new(-endpoint => $self->slave_endpoint,
270 -raise_error => 1,
271 @credentials);
272 }
273  
274 sub internal_ip {
275 my $self = shift;
276 return unless $self->running_as_instance;
277 return $self->{instance_metadata}->privateIpAddress;
278 }
279  
280 sub master_security_group {
281 my $self = shift;
282 return unless $self->running_as_instance;
283 my $sg = ($self->{instance_metadata}->securityGroups)[0];
284 $sg =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
285 return $sg;
286 }
287  
288 sub master_ip {
289 my $self = shift;
290 my $ip = $self->option('MASTER','external_ip');
291 $ip ||= $self->_get_external_ip;
292 return $ip;
293 }
294  
295 # poll interval in seconds
296 sub master_poll {
297 my $self = shift;
298 my $pi = $self->option('MASTER','poll_interval');
299 return $pi * 60;
300 }
301  
302 sub master_server_status_url {
303 my $self = shift;
304 return $self->option('MASTER','server_status_url')
305 || 'http://localhost/server-status';
306 }
307  
308 sub running_as_instance {
309 my $self = shift;
310 return -e '/var/lib/cloud/data/previous-instance-id'
311 && head('http://169.254.169.254');
312 }
313  
314  
315 # update conf file with new snapshot images
316 sub update_data_snapshots {
317 my $self = shift;
318 my @snapshot_ids = @_;
319 my $timestamp = 'synchronized with local filesystem on '.localtime;
320 my $conf_file = $self->conf_file;
321 my ($user,$group) = (stat($conf_file))[4,5];
322 open my $in,'<',$conf_file or die "Couldn't open $conf_file: $!";
323 open my $out,'>',"$conf_file.new" or die "Couldn't open $conf_file: $!";
324 while (<$in>) {
325 chomp;
326 s/^(data_snapshots\s*=).*/$1 @snapshot_ids # $timestamp/;
327 print $out "$_\n";
328 }
329 close $in;
330 close $out;
331 rename "$conf_file","$conf_file.bak" or die "Can't rename $conf_file: $!";
332 rename "$conf_file.new","$conf_file" or die "Can't rename $conf_file.new: $!";
333 chown $user,$group,$conf_file;
334 }
335  
336 #######################
337 # status
338 ######################
339  
340 # return true if slave is listening on at least one of the designated ports
341 sub ping_slave {
342 my $self = shift;
343 my $instance = shift;
344 my $ip = $self->running_as_instance?$instance->privateIpAddress:$instance->ipAddress;
345 my ($port) = $self->slave_ports;
346 my $ua = LWP::UserAgent->new;
347 my $req = HTTP::Request->new(HEAD => "http://$ip:$port");
348 my $res = $ua->request($req);
349 return $res->code == 403;
350 }
351  
352 # returns list of slave instances as VM::EC2::Instance objects
353 sub running_slaves {
354 my $self = shift;
355 $self->{running_slaves} ||= {};
356 return values %{$self->{running_slaves}};
357 }
358  
359 sub add_slave {
360 my $self = shift;
361 my $instance = shift;
362 $self->{running_slaves}{$instance}=$instance;
363 }
364  
365 sub remove_slave {
366 my $self = shift;
367 my $instance = shift;
368 delete $self->{running_slaves}{$instance};
369 }
370  
371 # given an instance ID, returns the slave VM::EC2::Instance object
372 sub id2slave {
373 my $self = shift;
374 my $id = shift;
375 return $self->{running_slaves}{$id};
376 }
377  
378 # spot requests - only tracks pending requests
379 sub pending_spot_requests {
380 my $self = shift;
381 $self->{pending_requests} ||= {};
382 return values %{$self->{pending_requests}};
383 }
384  
385 sub add_spot_request {
386 my $self = shift;
387 my $sr = shift;
388 $self->{pending_requests}{$sr} = $sr;
389 }
390  
391 sub remove_spot_request {
392 my $self = shift;
393 my $sr = shift;
394 delete $self->{pending_requests}{$sr};
395 }
396  
397 sub id2_spot_request {
398 my $self = shift;
399 my $id = shift;
400 return $self->{pending_requests}{$id};
401 }
402  
403 sub get_load {
404 my $self = shift;
405 $self->{pr} ||= Parse::Apache::ServerStatus->new(url=>$self->master_server_status_url);
406 if (-e '/tmp/gbrowse_load') {
407 open my $fh,'/tmp/gbrowse_load';
408 chomp (my $load = <$fh>);
409 return $load;
410 }
411 my $stats = $self->{pr}->get or $self->fatal("couldn't fetch load from Apache status: ",$self->{pr}->errstr);
412 return $stats->{rs};
413 }
414  
415  
416 ###########################################
417 # state change
418 ###########################################
419  
420 # this is called to update the number of live and pending slaves
421 # according to the load
422 sub adjust_instances {
423 my $self = shift;
424 my $load = shift;
425 my ($min,$max) = $self->slaves_wanted($load);
426 my $current = $self->pending_spot_requests + $self->running_slaves;
427
428 if ($current < $min) {
429 $self->log_debug("Need to add more slave spot instances (have $current, wanted $min)\n");
430 $self->request_spot_instance while $current++ < $min;
431 }
432  
433 elsif ($current > $max) {
434 $self->log_debug("Need to delete some slave spot instances (have $current, wanted $max)\n");
435 my $reconfigure;
436 my $ec2 = $self->ec2;
437 my @candidates = ($self->pending_spot_requests,$self->running_slaves);
438 while ($current-- > $max) {
439 my $c = shift @candidates;
440 if ($c->isa('VM::EC2::Spot::InstanceRequest')) {
441 $self->log_debug("Cancelling spot instance request $c\n");
442 $ec2->cancel_spot_instance_requests($c);
443 $self->remove_spot_request($c);
444 $reconfigure++;
445 } elsif ($c->isa('VM::EC2::Instance')) {
446 $self->log_debug("Terminating slave instance $c\n");
447 $ec2->terminate_instances($c);
448 $self->remove_slave($c);
449 $reconfigure++;
450 }
451 }
452 # we reconfigure master immediately to avoid calling instance that were terminated
453 $self->reconfigure_master() if $reconfigure;
454 }
455 }
456  
457 # this is called to act on state changes in spot requests and instances
458 sub update_requests {
459 my $self = shift;
460 my @requests = $self->pending_spot_requests;
461 for my $sr (@requests) {
462 my $state = $sr->current_status;
463 $self->log_debug("Status of $sr is $state");
464 my $instance = $sr->instance;
465 if ($state eq 'fulfilled' && $instance && $instance->instanceState eq 'running') {
466 $instance->add_tag(Name => 'GBrowse Slave');
467 $self->log_debug("New instance $instance; testing readiness");
468 next unless $self->ping_slave($instance); # not ready - try again on next poll
469 $self->log_debug("New slave instance is ready");
470 $self->add_slave($instance);
471 $self->remove_spot_request($sr); # we will never check this request again
472 $self->reconfigure_master();
473 } elsif ($sr->current_state =~ /cancelled|failed/ ) {
474 $self->remove_spot_request($sr);
475 }
476 }
477 }
478  
479 # launch a spot instance request
480 sub request_spot_instance {
481 my $self = shift;
482 my $ec2 = $self->ec2;
483  
484 my $subnet = $self->slave_subnet;
485 my @ports = $self->slave_ports;
486 my $key = $self->slave_ssh_key;
487  
488 my @options = (
489 -image_id => $self->slave_image_id,
490 -instance_type => $self->slave_instance_type,
491 -instance_count => 1,
492 -security_group_id => $self->slave_security_group,
493 -spot_price => $self->slave_spot_bid,
494 -block_device_mapping => $self->slave_block_device_mapping,
495 -user_data => "#!/bin/sh\nexec /opt/gbrowse/etc/init.d/gbrowse-slave start @ports",
496 $subnet? (-subnet_id => $subnet) : (),
497 $key ? (-key_name => $key) : (),
498 );
499  
500 my @debug_options;
501 for (my $i = 0;$i<@options;$i+=2) {
502 my $a = $options[$i];
503 my $v = $options[$i+1];
504 if (ref $v && ref $v eq 'ARRAY') {
505 push @debug_options,($a=>$_) foreach @$v;
506 } else {
507 push @debug_options,($a=>$v);
508 }
509 }
510
511  
512 my $debug_options = "@debug_options";
513 $debug_options =~ tr/\n/ /;
514  
515 $self->log_debug("Launching a spot request with options: $debug_options\n");
516 my @requests = $ec2->request_spot_instances(@options);
517 @requests or croak $ec2->error_str;
518  
519 $_->add_tag(Requestor=>'GBrowse AWS Balancer') foreach @requests;
520 $self->add_spot_request($_) foreach @requests;
521 }
522  
523 sub kill_slave {
524 my $self = shift;
525 my $instance = shift;
526 $self->remove_slave($instance);
527 $self->reconfigure_master();
528 $instance->terminate();
529 }
530  
531 sub reconfigure_master {
532 my $self = shift;
533 my @slaves = $self->running_slaves;
534 my @ips = map {$self->running_as_instance?$_->privateIpAddress:$_->ipAddress} @slaves;
535 my @a;
536 for my $i (@ips) {
537 for my $p ($self->slave_ports) {
538 push @a,"http://$i:$p";
539 }
540 }
541 if (@a) {
542 system 'sudo',CONFIGURE_SLAVES,(map {('--set'=>$_)} @a);
543 } else {
544 system 'sudo',CONFIGURE_SLAVES,'--set','';
545 }
546
547 }
548  
549 sub log_debug {shift->_log(3,@_)}
550 sub log_info {shift->_log(2,@_)}
551 sub log_warn {shift->_log(1,@_)}
552 sub log_crit {shift->_log(0,@_)}
553 sub fatal {
554 my $self = shift;
555 my @msg = shift;
556 $self->log_crit(@msg);
557 die;
558 }
559  
560 sub _log {
561 my $self = shift;
562 my ($level,@msg) = @_;
563 return unless $level <= $self->verbosity;
564 my $ts = strftime('%d/%b/%Y:%H:%M:%S %z',localtime);
565 my $msg = ucfirst "@msg";
566 chomp($msg);
567 print STDERR "[$ts] $msg\n";
568 }
569  
570 sub cleanup {
571 my $self = shift;
572 return if !$self->{pid} || $self->{pid} != $$;
573  
574 my $ec2 = eval{$self->ec2} or return;
575 $self->log_debug('Running cleanup routine');
576  
577 my @requests = $self->pending_spot_requests;
578 my @instances = ($self->running_slaves,grep {$_} map {$_->instance} @requests);
579  
580 if (@instances) {
581 $self->log_debug("terminating spot instances @instances\n");
582 delete $self->{running_slaves};
583 $self->reconfigure_master();
584 $ec2->terminate_instances(@instances);
585 }
586  
587 if (my @requests = grep {$_->current_state eq 'open'} $self->pending_spot_requests) {
588 $self->log_debug("cancelling spot instance requests @requests\n");
589 $ec2->cancel_spot_instance_requests(@requests);
590 delete $self->{pending_requests};
591 }
592  
593 if (my $sg = $self->{slave_security_group}) {
594 if (@instances) {
595 $self->log_debug('waiting for running instances to terminate');
596 $ec2->wait_for_instances(@instances);
597 }
598 $self->ec2->delete_security_group($sg);
599 delete $self->{slave_security_group};
600 $self->log_debug("deleting security group $sg\n");
601 }
602  
603 unlink $self->pidfile if $self->pidfile;
604 }
605  
606  
607  
608 #######################
609 # Synchronization
610 #######################
611  
612 sub launch_staging_server {
613 my $self = shift;
614 my $ec2 = $self->ec2;
615 my $staging = $self->{staging} ||= $ec2->staging_manager(-on_exit=>'run',
616 -verbose=>3);
617 $self->log_debug("Requesting block device mapping: ",join ',',@{$self->slave_block_device_mapping});
618 my $server = $staging->get_server(-name => 'slave_staging_server',
619 -username => 'admin',
620 -instance_type => $self->slave_instance_type,
621 -image_name => $self->slave_image_id,
622 -block_devices => $self->slave_block_device_mapping,
623 -server_class => 'Bio::Graphics::Browser2::Render::Slave::StagingServer', # this is defined at the bottom of this .pm file
624 -architecture => undef
625 );
626 $server->{manager} = $staging; # avoid global destruction issues
627 return $server;
628 }
629  
630 #######################
631 # Daemon stuff
632 #######################
633  
634 # BUG - redundant code cut-and-paste from Slave.pm
635 sub become_daemon {
636 my $self = shift;
637  
638 my $child = fork();
639 croak "Couldn't fork: $!" unless defined $child;
640 return $child if $child; # return child PID in parent process
641  
642 umask(0);
643 $ENV{PATH} = '/bin:/sbin:/usr/bin:/usr/sbin';
644  
645 setsid(); # become process leader
646  
647 # write out PID file if requested
648 if (my $l = $self->pidfile) {
649 my $fh = IO::File->new($l,">")
650 or $self->log_crit("Could not open pidfile $l: $!");
651 $fh->print($$)
652 or $self->log_crit("Could not write to pidfile $l: $!");
653 $fh->close();
654 }
655 $self->open_log;
656 open STDERR,">&",$self->logfh if $self->logfh;
657  
658 chdir '/'; # don't hold open working directories
659 open STDIN, "</dev/null";
660 open STDOUT,">/dev/null";
661  
662 $self->set_user;
663 return;
664 }
665  
666 # change user if requested
667 sub set_user {
668 my $self = shift;
669 my $u = $self->user or return;
670 my $uid = getpwnam($u);
671 defined $uid or $self->log_crit("Cannot change uid to $u: unknown user");
672 setuid($uid) or $self->log_crit("Cannot change uid to $u: $!");
673 }
674  
675 # open log file if requested
676 sub open_log {
677 my $self = shift;
678 my $l = $self->logfile or return;
679 my $fh = IO::File->new($l,">>") # append
680 or $self->Fatal("Could not open logfile $l: $!");
681 $fh->autoflush(1);
682 $self->logfh($fh);
683 }
684  
685  
686 #######################
687 # internal routines
688 ######################
689  
690 sub _get_external_ip {
691 my $self = shift;
692 my $ip= get('http://icanhazip.com');
693 chomp($ip);
694 $self->log_info("Found external IP address $ip");
695 return $ip;
696 }
697  
698 sub _parse_conf_file {
699 my $self = shift;
700 return if exists $self->{options}{'LOAD TABLE'};
701 open my $f,$self->conf_file or croak "Could not open ",$self->conf_file,": $!";
702 $self->{pushback} = [];
703 while (defined(my $line = $self->_getline($f))) {
704 $self->_parse_stanza($1,$f) if $line =~ /^\[([^]]+)\]/;
705 }
706 close $f;
707 croak "invalid config file; must contain [LOAD TABLE] and [SLAVE] stanzas"
708 unless exists $self->{options}{'LOAD TABLE'} and exists $self->{options}{'SLAVE'};
709 }
710  
711 sub _parse_stanza {
712 my $self = shift;
713 my ($stanza,$fh) = @_;
714 if (uc $stanza eq 'LOAD TABLE') {
715 $self->_parse_load_table($fh);
716 } else {
717 $self->_parse_regular_stanza($stanza,$fh);
718 }
719 }
720  
721 sub _parse_load_table {
722 my $self = shift;
723 my $fh = shift;
724 while (my $line = $self->_get_stanza_line($fh)) {
725 my @tokens = split /\s+/,$line;
726 @tokens == 3 or croak "invalid load table line: $line";
727 my ($load,$min,$max) = @tokens;
728 $self->{options}{'LOAD TABLE'}{$load} = [$min,$max];
729 }
730 }
731  
732 sub _parse_regular_stanza {
733 my $self = shift;
734 my ($stanza,$fh) = @_;
735 while (my $line = $self->_get_stanza_line($fh)) {
736 my ($option,$value) = $line =~ /^(\S+)\s*=\s*(.+)/ or next;
737 $self->{options}{uc $stanza}{$option} = $value;
738 }
739 }
740  
741 sub _get_stanza_line {
742 my $self = shift;
743 my $fh = shift;
744 local $^W=0;
745 my $line = $self->_getline($fh);
746 if ($line =~ /^\[/) {
747 push @{$self->{pushback}},$line;
748 return;
749 }
750 return $line;
751 }
752  
753 sub _getline {
754 my $self = shift;
755 my $fh = shift;
756  
757 if (@{$self->{pushback}}) {
758 return pop @{$self->{pushback}};
759 }
760  
761 while (1) {
762 defined(my $line = <$fh>) or return;
763 chomp $line;
764 $line =~ /^\s*#/ and next;
765 $line =~ s/\s+#.*$//;
766 $line =~ /\S/ or next;
767 return $line;
768 }
769 }
770  
771 sub _parse_instance_metadata {
772 my $self = shift;
773 $self->{instance_metadata} ||= VM::EC2::Instance::Metadata->new();
774 }
775  
776 sub _prompt {
777 my $self = shift;
778 my $msg = shift;
779 -t \*STDIN or return;
780 print STDERR $msg;
781 my $result = <STDIN>;
782 chomp $result;
783 return $result;
784 }
785  
786 ##############################################################################################################
787 # descendent of VM::EC2::Staging::Server that adds a few tricks
788 ##############################################################################################################
789  
790 package Bio::Graphics::Browser2::Render::Slave::StagingServer;
791 use base 'VM::EC2::Staging::Server';
792 use Sys::Hostname;
793  
794 use constant GB => 1_073_741_824;
795 use constant TB => 1_099_511_627_776;
796  
797 # return the size of the /opt/gbrowse volume in GB
798 # we intentionally truncate to floor
799 sub volume_size {
800 my $self = shift;
801 my $df = $self->scmd('df -B 1 /opt/gbrowse');
802 my ($total,$used,$available) = $df =~ /(\d+)\s+(\d+)\s+(\d+)/;
803 return int(0.5 + $total/GB);
804 }
805  
806 sub grow_volume {
807 my $self = shift;
808 my $gig_wanted = shift;
809  
810 # get information about the /dev/volumes/gbrowse lv
811 my ($lv,$vg,undef,$size) = split /,/,$self->scmd('sudo lvs /dev/volumes/gbrowse --noheadings --units g --nosuffix --separator ,');
812 $lv =~ s/^\s+//;
813 my $needed = int($gig_wanted-$size);
814 return if $needed <= 0;
815  
816 $self->info("Resizing /opt/gbrowse to $gig_wanted...\n");
817  
818 # get information about the physical volumes that belong to this group
819 my %volumes;
820 my $fh = $self->scmd_read('sudo pvs --noheadings --units g --nosuffix --separator ,');
821 while (<$fh>) {
822 chomp;
823 s/^\s+//;
824 my ($pv,$vg,undef,undef,$used,$free) = split /,/;
825 next unless $vg eq 'volumes';
826 $volumes{$pv} = $used+$free;
827 }
828 close $fh;
829  
830 # select a volume to resize
831 my $to_resize;
832 for my $pv (sort {$a<=>$b} keys %volumes) {
833 if ($volumes{$pv} + $needed < 1000) {
834 $to_resize = $pv;
835 last;
836 }
837 }
838  
839 # If we found a pv that we can resize sufficiently, then go ahead and do that.
840 # Otherwise, we add a new EBS volume to the volume group.
841 $self->info("Unmounting /opt/gbrowse filesystem...\n");
842 $self->ssh('sudo umount /opt/gbrowse') or die "Couldn't umount";
843  
844 if ($to_resize) {
845 $self->_resize_pv($to_resize,int($volumes{$to_resize}+$needed));
846 } else {
847 $self->_extend_vg('volumes',int($needed));
848 }
849
850 # If we get here, the volume group has been extended, so we can
851 # resize the logical volume and the filesystem
852 $self->info("Resizing logical volume...\n");
853 $self->ssh('sudo lvextend -l +100%FREE /dev/volumes/gbrowse') or die "Couldn't lvresize";
854  
855 $self->info("Checking filesystem prior to resizing...\n");
856 $self->ssh('sudo e2fsck -f -p /dev/volumes/gbrowse') or die "e2fsck failed";
857  
858 $self->info("Resizing filesystem...\n");
859 $self->ssh('sudo resize2fs -p /dev/volumes/gbrowse') or die "Couldn't resize2fs";
860  
861 $self->info("Remounting filesystem...\n");
862 $self->ssh('sudo mount /opt/gbrowse') or die "Couldn't mount";
863  
864 1;
865 }
866  
867 sub terminate {
868 my $self = shift;
869 $self->manager->unregister_server($self) if $self->manager;
870 $self->ec2->terminate_instances($self);
871 }
872  
873 sub start_services {
874 my $self = shift;
875 $self->_start_stop_services('start');
876 }
877  
878 sub stop_services {
879 my $self = shift;
880 $self->_start_stop_services('stop');
881 }
882  
883 sub _start_stop_services {
884 my $self = shift;
885 my $action = shift or die "usage: _start_stop_services(start|stop)";
886 $self->info($action eq 'stop' ? "Stopping services...\n":"Starting services...\n");
887 foreach ('apache2','mysql','postgresql') {
888 $self->ssh("sudo service $_ $action");
889 }
890 }
891  
892 sub snapshot_data_volumes {
893 my $self = shift;
894  
895 my %volumes;
896 my $fh = $self->scmd_read('sudo pvs --noheadings --units g --nosuffix --separator ,');
897 while (<$fh>) {
898 chomp;
899 s/^\s+//;
900 my ($pv,$vg,undef,undef,$used,$free) = split /,/;
901 next unless $vg eq 'volumes';
902 $pv =~ s!/dev/xvd!/dev/sd!;
903 $volumes{$pv}++;
904 }
905 close $fh;
906  
907 my $hostname = hostname();
908 my $timestamp = localtime();
909  
910 # get the EBS volumes for this device
911 my @vols = map {$_->volume} grep {$volumes{$_->deviceName}} $self->blockDeviceMapping;
912 @vols or die "Could not find the EBS volumes to snapshot";
913  
914 $self->info("Unmounting filesystem...\n");
915 $self->ssh('sudo umount /opt/gbrowse') or die "Couldn't umount";
916  
917 $self->info("Creating snapshots...\n");
918 my @snapshots = map {$_->create_snapshot("GBrowse data volume synchronized with $hostname on $timestamp")} @vols;
919 $_->add_tag(Name => "GBrowse data from ${hostname}\@${timestamp}") foreach @snapshots;
920  
921 $self->info("Remounting filesystem...\n");
922 $self->ssh('sudo mount /opt/gbrowse') or die "Couldn't mount";
923  
924 return @snapshots;
925 }
926  
927 sub _extend_vg {
928 my $self = shift;
929 my ($vg,$size) = @_;
930
931 my ($ebs_device,$local_device) = $self->unused_block_device();
932 $self->info("Creating ${size}G EBS volume...\n");
933 my $vol = $self->ec2->create_volume(-availability_zone => $self->placement,
934 -size => $size) or die "Couldn't create EBS volume: ",$self->ec2->error_str;
935 $self->ec2->wait_for_volumes($vol);
936 $vol->current_status eq 'available' or die "EBS volume creation failed: ",$self->ec2->error_str;
937
938 my $a = $vol->attach($self => $ebs_device) or die "EBS volume attachment failed: ",$self->ec2->error_str;
939 $self->ec2->wait_for_attachments($a);
940 $a->current_status eq 'attached' or die "Volume attachment failed: ",$self->ec2->error_str;
941  
942 $a->deleteOnTermination(1);
943  
944 $self->info("Creating LVM2 physical device...\n");
945 $self->ssh("sudo pvcreate $local_device") or die "pvcreate failed";
946  
947 $self->info("Extending 'volumes' volume group...\n");
948 $self->ssh("sudo vgextend volumes $local_device") or die "vgextend failed";
949  
950 1;
951 }
952  
953 sub _resize_pv {
954 my $self = shift;
955 my ($device,$new_size) = @_;
956  
957 # get the EBS volume for this device
958 my @mapping = $self->blockDeviceMapping;
959 (my $ebs_device = $device) =~ s!/dev/xvd!/dev/sd!;
960 my ($mapping) = grep /$ebs_device/,@mapping;
961 $mapping or die "Couldn't find an EBS mapping for $device";
962  
963 my $volume_id = $mapping->volumeId;
964 my $volume = $mapping->volume;
965
966 # disable the volume group
967 $self->ssh('sudo vgchange -an volumes') or die "Couldn't vgchange";
968
969 # detach the underlying device
970 $self->info("Detaching volume $volume...\n");
971 my $a = $volume->detach or die "Couldn't detach";
972 $self->ec2->wait_for_attachments($a);
973  
974 # snapshot it
975 $self->info("Snapshotting volume $volume...\n");
976 my $snapshot = $volume->create_snapshot('created by '.__PACKAGE__) or die "Couldn't snapshot: ",$self->ec2->error_str;
977 $self->ec2->wait_for_snapshots($snapshot);
978 $snapshot->current_status eq 'completed' or die "Snapshot errored: ",$self->ec2->error_str;
979
980 # create a new volume of the appropriate size
981 $self->info("Creating new volume from snapshot...\n");
982 my $zone = $volume->availabilityZone;
983
984 my $new_volume = $self->ec2->create_volume(-availability_zone => $zone,
985 -size => $new_size,
986 -snapshot_id => $snapshot) or die "Couldn't create volume: ",$self->ec2->error_str;
987 $self->ec2->wait_for_volumes($new_volume);
988 $new_volume->current_status eq 'available' or die "Volume error: ",$self->ec2->error_str;
989  
990 $self->info("Attaching new volume...\n");
991 $a = $self->attach_volume($new_volume => $ebs_device);
992 $self->ec2->wait_for_attachments($a);
993 $new_volume->deleteOnTermination(1);
994  
995 # activate
996 $self->info("Resizing physical volume...\n");
997 $self->ssh("sudo pvresize $device") or die "Couldn't pvresize";
998 $self->ssh('sudo vgchange -ay volumes') or die "Couldn't vgchange";
999  
1000 # get rid of the old volume and the new snapshot (which we no longer need)
1001 $self->ec2->delete_volume($volume);
1002 $self->ec2->delete_snapshot($snapshot);
1003  
1004 1;
1005 }
1006  
1007 1;
1008  
1009 =head1 AUTHOR
1010  
1011 Lincoln Stein E<lt>lincoln.stein@gmail.comE<gt>.
1012  
1013 Copyright (c) 2012 Ontario Institute for Cancer Research
1014  
1015 This package and its accompanying libraries is free software; you can
1016 redistribute it and/or modify it under the terms of the GPL (either
1017 version 1, or at your option, any later version) or the Artistic
1018 License 2.0. Refer to LICENSE for the full license text. In addition,
1019 please see DISCLAIMER.txt for disclaimers of warranty.
1020  
1021 =cut
1022