[Bio] / FigKernelPackages / P2P.pm Repository:
ViewVC logotype

Diff of /FigKernelPackages/P2P.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.1, Wed Sep 22 19:29:51 2004 UTC revision 1.27, Tue Jan 11 20:15:59 2005 UTC
# Line 18  Line 18 
18    
19  use FIG_Config;  use FIG_Config;
20    
21    use AnyDBM_File;
22    use Fcntl;
23    
24  use strict;  use strict;
25  use Exporter;  use Exporter;
26  use base qw(Exporter);  use base qw(Exporter);
27    
28    use Time::HiRes qw( usleep ualarm gettimeofday tv_interval );
29    
30  use Data::Dumper;  use Data::Dumper;
31    
32  use vars qw(@EXPORT @EXPORT_OK);  use vars qw(@EXPORT @EXPORT_OK);
# Line 31  Line 36 
36  our $ns_p2p = "http://thefig.info/schemas/p2p_update";  our $ns_p2p = "http://thefig.info/schemas/p2p_update";
37  our $ns_relay = "http://thefig.info/schemas/p2p_relay";  our $ns_relay = "http://thefig.info/schemas/p2p_relay";
38    
39    my $peg_batch_size = 1000;
40    my $anno_batch_size = 1000;
41    my $assign_batch_size = 1000;
42    my $fin_batch_size = 1000;
43    
44    my $log_fh;
45    my $html_fh;
46    
47  =pod  =pod
48    
49  =head1 perform_update($peer)  =head1 perform_update($peer, $last_update, $skip_tough_search, $update_thru, $log_file, $html_file, $assignment_policy))
50    
51  Perform a peer-to-peer update with the given peer. $peer is an instance of  Perform a peer-to-peer update with the given peer. $peer is an instance of
52  P2P::Requestor which can connect to the peer. It is expected that the  P2P::Requestor which can connect to the peer. It is expected that the
# Line 43  Line 56 
56  This code executes the high-level protocol, maintaining state between  This code executes the high-level protocol, maintaining state between
57  calls to the peer to exchange the actual information.  calls to the peer to exchange the actual information.
58    
59        $last_update: Search for updates since this time.
60        $skip_tough_search: Do not use the time-consuming $fig->tough_search method as a last resort for peg mapping.
61        $update_thru: Search for updates until this time. Undef means to search for all since $last_update.
62        $log_file: Write logging information to this file.
63        $html_file: Write a HTML summary to this file.
64        $assignment_policy: If a list reference, contains the list of users from which we will accept assignments. If a code ref, a predicate that is passed ($peg, $timestamp, $author, $function) and returns true if the assignment should be made.
65    
66  =cut  =cut
67    
68  sub perform_update  sub perform_update
69  {  {
70      my($fig, $peer, $last_update) = @_;      my($fig, $peer, $last_update, $skip_tough_search, $update_thru, $log_file, $html_file,
71           $assignment_policy) = @_;
72    
73        my $allow_assignment;
74    
75        $log_file = "/dev/null" unless $log_file ne "";
76        open($log_fh, ">>$log_file") or die "Cannot open logfile $log_file: $!\n";
77        $log_fh->autoflush(1);
78    
79        $html_file = "/dev/null" unless $html_file ne "";
80        open($html_fh, ">$html_file") or die "Cannot open htmlfile $html_file: $!\n";
81        $html_fh->autoflush(1);
82    
83        if (!defined($assignment_policy))
84        {
85            $allow_assignment = sub { 1;};
86        }
87        elsif (ref($assignment_policy) eq "CODE")
88        {
89            $allow_assignment = $assignment_policy;
90        }
91        elsif (ref($assignment_policy) eq "ARRAY")
92        {
93            my $ahash = {};
94            map { $ahash->{$_}++; } @$assignment_policy;
95            $allow_assignment = sub {
96                return $ahash->{$_[2]};
97            };
98        }
99        elsif (ref($assignment_policy) eq "HASH")
100        {
101            $allow_assignment = sub {
102                return $assignment_policy->{$_[2]};
103            };
104        }
105        else
106        {
107            print $log_fh "Invalid assignment policy $assignment_policy\n";
108            die "Invalid assignment policy $assignment_policy\n";
109        }
110    
111        my $now = localtime();
112        my $last_str = localtime($last_update);
113        print $html_fh <<END;
114    <h1>P2P Update at $now</h1>
115    Peer URL $peer->{url}<br>
116    Update from: $last_str<br>
117    END
118    
119        print $log_fh "Beginning P2P update at $now\n";
120        print $log_fh "  Peer URL: $peer->{url}\n";
121        print $log_fh "  Update from: $last_str\n";
122        print $log_fh "\n";
123    
124      my $ret = $peer->request_update($last_update);      my $ret = $peer->request_update($last_update, $update_thru);
125    
126      if (!$ret or ref($ret) ne "ARRAY")      if (!$ret or ref($ret) ne "ARRAY")
127      {      {
128          die "perform_update: request_updated failed\n";          die "perform_update: request_update failed\n";
129      }      }
130    
131      my($session, $target_release, $num_annos, $num_pegs, $num_genomes,      my($session, $target_release, $num_assignments, $num_annos, $num_pegs, $num_genomes,
132         $target_time, $compatible) = @$ret;         $target_time, $compatible) = @$ret;
133    
134      print "perform_update: session=$session target=$target_release num_annos=$num_annos\n";      print "perform_update: session=$session target=@$target_release num_annos=$num_annos\n";
135      print "                num_pegs=$num_pegs num_genomes=$num_genomes target_time=$target_time compat=$compatible\n";      print "                num_pegs=$num_pegs num_genomes=$num_genomes target_time=$target_time compat=$compatible\n";
136    
137        my @my_release = $fig->get_release_info();
138    
139        print $log_fh "Session id = $session\n";
140        print $log_fh "Target release information: \n\t", join("\n\t", @$target_release), "\n";
141        print $log_fh "My release information: \n\t", join("\n\t", @my_release), "\n";
142        print $log_fh "$num_annos annotations\n";
143        print $log_fh "$num_assignments assignments\n";
144        print $log_fh "$num_pegs pegs\n";
145    
146        print $html_fh "Session id = $session<br>\n";
147        print $html_fh "Target release information: <br>\n\t", join("<br>\n\t", @$target_release), "<br>\n";
148        print $html_fh "My release information: <br>\n\t", join("<br>\n\t", @my_release), "<br>\n";
149        print $html_fh "$num_annos annotations<br>\n";
150        print $html_fh "$num_assignments assignments<br>\n";
151        print $html_fh "$num_pegs pegs<br>\n";
152    
153        #
154        # We now know the data release for our peer.
155        #
156        # Open up the peg translation cache database (a AnyDBM_File) tied
157        # to %peg_cache. We needn't worry about keeping it in a directory
158        # based on our current release, as it the cache directory is kept *in*
159        # the current data release directory.
160        #
161    
162        my $cache_handle;
163        my %peg_cache;
164        if ($target_release->[1] ne "")
165        {
166            my $cache_file = "pegcache.$target_release->[1].db";
167            my $cache_dir = "$FIG_Config::data/P2PQueue";
168            $fig->verify_dir($cache_dir);
169    
170            $cache_handle = tie(%peg_cache, "AnyDBM_File", "$cache_dir/$cache_file",
171                                O_CREAT | O_RDWR, 0666);
172            $cache_handle or warn "Could not tie peg_cache to $cache_dir/$cache_file: $!\n";
173        }
174    
175        #
176        # peg_mapping is the local mapping from remote->local peg. This might
177        # be replacable by peg_cache from above.
178        #
179        my %peg_mapping;
180    
181    
182      #      #
183      # We have  the information now to begin the update process. Retrieve the pegs.      # We have  the information now to begin the update process. Retrieve the pegs.
184      #      #
185    
186      $ret = $peer->get_pegs($session, 0, $num_pegs);      _compute_peg_mapping($fig, $peer, $session, $num_pegs, \%peg_mapping, \%peg_cache, $cache_handle,
187                             $skip_tough_search);
188    
189        eval { $cache_handle->sync();};
190        untie %peg_cache;
191    
192        #
193        # Create a list of locally-mapped annotations on a per-genome
194        # basis.
195        #
196    
197        my %genome_annos;
198    
199        #
200        # %genome_assignments is a hash mapping from genome to a hashref
201        # that maps  peg to function (since assignments are unique).
202        #
203        # (Hm. Unless two remote pegs map to the same local peg; unclear what to do
204        # then. Punt for now).
205        #
206        my %genome_assignments;
207    
208        #
209        # Retrieve the annotations, and generate a list of mapped annotations.
210        #
211    
212        for (my $anno_start = 0; $anno_start < $num_annos; $anno_start += $anno_batch_size)
213        {
214            my $anno_req_len = $num_annos - $anno_start;
215            $anno_req_len = $anno_batch_size if $anno_req_len > $anno_batch_size;
216    
217            print "Retrieve $anno_req_len annos at $anno_start\n";
218            print $log_fh "Retrieve $anno_req_len annos at $anno_start\n";
219    
220            my $annos = $peer->get_annotations($session, $anno_start, $anno_req_len);
221    
222            for my $anno (@$annos)
223            {
224                my($his_id, $ts, $author, $anno) = @$anno;
225    
226                my $my_id = $peg_mapping{$his_id};
227                next unless $my_id;
228    
229                my $genome = $fig->genome_of($my_id);
230    
231                push(@{$genome_annos{$genome}}, [$my_id, $ts, $author, $anno]);
232            }
233        }
234    
235        #
236        # Do the same for the assignments
237        #
238    
239        # print Dumper($assignments);
240    
241    
242        for (my $assign_start = 0; $assign_start < $num_assignments; $assign_start += $assign_batch_size)
243        {
244            my $assign_req_len = $num_assignments - $assign_start;
245            $assign_req_len = $assign_batch_size if $assign_req_len > $assign_batch_size;
246    
247            print "Retrieve $assign_req_len assigns at $assign_start\n";
248            print $log_fh "Retrieve $assign_req_len assigns at $assign_start\n";
249    
250            my $assignments = $peer->get_assignments($session, $assign_start, $assign_req_len);
251    
252            for my $assign (@$assignments)
253            {
254                my($his_id, $ts, $author, $func) = @$assign;
255    
256                my $my_id = $peg_mapping{$his_id};
257                next unless $my_id;
258    
259                my $genome = $fig->genome_of($my_id);
260    
261                $genome_assignments{$genome}->{$my_id} =  [$my_id, $ts, $author, $func];
262            }
263        }
264    
265        # print Dumper(\%genome_annos);
266    
267        #
268        # Now install annotations.
269        #
270    
271        for my $genome (keys(%genome_annos))
272        {
273            #
274            # Plan:  Apply the merge_annotations.pl logic. Read the annotations
275            # from the per-org annotations file, add the new ones here, sort, and remove duplicates.
276            # Write the results to the annotations file.
277            #
278            # When we are all done, rerun the index_annotations script.
279            #
280            # Why not do that incrementally? Partly because the annotation_seeks table doesn't
281            # have a column for the genome id, so a removal of old data would require a
282            # string-match query; since a complete reindex of the annotations is pretty
283            # fast (60 sec on a G4 laptop on a firewire disk), it's not clear whether the incremental
284            # update would actually be a win.
285            #
286    
287            my @annos = @{$genome_annos{$genome}};
288            my $assignments = $genome_assignments{$genome};
289            #
290            # %assignment_annos is a hash from peg to the list
291            # of annotations for that peg.
292            #
293            my %assignment_annos;
294    
295            my $dir = "$FIG_Config::organisms/$genome";
296            my $anno_file = "$dir/annotations";
297            my $anno_bak = "$dir/annotations." . time;
298    
299            my $new_count = @annos;
300    
301            #
302            # Rename the annotations file to a new name based on the current time.
303            #
304    
305            my $gs = $fig->genus_species($genome);
306            print $html_fh "<h1>Updates for $genome ($gs)</h1>\n";
307    
308            if (-f $anno_file)
309            {
310                rename($anno_file, $anno_bak) or die "Cannot rename $anno_file to $anno_bak: $!";
311                print $log_fh "Moved annotations file $anno_file to backup $anno_bak\n";
312            }
313    
314            if (open(my $fh, "<$anno_bak"))
315            {
316                #
317                # While we are scanning here, we look for the latest local assignment
318                # for any peg for which we are installing an assignment.
319                #
320                local($/) = "\n//\n";
321    
322                my($chunk, $peg, $ts, $author, $anno);
323    
324                while (defined($chunk = <$fh>))
325                {
326                    chomp $chunk;
327                    ($peg, $ts, $author, $anno) = split(/\n/, $chunk, 4);
328    
329                    if ($peg =~ /^fig\|/ and $ts =~ /^\d+$/)
330                    {
331                        #
332                        # The last field marks this as an "old" annotation, so we don't
333                        # log its installation later.
334                        #
335                        my $ent = [$peg, $ts, $author, $anno, 1];
336                        push(@annos, $ent);
337    
338                        if (defined($assignments->{$peg}))
339                        {
340                            #
341                            # We have an incoming assignment for this peg.
342                            # Don't parse anything yet, but push the annotation
343                            # on a list so we can sort by date.
344                            #
345                            push(@{$assignment_annos{$peg}}, $ent);
346                        }
347                    }
348                }
349                close($fh);
350            }
351    
352            #
353            # Determine if we are going to install an assignment.
354            #
355    
356            my $cgi_url = &FIG::cgi_url();
357            print $html_fh "<h2>Assignments made</h2>\n";
358            print $html_fh "<table border=\"1\">\n";
359            print $html_fh "<tr><th>PEG</th><th>Old assignment</th><th>New assignment</th><tr>\n";
360    
361            for my $peg (keys %$assignments)
362            {
363                my(undef, $ts, $author, $func) = @{$assignments->{$peg}};
364    
365                #
366                # Sort the existing annotations for this peg by date.
367                #
368                # Recall that this list has entries [$peg, $timestamp, $author, $anno, $old_flag]
369                #
370    
371                my @eannos;
372                if (ref($assignment_annos{$peg}))
373                {
374                    @eannos = sort { $b->[1] <=> $a->[1] } @{$assignment_annos{$peg}};
375                }
376                else
377                {
378                    #
379                    # No assignment annotations found.
380                    #
381                    @eannos = ();
382                }
383    
384                # print "Assignment annos for $peg: ", Dumper(\@eannos);
385    
386                #
387                # Filter out just the master assignments that are newer than
388                # the one we are contemplating putting in place.
389                #
390    
391                my @cand = grep {
392                    ($_->[1] > $ts) and ($_->[3] =~ /Set master function to/)
393                    } @eannos;
394    
395                if (@cand > 0)
396                {
397                    #
398                    # Here is were some policy needs to be put in place --
399                    # we have a more recent annotation on the current system.
400                    #
401                    # For now, we will not install an assignment if there is any
402                    # newer assignment in place.
403                    #
404    
405                    warn "Skipping assignment for $peg $func due to more recent assignment $cand[0]->[3]\n";
406                    print $log_fh "Skipping assignment for $peg $func due to more recent assignment $cand[0]->[3]\n";
407                }
408                else
409                {
410                    #
411                    # Nothing is blocking us. While we are testing, just slam this assignment in.
412                    #
413    
414                    my $old = $fig->function_of($peg, 'master');
415    
416                    if ($old ne $func and &$allow_assignment($peg, $ts, $author, $func))
417                    {
418                        my $l = "$cgi_url/protein.cgi?prot=$peg";
419                        print $html_fh "<tr><td><a href=\"$l\">$peg</a></td><td>$old</td><td>$func</td></tr>\n";
420    
421                        print "Assign $peg $func\n";
422                        print $log_fh "Assign $peg $func\n";
423                        print $log_fh "   was $old\n";
424                        $fig->assign_function($peg, 'master', $func);
425    
426                    }
427                }
428            }
429    
430            print $html_fh "</table>\n";
431    
432            print $html_fh "<h2>Annotations added</h2>\n";
433            print $html_fh "<table border=\"1\">\n";
434            print $html_fh "<tr><th>PEG</th><th>Time</th><th>Author</th><th>Annotation</th></tr>\n";
435    
436            open(my $outfh, ">$anno_file") or die "Cannot open new annotation file $anno_file: $!\n";
437    
438            my $last;
439            my @sorted = sort { ($a->[0] cmp $b->[0]) or ($a->[1] <=> $b->[1]) } @annos;
440            my $inst = 0;
441            my $dup = 0;
442            foreach my $ann (@sorted)
443            {
444                my $txt = join("\n", @$ann);
445                #
446                # Drop the trailing \n if there is one; we  will add it back when we print and
447                # want to ensure the file format remains sane.
448                #
449                chomp $txt;
450                if ($txt ne $last)
451                {
452                    my $peg = $ann->[0];
453                    my $l = "$cgi_url/protein.cgi?prot=$peg";
454                    if (!$ann->[4])
455                    {
456                        print $html_fh "<tr>" . join("\n", map { "<td>$_</td>" }
457                                                     "<a href=\"$l\">$peg</a>",
458                                                     scalar(localtime($ann->[1])), $ann->[2], $ann->[3])
459                            . "</tr>\n";
460                    }
461    
462                    print $outfh "$txt\n//\n";
463                    $last = $txt;
464                    # print "Inst $ann->[0] $ann->[1] $ann->[2]\n";
465                    $inst++;
466                }
467                else
468                {
469                    # print "Dup $ann->[0] $ann->[1] $ann->[2]\n";
470                    $dup++;
471                }
472            }
473            print $html_fh "</table>\n";
474            close($outfh);
475            chmod(0666, $anno_file) or warn "Cannot chmod 0666 $anno_file: $!\n";
476            print "Wrote $anno_file. $new_count new annos, $inst installed, $dup duplicates\n";
477            print $log_fh "Wrote $anno_file. $new_count new annos, $inst installed, $dup duplicates\n";
478        }
479        close($html_fh);
480    }
481    
482    #
483    # Compute the peg mapping for a session.
484    #
485    # $fig          Active FIG instance
486    # $peer         P2P peer for this session.
487    # $session      P2P session ID
488    # $peg_mapping  Hash ref for the remote -> local PEG mapping
489    # $peg_cache    Hash ref for the persistent remote -> local PEG mapping cache db.
490    # $cache_handle AnyDBM_File handle corresponding to $peg_cache.
491    #
492    sub _compute_peg_mapping
493    {
494        my($fig, $peer, $session, $num_pegs, $peg_mapping, $peg_cache, $cache_handle, $skip_tough_search) = @_;
495    
496        #
497        # genome_map is a hash mapping from target genome id to a list of
498        # pegs on the target. This is used to construct a finalize_pegs request after
499        # the first phase of peg mapping.
500        #
501    
502        my %genome_map;
503    
504        #
505        # target_genome_info is a hash mapping from target genome
506        # identifier to the target-side information on the genome -
507        # number of contigs, number of nucleotides, checksum.
508        #
509        # We accumulate it here across possibly multiple batches of
510        # peg retrievals in order to create a single  finalization
511        # list.
512        #
513    
514        my %target_genome_info;
515    
516        #
517        # For very large transfers, we need to batch the peg processing.
518        #
519    
520        for (my $peg_start = 0; $peg_start < $num_pegs; $peg_start += $peg_batch_size)
521        {
522            my $peg_req_len = $num_pegs - $peg_start;
523            $peg_req_len = $peg_batch_size if $peg_req_len > $peg_batch_size;
524    
525            print "Getting $peg_req_len pegs at $peg_start\n";
526            print $log_fh "Getting $peg_req_len pegs at $peg_start\n";
527            my $ret = $peer->get_pegs($session, $peg_start, $peg_req_len);
528    
529      if (!$ret or ref($ret) ne "ARRAY")      if (!$ret or ref($ret) ne "ARRAY")
530      {      {
# Line 75  Line 533 
533    
534      my($peg_list, $genome_list) = @$ret;      my($peg_list, $genome_list) = @$ret;
535    
536            for my $gent (@$genome_list)
537            {
538                $target_genome_info{$gent->[0]} = $gent;
539            }
540    
541            _compute_peg_mapping_batch($fig, $peer, $session, $peg_mapping, $peg_cache, $cache_handle,
542                                       $peg_list, \%genome_map);
543        }
544    
545        #
546        # We have finished first pass. Now go over the per-genome mappings that need to be made.
547        #
548        # $genome_map{$genome_id} is a list of pegs that reside on that genome.
549        # The pegs and genome id are both target-based identifiers.
550        #
551        # %target_genome_info defines the list of genome information we have on the remote
552        # side.
553        #
554        # We build a request to be passed to finalize_pegs. Each entry in the request is either
555        # ['peg_genome', $peg] which means that we have a genome that corresponds to the
556        # genome the peg is in. We can attempt to map via contig locations.
557        #
558        # If that is not the case,  we pass a request entry of ['peg_unknown', $peg]
559        # which will result in the sequence data being returned.
560        #
561    
562        my @finalize_req = ();
563    
564        #
565        # local_genome maps a target peg identifier to the local genome id it translates to.
566        #
567        my %local_genome;
568    
569        for my $genome (keys(%target_genome_info))
570        {
571            my($tg, $n_contigs, $n_nucs, $cksum) = @{$target_genome_info{$genome}};
572    
573            $tg eq $genome or die "Invalid entry in target_genome_info for $genome => $tg, $n_contigs, $n_nucs, $cksum";
574    
575            #
576            # Don't bother unless we have any pegs to look up.
577            #
578            next unless defined($genome_map{$genome});
579    
580            #
581            # Determine if we have a local genome installed that matches precisely the
582            # genome on the target side.
583            #
584            my $my_genome = $fig->find_genome_by_content($genome, $n_contigs, $n_nucs, $cksum);
585    
586            my $pegs = $genome_map{$genome};
587    
588            if ($my_genome)
589            {
590                #
591                # We do have such a local genome. Generate a peg_genome request to
592                # get the location information from the target side.
593                #
594                # Also remember the local genome mapping for this peg.
595                #
596    
597                print "$genome mapped to $my_genome\n";
598                print $log_fh "$genome mapped to $my_genome\n";
599                for my $peg (@$pegs)
600                {
601                    push(@finalize_req, ['peg_genome', $peg]);
602                    $local_genome{$peg} = $my_genome;
603                }
604    
605            }
606            else
607            {
608                #
609                # We don't have such a genome. We need to retrieve the
610                # sequence data in order to finish mapping.
611                #
612                push(@finalize_req, map { ['peg_unknown', $_] } @$pegs);
613            }
614        }
615    
616        #
617        # We've built our finalization request. Handle it (possibly with batching here too).
618        #
619    
620        _process_finalization_request($fig, $peer, $session, $peg_mapping, $peg_cache, $cache_handle,
621                                     \%local_genome, \@finalize_req, $skip_tough_search);
622    
623    }
624    
625    #
626    # Process one batch of PEGs.
627    #
628    # Same args as _compute_peg_mapping, with the addition of:
629    #
630    #       $peg_list       List of pegs to be processed
631    #       $genome_map     Hash maintaining list of genomes with their pegs.
632    #       $target_genome_info     Hash maintaining overall list of target-side genome information.
633    #
634    sub _compute_peg_mapping_batch
635    {
636        my($fig, $peer, $session, $peg_mapping, $peg_cache, $cache_handle,
637           $peg_list, $genome_map, $target_genome_info) = @_;
638    
639        #
640        # Walk the list of pegs as returned from get_pegs() and determine what has to
641        # be done.
642        #
643        # If the entry is ['peg', $peg], we can use the peg ID as is.
644        #
645        # If the entry is ['peg_info', $peg, $alias_list, $genome], the peg
646        # has the given aliases, and is in the given genome.
647        #
648        for my $peg_info (@$peg_list)
649        {
650            my($key, $peg, @rest) = @$peg_info;
651    
652            if ($key eq 'peg')
653            {
654                #
655                # Peg id is directly usable.
656                #
657                $peg_mapping->{$peg} = $peg;
658            }
659            elsif ($key eq 'peg_info')
660            {
661                #
662                # Peg id not directly usable. See if we have it in the cache.
663                #
664    
665                if ((my $cached = $peg_cache->{$peg}) ne "")
666                {
667                    #
668                    # Cool, we've cached the result. Use it.
669                    #
670    
671                    $peg_mapping->{$peg} = $cached;
672                    # warn "Found cached mapping $peg => $cached\n";
673                    next;
674                }
675    
676                #
677                # It is not cached. Attempt to resolve by means of alias IDs.
678                #
679    
680                my($alias_list, $genome_id) = @rest;
681    
682                for my $alias (@$alias_list)
683                {
684                    my $mapped = $fig->by_alias($alias);
685                    if ($mapped)
686                    {
687                        print "$peg maps to $mapped via $alias\n";
688                        print $log_fh "$peg maps to $mapped via $alias\n";
689                        $peg_mapping->{$peg}= $mapped;
690                        $peg_cache->{$peg} = $mapped;
691                        last;
692                    }
693                }
694    
695                #
696                # If we weren't able to resolve by ID,
697                # add to %genome_map as a PEG that will need
698                # to be resolved by means of contig location.
699                #
700    
701                if (!defined($peg_mapping->{$peg}))
702                {
703                    push(@{$genome_map->{$genome_id}}, $peg);
704                    print "$peg did not map on first pass\n";
705                    print $log_fh "$peg did not map on first pass\n";
706                }
707            }
708        }
709    
710        #
711        # Flush the cache to write out any computed mappings.
712        #
713        eval { $cache_handle->sync();};
714    
715    }
716    
717    sub _process_finalization_request
718    {
719        my($fig, $peer, $session, $peg_mapping, $peg_cache, $cache_handle,
720           $local_genome, $finalize_req, $skip_tough_search) = @_;
721    
722        #
723        # Immediately return unless there's something to do.
724        #
725        return unless ref($finalize_req) and @$finalize_req > 0;
726    
727        while (@$finalize_req > 0)
728        {
729            my @req = splice(@$finalize_req, 0, $fin_batch_size);
730    
731            print "Invoking finalize_pegs on ", int(@req), " pegs\n";
732            print $log_fh "Invoking finalize_pegs on ", int(@req), " pegs\n";
733            my $ret = $peer->finalize_pegs($session, \@req);
734    
735            if (!$ret or ref($ret) ne "ARRAY")
736            {
737                die "perform_update: finalize_pegs failed\n";
738            }
739    
740            #
741            # The return is a list of either location entries or
742            # sequence data. Attempt to finish up the mapping.
743            #
744    
745            my(%sought, %sought_seq);
746    
747    
748            my $dbh = $fig->db_handle();
749            for my $entry (@$ret)
750            {
751                my($what, $peg, @rest) = @$entry;
752    
753                if ($what eq "peg_loc")
754                {
755                    my($strand, $start, $end, $cksum, $seq) = @rest;
756    
757                    #
758                    # We have a contig location. Try to find a matching contig
759                    # here, and see if it maps to something.
760                    #
761    
762                    my $my_genome = $local_genome->{$peg};
763                    my $local_contig = $fig->find_contig_with_checksum($my_genome, $cksum);
764                    if ($local_contig)
765                    {
766      #      #
767      # Walk the peg-list to and generate @pegs_to_finalize.                      # Now look up the local peg. We match on the end location; depending on the strand
768                        # the feature is on, we want to look at either minloc or maxloc.
769      #      #
770    
771      my(%peg_mapping, %genome_map );                      my($start_loc, $end_loc);
772    
773      for my $peg_info (@$peg_list)                      if ($strand eq '-')
774      {      {
775          my($key, $peg, @rest) = @$peg_info;                          $start_loc = 'maxloc';
776                            $end_loc = 'minloc';
777                        }
778                        else
779                        {
780                            $start_loc = 'minloc';
781                            $end_loc = 'maxloc';
782                        }
783    
784          if ($key eq 'peg')                      my $res = $dbh->SQL(qq!SELECT id, $start_loc from features
785                                               WHERE $end_loc = $end and genome = '$my_genome' and
786                                               contig = '$local_contig'
787                                            !);
788    
789                        if ($res and @$res > 0)
790                        {
791                            my $id;
792                            if (@$res == 1)
793          {          {
794              #              #
795              # Peg id is directly usable.                              # Found a unique mapping.
796              #              #
797                                $id = $res->[0]->[0];
798          }          }
799          elsif ($key eq 'peg_info')                          else
800          {          {
801              #              #
802              # Peg id not directly usable.                              # Multiple mappings found. See if one matches the
803                                # start location. If it doesn't, pick the one that
804                                # is closest in length.
805              #              #
806    
807              my($alias_list, $genome_id) = @rest;                              my @lens;
808    
809              for my $alias (@$alias_list)                              for my $res_ent (@$res)
810              {              {
811                  my $mapped = $fig->by_alias($alias);                                  my($rid, $rloc) = @$res_ent;
812                  if ($mapped && $peg !~ /5$/)  
813                                    push(@lens, [$rid, abs($rloc - $end - ($start - $end))]);
814                                    warn "Matching $rid $rloc to $start\n";
815                                    if ($rloc == $start)
816                  {                  {
817                      print "$peg maps to $mapped via $alias\n";                                      $id = $rid;
818                      $peg_mapping{$peg}= $mapped;                                      warn "Matched $rid\n";
819                      last;                      last;
820                  }                  }
821              }              }
822    
823              #                              if (!$id)
824              # If we didn't succeed in mapping by alias,                              {
825              # stash this in the list of pegs to be mapped by                                  my @slens = sort { $a->[1] <=> $b->[1]} @lens;
826              # genome.                                  my $len;
827              #                                  ($id, $len) = @{$slens[0]};
828                                    warn "No unique match found, picking closest match $id (len=$len)\n";
829                                }
830                            }
831    
832              if (!defined($peg_mapping{$peg}))                          $peg_mapping->{$peg} = $id;
833                            $peg_cache->{$peg} = $id;
834                            print "Mapped $peg to $id via contigs\n";
835                        }
836                        else
837              {              {
838                  push(@{$genome_map{$genome_id}}, $peg);                          print "failed: $peg  $my_genome and contig $local_contig start=$start end=$end strand=$strand\n";
839                            print $log_fh "failed: $peg  $my_genome and contig $local_contig start=$start end=$end strand=$strand\n";
840                            print $html_fh "Contig match failed: $peg $my_genome contig $local_contig start $start end $end strand $strand<br>\n";
841                            $sought{$peg}++;
842                            $sought_seq{$peg} = $seq;
843              }              }
844          }          }
845                    else
846                    {
847                        print "Mapping failed for $my_genome checksum $cksum\n";
848                        print $log_fh "Mapping failed for $my_genome checksum $cksum\n";
849                        print $html_fh "Mapping failed for $my_genome checksum $cksum<br>\n";
850                        $sought{$peg}++;
851                        $sought_seq{$peg} = $seq;
852                    }
853                }
854                elsif ($what eq "peg_seq")
855                {
856                    my($seq) = @rest;
857    
858                    $sought{$peg}++;
859                    $sought_seq{$peg} = $seq;
860                }
861      }      }
862    
863      #      #
864      # finished first pass. Now go over the per-genome mappings that need to be made.          # Now see if we need to do a tough search.
865      #      #
866    
867      for my $genome_info (@$genome_list)          if (keys(%sought) > 0 and !$skip_tough_search)
868      {      {
869          my($genome, $n_contigs, $n_nucs, $cksum) = @$genome_info;              my %trans;
   
         next unless $genome_map{$genome};  
870    
871          my $my_genome = $fig->find_genome_by_content($genome, $n_contigs, $n_nucs, $cksum);              print "Starting tough search\n";
872                print $log_fh "Starting tough search\n";
873    
874          if ($my_genome)              $fig->tough_search(undef, \%sought_seq, \%trans, \%sought);
875                print "Tough search translated: \n";
876                print $log_fh "Tough search translated: \n";
877                while (my($tpeg, $ttrans) = each(%trans))
878          {          {
879              #                  print "  $tpeg -> $ttrans\n";
880              # Found a match.                  print $log_fh "  $tpeg -> $ttrans\n";
881              #                  $peg_mapping->{$tpeg} = $ttrans;
882              print "Genome $genome maps to $my_genome locally\n";                  $peg_cache->{$tpeg} = $ttrans;
883                }
884          }          }
885      }      }
886  }  }
   
887    
888  #############  #############
889  #  #
# Line 166  Line 904 
904  {  {
905      my($class, $url) = @_;      my($class, $url) = @_;
906    
907      my $proxy = SOAP::Lite->uri($P2P::ns_relay)->proxy($url);      my $creds = [];
908    
909        my $proxy = SOAP::Lite->uri($P2P::ns_relay)->proxy([$url,
910                                                            credentials => $creds]);
911    
912      my $self = {      my $self = {
913          url => $url,          url => $url,
# Line 239  Line 980 
980          # element in the body of the message.          # element in the body of the message.
981          #          #
982          my $ns = $reply->namespaceuriof('/Envelope/Body/[1]');          my $ns = $reply->namespaceuriof('/Envelope/Body/[1]');
983          print "Reply ns=$ns want $P2P::ns_relay\n";          # print "Reply ns=$ns want $P2P::ns_relay\n";
984    
985          if ($ns eq $P2P::ns_relay)          if ($ns eq $P2P::ns_relay)
986          {          {
987              my $val = $reply->result;              my $val = $reply->result;
988              print "got val=", Dumper($val);              # print "got val=", Dumper($val);
989              if ($val->[0] eq 'deferred')              if ($val->[0] eq 'deferred')
990              {              {
991                  #                  #
# Line 286  Line 1027 
1027  use strict;  use strict;
1028    
1029  use Data::Dumper;  use Data::Dumper;
1030    use Time::HiRes qw( usleep ualarm gettimeofday tv_interval );
1031    
1032  use SOAP::Lite;  use SOAP::Lite;
1033    
1034    #use SOAP::Lite +trace => [qw(transport dispatch result debug)];
1035  use P2P;  use P2P;
1036    
1037  #  #
# Line 297  Line 1041 
1041    
1042  sub new  sub new
1043  {  {
1044      my($class, $fig, $url, $peer_id, $relay) = @_;      my($class, $fig, $url, $peer_id, $relay, $credentials) = @_;
1045    
1046        $credentials = [] unless ref($credentials);
1047    
1048      my $proxy = SOAP::Lite->uri($ns_p2p)->proxy($url);      my $proxy = SOAP::Lite->uri($ns_p2p)->proxy($url, timeout => 3600);
1049    
1050        for my $cred (@$credentials)
1051        {
1052            $proxy->transport->credentials(@$cred);
1053        }
1054    
1055      my $self = {      my $self = {
1056          fig => $fig,          fig => $fig,
# Line 325  Line 1076 
1076    
1077  sub request_update  sub request_update
1078  {  {
1079      my($self, $last_update) = @_;      my($self, $last_update, $update_thru) = @_;
1080    
1081      my $rel = $self->{fig}->get_release_info();      my $rel = [$self->{fig}->get_release_info()];
1082    
1083      if (!defined($last_update))      if (!defined($last_update))
1084      {      {
1085          $last_update = $self->{fig}->get_peer_last_update($self->{peer_id});          $last_update = $self->{fig}->get_peer_last_update($self->{peer_id});
1086      }      }
1087    
1088      my $reply = $self->{proxy}->request_update($rel, $last_update);      print "Requesting update via $self->{proxy}\n";
1089        my $reply = $self->{proxy}->request_update($rel, $last_update, $update_thru);
1090        # print "Got reply ", Dumper($reply);
1091    
1092      if ($self->{relay})      if ($self->{relay})
1093      {      {
# Line 364  Line 1117 
1117      return $self->call("get_pegs", $session_id, $start, $length);      return $self->call("get_pegs", $session_id, $start, $length);
1118  }  }
1119    
1120    sub finalize_pegs
1121    {
1122        my($self, $session_id, $request) = @_;
1123    
1124        return $self->call("finalize_pegs", $session_id, $request);
1125    }
1126    
1127    sub get_annotations
1128    {
1129        my($self, $session_id, $start, $length) = @_;
1130    
1131        return $self->call("get_annotations", $session_id, $start, $length);
1132    }
1133    
1134    sub get_assignments
1135    {
1136        my($self, $session_id, $start, $length) = @_;
1137    
1138        return $self->call("get_assignments", $session_id, $start, $length);
1139    }
1140    
1141  sub call  sub call
1142  {  {
1143      my($self, $func, @args) = @_;      my($self, $func, @args) = @_;
1144    
1145        my $t0 = [gettimeofday()];
1146        print "Calling $func\n";
1147      my $reply = $self->{proxy}->$func(@args);      my $reply = $self->{proxy}->$func(@args);
1148        my $t1 = [gettimeofday()];
1149    
1150        my $elap = tv_interval($t0, $t1);
1151        print "Call to $func took $elap\n";
1152    
1153      if ($self->{relay})      if ($self->{relay})
1154      {      {
# Line 406  Line 1186 
1186    
1187  sub request_update  sub request_update
1188  {  {
1189      my($class, $his_release, $last_update)= @_;      my($class, $his_release, $last_update, $update_thru)= @_;
1190    
1191      #      #
1192      # Verify input.      # Verify input.
# Line 417  Line 1197 
1197          die "request_update: last_update must be a number (not '$last_update')\n";          die "request_update: last_update must be a number (not '$last_update')\n";
1198      }      }
1199    
1200        if ($update_thru eq "")
1201        {
1202            $update_thru = time + 10000;
1203        }
1204    
1205      #      #
1206      # Create a new session id and a spool directory to use for storage      # Create a new session id and a spool directory to use for storage
1207      # of information about it. This can go in the tempdir since it is      # of information about it. This can go in the tempdir since it is
# Line 424  Line 1209 
1209      #      #
1210    
1211      &FIG::verify_dir("$FIG_Config::temp/p2p_spool");      &FIG::verify_dir("$FIG_Config::temp/p2p_spool");
1212      #my $spool_dir = tempdir(DIR  => "$FIG_Config::temp/p2p_spool");      my $spool_dir = tempdir(DIR  => "$FIG_Config::temp/p2p_spool");
1213    
1214      my $spool_dir = "$FIG_Config::temp/p2p_spool/test";      #my $spool_dir = "$FIG_Config::temp/p2p_spool/test";
1215      &FIG::verify_dir($spool_dir);      &FIG::verify_dir($spool_dir);
1216    
1217      my $session_id = basename($spool_dir);      my $session_id = basename($spool_dir);
# Line 444  Line 1229 
1229    
1230      my %pegs;      my %pegs;
1231    
1232        #
1233        # We keep track of usernames that have been seen, so that
1234        # we can both update our local user database and
1235        # we can report them to our peer.
1236        #
1237    
1238        my %users;
1239    
1240      my $num_annos = 0;      my $num_annos = 0;
1241      my $num_genomes = 0;      my $num_genomes = 0;
1242      my $num_pegs = 0;      my $num_pegs = 0;
1243        my $num_assignments = 0;
1244    
1245      my $anno_fh;      my $anno_fh;
1246      open($anno_fh, ">$spool_dir/annos");      open($anno_fh, ">$spool_dir/annos");
# Line 457  Line 1251 
1251      my $genome_fh;      my $genome_fh;
1252      open($genome_fh, ">$spool_dir/genomes");      open($genome_fh, ">$spool_dir/genomes");
1253    
1254        my $assign_fh;
1255        open($assign_fh, ">$spool_dir/assignments");
1256    
1257        #
1258        # We originally used a query to get the PEGs that needed to have annotations
1259        # sent. Unfortunately, this performed very poorly due to all of the resultant
1260        # seeking around in the annotations files.
1261        #
1262        # The code below just runs through all of the anno files looking for annos.
1263        #
1264        # A better way to do this would be to do a query to retrieve the genome id's for
1265        # genomes that have updates. The problem here is that the annotation_seeks
1266        # table doesn't have an explicit genome field.
1267        #
1268        # Surprisingly, to me anyway, the following query appers to run quickly, in both
1269        # postgres and mysql:
1270        #
1271        # SELECT distinct(substring(fid from 5 for position('.peg.' in fid) - 5))
1272        # FROM annotation_seeks
1273        # WHERE dateof > some-date.
1274        #
1275        # The output of that can be parsed to get the genome id and just those
1276        # annotations files searched.
1277        #
1278    
1279      for my $genome (@$all_genomes)      for my $genome (@$all_genomes)
1280      {      {
1281          my $num_annos_for_genome = 0;          my $num_annos_for_genome = 0;
1282            my %assignment;
1283    
1284          my $genome_dir = "$FIG_Config::organisms/$genome";          my $genome_dir = "$FIG_Config::organisms/$genome";
1285          next unless -d $genome_dir;          next unless -d $genome_dir;
# Line 476  Line 1296 
1296    
1297                  if ((($fid, $anno_time, $who, $anno_text) =                  if ((($fid, $anno_time, $who, $anno_text) =
1298                       ($ann =~ /^(fig\|\d+\.\d+\.peg\.\d+)\n(\d+)\n(\S+)\n(.*\S)/s)) and                       ($ann =~ /^(fig\|\d+\.\d+\.peg\.\d+)\n(\d+)\n(\S+)\n(.*\S)/s)) and
1299                      $anno_time > $last_update)                      $anno_time > $last_update and
1300                        $anno_time < $update_thru)
1301    
1302                  {                  {
1303                      #                      #
1304                        # Update users list.
1305                        #
1306    
1307                        $users{$who}++;
1308    
1309                        #
1310                      # Look up aliases if we haven't seen this fid before.                      # Look up aliases if we haven't seen this fid before.
1311                      #                      #
1312    
# Line 497  Line 1324 
1324    
1325                      $num_annos_for_genome++;                      $num_annos_for_genome++;
1326                      $num_annos++;                      $num_annos++;
1327    
1328                        #
1329                        # While we're here, see if this is an assignment. We check in the
1330                        # %assignment hash, which is keyed on fid, to see if we already
1331                        # saw an assignment for this fid. If we have, we keep this one only if
1332                        # the assignment time on it is later than the one we saw already.
1333                        #
1334                        # We are only looking at master assignments for now. We will need
1335                        # to return to this issue and reexamine it, but in order to move
1336                        # forward I am only matching master assignments.
1337                        #
1338    
1339                        if ($anno_text =~ /Set master function to\n(\S[^\n]+\S)/)
1340                        {
1341                            my $func = $1;
1342    
1343                            my $other = $assignment{$fid};
1344    
1345                            #
1346                            # If we haven't seen an assignment for this fid,
1347                            # or if it the other assignment has a timestamp that
1348                            # is earlier than this one, set the assignment.
1349                            #
1350    
1351                            if (!defined($other) or
1352                                ($other->[1] < $anno_time))
1353                            {
1354                                $assignment{$fid} = [$fid, $anno_time, $who, $func];
1355                            }
1356                        }
1357                  }                  }
1358              }              }
1359              close($afh);              close($afh);
1360    
1361                #
1362                # Write out the assignments that remain.
1363                #
1364    
1365                for my $fid (sort keys(%assignment))
1366                {
1367                    print $assign_fh join("\t", @{$assignment{$fid}}), "\n";
1368                    $num_assignments++;
1369                }
1370          }          }
1371    
1372    
1373          #          #
1374          # Determine genome information if we have annotations for this one.          # Determine genome information if we have annotations for this one.
1375          #          #
# Line 533  Line 1401 
1401      close($anno_fh);      close($anno_fh);
1402      close($peg_fh);      close($peg_fh);
1403      close($genome_fh);      close($genome_fh);
1404        close($assign_fh);
1405    
1406      print "Pegs: $num_pegs\n";      print "Pegs: $num_pegs\n";
1407      print "Genomes: $num_genomes\n";      print "Genomes: $num_genomes\n";
# Line 542  Line 1411 
1411      # Check compatibility.      # Check compatibility.
1412      #      #
1413    
1414      my $my_release = $fig->get_release_info();      my $my_release = [$fig->get_release_info()];
1415      my $compatible = (defined($my_release) && ($my_release == $his_release)) ? 1 : 0;  
1416        #
1417        # Release id is $my_release->[1].
1418        #
1419    
1420        my $compatible;
1421        if ($my_release->[1] ne "" and $his_release->[1] ne "")
1422        {
1423            #
1424            # Both releases must be defined for them to be compatible.
1425            #
1426            # At some point we need to consider the derived-release issue.
1427            #
1428    
1429            $compatible = $my_release->[1] eq $his_release->[1];
1430        }
1431        else
1432        {
1433            $compatible = 0;
1434        }
1435    
1436      open(my $fh, ">$spool_dir/INFO");      open(my $fh, ">$spool_dir/INFO");
1437      print $fh "requestor_release\t$his_release\n";      print $fh "requestor_release\t$his_release\n";
1438      print $fh "last_update\t$last_update\n";      print $fh "last_update\t$last_update\n";
1439        print $fh "update_thru\t$update_thru\n";
1440      print $fh "cur_update\t$now\n";      print $fh "cur_update\t$now\n";
1441      print $fh "target_release\t$my_release\n";      print $fh "target_release\t$my_release\n";
1442      print $fh "compatible\t$compatible\n";      print $fh "compatible\t$compatible\n";
1443      print $fh "num_pegs\t$num_pegs\n";      print $fh "num_pegs\t$num_pegs\n";
1444      print $fh "num_genomes\t$num_genomes\n";      print $fh "num_genomes\t$num_genomes\n";
1445      print $fh "num_annos\t$num_annos\n";      print $fh "num_annos\t$num_annos\n";
1446        print $fh "num_assignments\t$num_assignments\n";
1447      close($fh);      close($fh);
1448    
1449      return [$session_id, $my_release, $num_annos, $num_pegs, $num_genomes, $now, $compatible];      #
1450        # Construct list of users, and pdate local user database.
1451        #
1452    
1453        my @users = keys(%users);
1454        # $fig->ensure_users(\@users);
1455    
1456        return [$session_id, $my_release, $num_assignments, $num_annos, $num_pegs, $num_genomes,
1457                $now, $compatible, \@users];
1458  }  }
1459    
1460    
# Line 669  Line 1567 
1567    
1568      return [$peg_output, $genome_output];      return [$peg_output, $genome_output];
1569  }  }
1570    
1571    sub finalize_pegs
1572    {
1573        my($self, $session, $request) = @_;
1574        my($out);
1575    
1576        my $fig = new FIG;
1577    
1578        #
1579        # Walk the request handling appropriately. This is fairly easy, as it
1580        # is just a matter of pulling either sequence or location/contig data.
1581        #
1582    
1583        for my $item (@$request)
1584        {
1585            my($what, $peg) = @$item;
1586    
1587            if ($what eq "peg_genome")
1588            {
1589                #
1590                # Return the location and contig checksum for this peg.
1591                #
1592                # We also include the sequence in case the contig mapping doesn't work.
1593                #
1594    
1595                my $loc = $fig->feature_location($peg);
1596                my $contig = $fig->contig_of($loc);
1597                my $cksum = $fig->contig_checksum($fig->genome_of($peg), $contig);
1598                my $seq = $fig->get_translation($peg);
1599    
1600                push(@$out, ['peg_loc', $peg,
1601                            $fig->strand_of($peg),
1602                            $fig->beg_of($loc), $fig->end_of($loc),
1603                            $cksum, $seq]);
1604    
1605            }
1606            elsif ($what eq "peg_unknown")
1607            {
1608                my $seq = $fig->get_translation($peg);
1609                push(@$out, ['peg_seq', $peg, $seq]);
1610            }
1611        }
1612        return $out;
1613    }
1614    
1615    
1616    sub get_annotations
1617    {
1618        my($self, $session_id, $start, $len) = @_;
1619    
1620        #
1621        # This is now easy; just run thru the saved annotations and return.
1622        #
1623    
1624        my(%session_info);
1625    
1626        my $spool_dir = "$FIG_Config::temp/p2p_spool/$session_id";
1627    
1628        -d $spool_dir or die "Invalid session id $session_id";
1629    
1630        #
1631        # Read in the cached information for this session.
1632        #
1633    
1634        open(my $info_fh, "<$spool_dir/INFO") or die "Cannot open INFO file: $!";
1635        while (<$info_fh>)
1636        {
1637            chomp;
1638            my($var, $val) = split(/\t/, $_, 2);
1639            $session_info{$var} = $val;
1640        }
1641        close($info_fh);
1642    
1643        #
1644        # Sanity check start and length.
1645        #
1646    
1647        if ($start < 0 or $start >= $session_info{num_annos})
1648        {
1649            die "Invalid start position $start";
1650        }
1651    
1652        if ($len < 0 or ($start + $len - 1) >= $session_info{num_annos})
1653        {
1654            die "Invalid length $len";
1655        }
1656    
1657        #
1658        # Open file, spin to the starting line, then start reading.
1659        #
1660    
1661        open(my $anno_fh, "<$spool_dir/annos") or die "Cannot open annos file: $!";
1662    
1663        my $anno_output = [];
1664    
1665        my $anno_num = 0;
1666    
1667        local $/ = "//\n";
1668        while (<$anno_fh>)
1669        {
1670            next if ($anno_num < $start);
1671    
1672            last if ($anno_num > ($start + $len));
1673    
1674            chomp;
1675    
1676            my($id, $date, $author, $anno) = split(/\n/, $_, 4);
1677    
1678            push(@$anno_output, [$id, $date, $author, $anno]);
1679        }
1680        continue
1681        {
1682            $anno_num++;
1683        }
1684    
1685        return $anno_output;
1686    }
1687    
1688    sub get_assignments
1689    {
1690        my($self, $session_id, $start, $len) = @_;
1691    
1692        #
1693        # This is now easy; just run thru the saved assignments and return.
1694        #
1695    
1696        my(%session_info);
1697    
1698        my $spool_dir = "$FIG_Config::temp/p2p_spool/$session_id";
1699    
1700        -d $spool_dir or die "Invalid session id $session_id";
1701    
1702        #
1703        # Read in the cached information for this session.
1704        #
1705    
1706        open(my $info_fh, "<$spool_dir/INFO") or die "Cannot open INFO file: $!";
1707        while (<$info_fh>)
1708        {
1709            chomp;
1710            my($var, $val) = split(/\t/, $_, 2);
1711            $session_info{$var} = $val;
1712        }
1713        close($info_fh);
1714    
1715        #
1716        # Sanity check start and length.
1717        #
1718    
1719        if ($start < 0 or $start >= $session_info{num_assignments})
1720        {
1721            die "Invalid start position $start";
1722        }
1723    
1724        if ($len < 0 or ($start + $len - 1) >= $session_info{num_assignments})
1725        {
1726            die "Invalid length $len";
1727        }
1728    
1729        #
1730        # Open file, spin to the starting line, then start reading.
1731        #
1732    
1733        open(my $assign_fh, "<$spool_dir/assignments") or die "Cannot open assignments file: $!";
1734    
1735        my $assign_output = [];
1736    
1737        my $assign_num = 0;
1738    
1739        while (<$assign_fh>)
1740        {
1741            next if ($assign_num < $start);
1742    
1743            last if ($assign_num > ($start + $len));
1744    
1745            chomp;
1746    
1747            my($id, $date, $author, $func) = split(/\t/, $_, 4);
1748    
1749            push(@$assign_output, [$id, $date, $author, $func]);
1750        }
1751        continue
1752        {
1753            $assign_num++;
1754        }
1755    
1756        return $assign_output;
1757    }
1758    
1759    1;

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.27

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3