blib/lib/Bio/Phylo/CIPRES.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package Bio::Phylo::CIPRES;
2 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use XML::Twig;
Subroutine BEGIN: called CC=1 SCAR=2.6
7 use Data::Dumper;
8 use LWP::UserAgent;
9 use YAML qw(LoadFile);
10 use Bio::Phylo::Util::Logger ':simple';
11 use Bio::Phylo::Util::Exceptions 'throw';
12  
13 =head1 NAME
14  
15 Bio::Phylo::CIPRES - Reusable components for CIPRES REST API access
16  
17 =head1 SYNOPSIS
18  
19 my %result = Bio::Phylo::CIPRES->new(
20 'infile' => 'infile.fasta', # input data file
21 'tool' => 'MAFFT_XSEDE', # tool to run
22 'param' => { 'vparam.runtime_' => 7.5 }, # extra parameters, e.g. max runtime
23 'outfile' => { 'output.mafft' => 'out.fa' }, # name of output data to fetch
24 'yml' => 'config.yml', # client credentials
25 )->run;
26
27 while( my ( $name, $data ) = each %result ) {
28
29 # write data to output file
30 my $outfile = "${name}.fasta";
31 open my $fh, '>', $outfile or die $!;
32 print $fh $data;
33 }
34  
35 =head1 DESCRIPTION
36  
37 The CyberInfrastructure for Phylogenetic RESearch (L<CIPRES|http://www.phylo.org>) is a
38 portal that provides access to phylogenetic analyses tools that can be run on the XSEDE
39 HPC infrastructure. The portal has a web browser (point and click) interface, but also
40 a web service interface that can be interacted with using RESTful commands. The basic
41 workflow is as follows:
42  
43 =over
44  
45 =item * B<Launch a job>
46 This is done by issuing an HTTP POST request that includes: 1) HTTP authentication (i.e.
47 a user name and password that is registered to the realm), 2) uploading input data, 3)
48 configuration options for the job. The result value is an XML document that reports the
49 status. If all goes well, this will report that the job was launched successfully, and it
50 gives a URL to visit to check up on the status.
51  
52 =item * B<Check job status>
53 The job URL is visited periodically (at most once every 60 seconds, as per CIPRES policy).
54 This is done using an authenticated GET request where the return value is an XML document
55 that reports whether the job has finished. Once it is finished, the document will include
56 a link to another document that lists the output data, which will be named (e.g.
57 C<output.mafft>) and which will be identifiable by a URL from whence the data can be
58 retrieved.
59  
60 =item * B<Get results>
61 Upon completion the results are fetched from their respective URLs. Under simple cases
62 this will be just a single file (e.g. an alignment), but there could be multiple file
63 types, as well as output from STDERR and STDOUT and various job status files that the
64 server generated internally.
65  
66 =back
67  
68 This module hides the complexity of this interaction, so that entire analyses can be
69 run using only the commands shown in the synopsis section. The general idea is that
70 you can reuse this functionality in other modules and scripts. It is also does the heavy
71 lifting for the L<cipresrun> executable that allows you to run analyses from terminal
72 interfaces.
73  
74 =cut
75  
76 # global constants
77 our $AUTOLOAD;
78 use version; our $VERSION = qv("v0.2.0");
79 my $REALM = "Cipres Authentication";
80 my $PORT = 443;
81  
82 =head1 METHODS
83  
84 =head2 new()
85  
86 The constructor takes the arguments as shown in the SYNOPSIS section. The arguments are
87 a direct translation of the named arguments (not option flags) that are passed on the
88 command line to the L<cipresrun> program. The value of the C<outfile> argument, and that
89 of the C<param> argument, is both a hash reference.
90  
91 =cut
92  
93 sub new {
94 my $class = shift;
95 my @fields = qw[infile tool param outfile url user pass cipres_appkey];
96 my $self = bless { map { $_ => undef } @fields }, $class;
97 my %args = @_;
98 while( my ( $property, $value ) = each %args ) {
99 $self->$property($value);
100 }
101 return $self;
102 }
103  
104 =head2 run()
105  
106 Runs the entire analysis using the configuration as provided to the constructor. Returns
107 key value pairs where each key is an C<outfile> and each file is the data as text.
108  
109 =cut
110  
111 sub run {
112 my $self = shift;
113 my $url = $self->launch_job;
114 while(1) {
115 sleep(60);
116 my $status = $self->check_status($url);
117 if ( $status->{'completed'} eq 'true' ) {
118 $self->get_results( $status->{'outfiles'} );
119 return $url;
120 }
121 }
122 }
123  
124 =head2 launch_job()
125  
126 Is called by C<run()>. Launches the analysis and returns the status URL at which progress
127 can be inspected.
128  
129 =cut
130  
131 sub launch_job {
132 my $self = shift;
133 my $ua = $self->ua;
134 my $url = $self->url;
135 my $load = $self->payload;
136 my @head = $self->headers(1);
137 my $res = $ua->post( $url . '/job/' . $self->user, $load, @head );
138 if ( $res->is_success ) {
139
140 # run submission, parse result
141 my $status_url;
142 my $result = $res->decoded_content;
143 DEBUG $result;
144 XML::Twig->new(
145 'twig_handlers' => {
146 'jobstatus/selfUri/url' => sub { $status_url = $_->text }
147 }
148 )->parse($result);
149 INFO "Job launched at $status_url";
150 return $status_url;
151 }
152 else {
153 throw 'NetworkError' => $res->status_line;
154 }
155 }
156  
157 =head2 check_status()
158  
159 Is called by C<run()>. Consults the status URL. Returns a hash reference whose values
160 specify whether the job is done, and if so, where the results can be fetched.
161  
162 =cut
163  
164 sub check_status {
165 my ( $self, $url ) = @_;
166 INFO "Going to check status for $url";
167 my $ua = $self->ua;
168 my @head = $self->headers(0);
169 my $res = $ua->get( $url, @head );
170 if ( $res->is_success ) {
171
172 # post request, fetch result
173 my ( $status, $outfiles );
174 my $result = $res->decoded_content;
175 DEBUG $result;
176 XML::Twig->new(
177 'twig_handlers' => {
178 'jobstatus/resultsUri/url' => sub { $outfiles = $_->text },
179 'jobstatus/terminalStage' => sub { $status = $_->text }
180 }
181 )->parse($result);
182 my $time = localtime();
183 INFO "[$time] completed: $status";
184 return { 'completed' => $status, 'outfiles' => $outfiles };
185 }
186 else {
187 throw 'NetworkError' => $res->status_line;
188 }
189 }
190  
191 =head2 get_results()
192  
193 Is called by C<run()>. Returns the named result data as a hash.
194  
195 =cut
196  
197 sub get_results {
198 my ( $self, $url ) = @_;
199 my %out = %{ $self->outfile };
200 my $ua = $self->ua;
201 my @head = $self->headers(0);
202 my $res = $ua->get( $url, @head );
203 my %out_url;
204 if ( $res->is_success ) {
205 my $result = $res->decoded_content;
206 DEBUG $result;
207 XML::Twig->new(
208 'twig_handlers' => {
209 'results/jobfiles/jobfile' => sub {
210 my $node = $_;
211 my $name = $node->findvalue('filename');
212 if ( $out{ $name } ) {
213 $out_url{ $name } = $node->findvalue('downloadUri/url');
214 }
215 DEBUG $node->toString;
216 }
217 }
218 )->parse($result);
219 for my $name ( keys %out ) {
220 my $location = $out_url{ $name };
221 $res = $ua->get( $location, @head );
222 if ( $res->is_success ) {
223 open my $fh, '>', $out{ $name } or die $!;
224 print $fh $res->decoded_content;
225 }
226 else {
227 throw 'NetworkError' => $res->status_line;
228 }
229 }
230 }
231 else {
232 throw 'NetworkError' => $res->status_line;
233 }
234 }
235  
236 =head2 yml()
237  
238 Given the location the config.yml file, populates properties of the object with the
239 right parameter values to authenticate the client with the CIPRES server.
240  
241 =cut
242  
243 sub yml {
244 my ( $self, $yml ) = @_;
245 INFO "Reading YAML file $yml";
246 my $info = LoadFile($yml);
247 DEBUG "Parsed " . Dumper( $info );
248 $self->user( $info->{'CRA_USER'} );
249 $self->pass( $info->{'PASSWORD'} );
250 $self->url( $info->{'URL'} );
251 $self->cipres_appkey( $info->{'KEY'} );
252 }
253  
254 =head2 ua()
255  
256 Instantiates an authenticated L<LWP::UserAgent> object.
257  
258 =cut
259  
260 sub ua {
261 my $self = shift;
262 my $host = URI->new( $self->url )->host();
263 my $user = $self->user;
264 my $pass = $self->pass;
265 my $ua = LWP::UserAgent->new;
266 DEBUG "Instantiating UserAgent $host:$PORT / $REALM / $user:****";
267 $ua->ssl_opts( 'verify_hostname' => 0 );
268 $ua->credentials(
269 $host . ':' . $PORT,
270 $REALM,
271 $user => $pass
272 );
273 return $ua;
274 }
275  
276 =head2 payload()
277  
278 Constructs the HTTP POST payload for launching jobs. Returns an array reference of
279 key/value pairs.
280  
281 =cut
282  
283 sub payload {
284 my $self = shift;
285 DEBUG "Composing payload for ".$self->tool." with infile ".$self->infile;
286 my $load = [
287 'tool' => $self->tool,
288 'input.infile_' => [ $self->infile ],
289 'metadata.statusEmail' => 'true',
290 %{ $self->param }
291 ];
292 DEBUG Dumper($load);
293 return $load;
294 }
295  
296 =head2 headers()
297  
298 Constructs the HTTP headers to identify the client app and, optionally, to tell the
299 server that multipart/form-data is being attached as a payload.
300  
301 =cut
302  
303 sub headers {
304 my ( $self, $form ) = @_;
305 if ( $form ) {
306 DEBUG "Composing POST / form-data headers";
307 return (
308 'Content_Type' => 'form-data',
309 'cipres-appkey' => $self->cipres_appkey,
310 );
311 }
312 else {
313 DEBUG "Composing GET headers";
314 return ( 'cipres-appkey' => $self->cipres_appkey );
315 }
316 }
317  
318 =head2 clean_job()
319  
320 Cleans up the job on the server that is identified by the provided input URL (i.e. the
321 status URL, which is the return value of the run() method).
322  
323 =cut
324  
325 sub clean_job {
326 my ( $self, $url ) = @_;
327 my $ua = $self->ua;
328 my @head = $self->headers(0);
329 INFO "Going to clean job $url";
330 $ua->delete( $url, @head );
331 }
332  
333 sub AUTOLOAD {
334 my ( $self, $arg ) = @_;
335 my $property = $AUTOLOAD;
336 $property =~ s/.*://;
337 if ( exists $self->{$property} ) {
338 if ( $arg ) {
339 $self->{$property} = $arg;
340 return $self;
341 }
342 else {
343 return $self->{$property};
344 }
345 }
346 else {
347 my $template = 'Can\'t locate object method "%s" via package "%s"';
348 croak sprintf $template, $property, __PACKAGE__;
349 }
350 }
351  
352 sub DESTROY {
353 # maybe kill and delete process on server?
354 }
355  
356 =head1 SEE ALSO
357  
358 Also consult the documentation for L<cipresrun>, which shows the usage of this module
359 from the command line.
360  
361 =cut
362  
363 1;
↑ Summary