]> git.donarmstrong.com Git - debbugs.git/blob - bin/debbugs-loadsql
skip undefined source versions
[debbugs.git] / bin / debbugs-loadsql
1 #! /usr/bin/perl
2 # debbugs-loadsql is part of debbugs, and is released
3 # under the terms of the GPL version 2, or any later version, at your
4 # option. See the file README and COPYING for more information.
5 # Copyright 2012 by Don Armstrong <don@donarmstrong.com>.
6
7
8 use warnings;
9 use strict;
10
11 use Getopt::Long qw(:config no_ignore_case);
12 use Pod::Usage;
13
14 =head1 NAME
15
16 debbugs-loadsql -- load debbugs sql database
17
18 =head1 SYNOPSIS
19
20 debbugs-loadsql [options] [subcommand]
21
22  Subcommands:
23   bugs help versions configuration
24   suites logs packages debinfo
25  Options:
26   --quick, -q only load changed things
27   --progress Show progress bar
28   --service, -s service name
29   --sysconfdir, -c postgresql service config dir
30   --spool-dir debbugs spool directory
31   --debug, -d debugging level (Default 0)
32   --help, -h display this help
33   --man, -m display manual
34
35 =head1 SUBCOMMANDS
36
37 =head2 help
38
39 Display this manual
40
41 =head2 bugs
42
43 Add bugs (subject, number, etc) to the database
44
45    --preload create all bugs first, then add information
46
47 =head2 versions
48
49 Add version descendant information (which version is based on which version) to
50 the database
51
52 =head2 maintainers
53
54 Add source maintainers to the BTS
55
56 =head2 configuration
57
58 Add debbugs configuration information (tags, severity, etc)
59
60 =head2 suites
61
62 Add suite information from ftp distribution
63
64   --ftpdists location of FTP mirror
65
66 =head2 logs
67
68 Add bug logs
69
70 =head2 packages
71
72 Add package information from the ftp archive
73
74   --ftpdists location of FTP mirror
75   --suites Suite to operate on
76
77 =head2 debinfo
78
79 Add package information from a debinfo file
80
81   --null -0 names of debinfo files are null separated
82
83 =head1 OPTIONS
84
85 =over
86
87 =item B<--quick, -q>
88
89 Only load changed bugs
90
91 =item B<--progress>
92
93 Show progress bar (requires Term::ProgressBar)
94
95 =item B<--service,-s>
96
97 Postgreql service to use; defaults to debbugs
98
99 =item B<--sysconfdir,-c>
100
101 System configuration directory to use; if not set, defaults to the
102 postgresql default. [Operates by setting PGSYSCONFDIR]
103
104 =item B<--spool-dir>
105
106 Debbugs spool directory; defaults to the value configured in the
107 debbugs configuration file.
108
109 =item B<--verbose>
110
111 Output more information about what is happening. Probably not useful
112 if you also set --progress.
113
114 =item B<--debug, -d>
115
116 Debug verbosity.
117
118 =item B<--help, -h>
119
120 Display brief useage information.
121
122 =item B<--man, -m>
123
124 Display this manual.
125
126 =back
127
128
129 =cut
130
131
132 use vars qw($DEBUG);
133
134 use Debbugs::Common (qw(checkpid lockpid get_hashname getparsedaddrs getbugcomponent make_list getsourcemaintainers),
135                      qw(hash_slice open_compressed_file),);
136 use Debbugs::Config qw(:config);
137 use Debbugs::Status qw(read_bug split_status_fields);
138 use Debbugs::Log;
139 use Debbugs::DB;
140 use Debbugs::DB::Load qw(:load_bug :load_package :load_suite);
141 use DateTime;
142 use File::stat;
143 use File::Basename;
144 use File::Spec;
145 use IO::Dir;
146 use IO::File;
147 use IO::Uncompress::AnyUncompress;
148 use Encode qw(decode_utf8);
149 use List::MoreUtils qw(natatime);
150
151 my %options =
152     (debug           => 0,
153      help            => 0,
154      man             => 0,
155      verbose         => 0,
156      quiet           => 0,
157      quick           => 0,
158      service         => $config{debbugs_db},
159      progress        => 0,
160     );
161
162 Getopt::Long::Configure('pass_through');
163 GetOptions(\%options,
164            'quick|q',
165            'service|s=s',
166            'sysconfdir|c=s',
167            'progress!',
168            'spool_dir|spool-dir=s',
169            'verbose|v+',
170            'quiet+',
171            'debug|d+','help|h|?','man|m');
172 Getopt::Long::Configure('default');
173
174 pod2usage() if $options{help};
175 pod2usage({verbose=>2}) if $options{man};
176
177 $DEBUG = $options{debug};
178
179 my %subcommands =
180     ('bugs' => {function => \&add_bugs,
181                 arguments => {'preload' => 0},
182                },
183      'versions' => {function => \&add_versions,
184                    },
185      'debinfo' => {function => \&add_debinfo,
186                    arguments => {'0|null' => 0},
187                   },
188      'maintainers' => {function => \&add_maintainers,
189                       },
190      'configuration' => {function => \&add_configuration,
191                         },
192      'suites' => {function => \&add_suite,
193                   arguments => {'ftpdists=s' => 1,
194                                },
195                  },
196      'logs' => {function => \&add_logs,
197                },
198      'packages' => {function => \&add_packages,
199                     arguments => {'ftpdists=s' => 1,
200                                   'suites=s@' => 0,
201                                  },
202                    },
203      'help' => {function => sub {pod2usage({verbose => 2});}}
204     );
205
206 my @USAGE_ERRORS;
207 $options{verbose} = $options{verbose} - $options{quiet};
208
209 if ($options{progress}) {
210     eval "use Term::ProgressBar";
211     push @USAGE_ERRORS, "You asked for a progress bar, but Term::ProgressBar isn't installed" if $@;
212 }
213
214
215 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
216
217 if (exists $options{sysconfdir}) {
218     if (not defined $options{sysconfdir} or not length $options{sysconfdir}) {
219         delete $ENV{PGSYSCONFDIR};
220     } else {
221         $ENV{PGSYSCONFDIR} = $options{sysconfdir};
222     }
223 }
224
225 if (exists $options{spool_dir} and defined $options{spool_dir}) {
226     $config{spool_dir} = $options{spool_dir};
227 }
228
229 my $prog_bar;
230 if ($options{progress}) {
231     $prog_bar = eval "Term::ProgressBar->new({count => 1,ETA=>q(linear)})";
232     warn "Unable to initialize progress bar: $@" if not $prog_bar;
233 }
234
235
236 my ($subcommand) = shift @ARGV;
237 if (not defined $subcommand) {
238     $subcommand = 'help';
239     print STDERR "You must provide a subcommand; displaying usage.\n";
240     pod2usage();
241 } elsif (not exists $subcommands{$subcommand}) {
242     print STDERR "$subcommand is not a valid subcommand; displaying usage.\n";
243     pod2usage();
244 }
245
246 binmode(STDOUT,':encoding(UTF-8)');
247 binmode(STDERR,':encoding(UTF-8)');
248
249 my $opts =
250     handle_subcommand_arguments(\@ARGV,$subcommands{$subcommand}{arguments});
251 $subcommands{$subcommand}{function}->(\%options,$opts,$prog_bar,\%config,\@ARGV);
252
253 sub add_bugs {
254     my ($options,$opts,$p,$config,$argv) = @_;
255     chdir($config->{spool_dir}) or
256         die "chdir $config->{spool_dir} failed: $!";
257
258     my $verbose = $options->{debug};
259
260     my $initialdir = "db-h";
261
262     if (defined $argv->[0] and $argv->[0] eq "archive") {
263         $initialdir = "archive";
264     }
265     my $s = db_connect($options);
266
267
268     my $time = 0;
269     my $start_time = time;
270     my %tags;
271     my %severities;
272     my %queue;
273
274     if ($opts->{preload}) {
275         my @bugs;
276         walk_bugs([(@{$argv}?@{$argv} : $initialdir)],
277                   undef,
278                   'summary',
279                   undef,
280                   sub {
281                     push @bugs,@_;
282                   },
283                   10000
284                  );
285         $s->resultset('Bug')->quick_insert_bugs(@bugs);
286     }
287     walk_bugs([(@{$argv}?@{$argv} : $initialdir)],
288               $p,
289               'summary',
290               $verbose,
291               sub {
292                 my @bugs = @_;
293                 my @bugs_to_update;
294                 if ($options{quick}) {
295                   for my $bug (@bugs) {
296                     my $stat = stat(getbugcomponent($bug,'summary',$initialdir));
297                     if (not defined $stat) {
298                       print STDERR "Unable to stat $bug $!\n";
299                       next;
300                     }
301                     my $rs = $s->resultset('Bug')->search({id=>$bug})->single();
302                     next if defined $rs and $stat->mtime <= $rs->last_modified()->epoch();
303                     push @bugs_to_update, $bug;
304                   }
305                 } else {
306                   @bugs_to_update = @bugs;
307                 }
308                 eval {
309                   $s->txn_do(sub {
310                                for my $bug (@bugs_to_update) {
311                                  load_bug(db => $s,
312                                           bug => $bug,
313                                           tags => \%tags,
314                                           severities => \%severities,
315                                           queue => \%queue);
316                                }
317                              });
318                 };
319                 if ($@) {
320                   die "failure while trying to load bug: $@";
321                 }
322               },
323               50
324              );
325     handle_load_bug_queue(db => $s,
326                           queue => \%queue);
327 }
328
329 sub add_versions {
330     my ($options,$opts,$p,$config,$argv) = @_;
331
332     my $s = db_connect($options);
333
334     my @files = @{$argv};
335     $p->target(scalar @files) if $p;
336     for my $file (@files) {
337         my $fh = IO::File->new($file,'r') or
338             die "Unable to open $file for reading: $!";
339         my @versions;
340         my %src_pkgs;
341         while (<$fh>) {
342             chomp;
343             next unless length $_;
344             if (/(\w[-+0-9a-z.]+) \(([^\(\) \t]+)\)/) {
345                 push @versions, [$1,$2];
346             }
347         }
348         close($fh);
349         my $ancestor_sv;
350         for my $i (reverse 0..($#versions)) {
351             my $sp;
352             if (not defined $src_pkgs{$versions[$i][0]}) {
353                 $src_pkgs{$versions[$i][0]} =
354                     $s->resultset('SrcPkg')->
355                     get_src_pkg_id($versions[$i][0]);
356             }
357             $sp = $src_pkgs{$versions[$i][0]};
358             # There's probably something wrong if the source package
359             # doesn't exist, but we'll skip it for now
360             last if not defined $sp;
361             my $sv = $s->resultset('SrcVer')->find({src_pkg=>$sp,
362                                                     ver => $versions[$i][1],
363                                                    });
364             last if not defined $sv;
365             if (defined $ancestor_sv and defined $sv and not defined $sv->based_on()) {
366                 $sv->update({based_on => $ancestor_sv})
367             }
368             $ancestor_sv = $sv->id();
369         }
370         $p->update() if $p;
371     }
372     $p->remove() if $p;
373 }
374
375 sub add_debinfo {
376     my ($options,$opts,$p,$config,$argv) = @_;
377
378     my @files = @{$argv};
379     if (not @files) {
380        {
381            local $/ = "\n";
382            local $/ = "\0" if $opts->{0};
383            while (<STDIN>) {
384                s/\n$// unless $opts->{0};
385                s/\0$// if $opts->{0};
386                push @files, $_;
387            }
388        }
389     }
390     return unless @files;
391     my $s = db_connect($options);
392     $p->target(scalar @files) if $p;
393     my $it = natatime 100, @files;
394     while (my @v = $it->()) {
395         my %cache;
396         my @debinfos;
397         for my $file (@v) {
398             my $fh = IO::File->new($file,'r') or
399                 die "Unable to open $file for reading: $!";
400             my $f_stat = stat($file);
401             my $ct_date = DateTime->from_epoch(epoch => $f_stat->ctime);
402             while (<$fh>) {
403                 chomp;
404                 next unless length $_;
405                 my ($binname, $binver, $binarch, $srcname, $srcver) = split;
406                 # if $srcver is not defined, this is probably a broken
407                 # .debinfo file [they were causing #686106, see commit
408                 # 49c85ab8 in dak.] Basically, $binarch didn't get put into
409                 # the file, so we'll fudge it from the filename.
410                 if (not defined $srcver) {
411                     ($srcname,$srcver) = ($binarch,$srcname);
412                     ($binarch) = $file =~ /_([^\.]+)\.debinfo/;
413                 }
414                 if (not defined $srcver) {
415                     print STDERR "malformed debinfo (no srcver): $file\n";
416                     next;
417                 }
418                 push @debinfos,
419                     [$binname,$binver,$binarch,$srcname,$srcver,$ct_date];
420             }
421         }
422         $s->txn_do(
423             sub {
424                 for my $di (@debinfos) {
425                     Debbugs::DB::Load::load_debinfo($s,@{$di}[0..5],\%cache);
426                 }
427             });
428         $p->update($p->last_update()+@v) if $p;
429     }
430     $p->remove() if $p;
431 }
432
433 sub add_maintainers {
434     my ($options,$opts,$p,$config,$argv) = @_;
435
436     my $s = db_connect($options);
437     my $maintainers = getsourcemaintainers();
438     $p->target(2) if $p;
439     ## get all of the maintainers, and add the missing ones
440     my $maints = $s->resultset('Maintainer')->
441         get_maintainers(values %{$maintainers});
442     $p->update();
443     my @svs = $s->resultset('SrcVer')->
444         search({maintainer => undef
445                },
446               {join => 'src_pkg',
447                group_by => 'me.src_pkg, src_pkg.pkg',
448                result_class => 'DBIx::Class::ResultClass::HashRefInflator',
449                columns => [qw(me.src_pkg src_pkg.pkg)],
450               }
451               )->all();
452     $p->target(2+@svs) if $p;
453     $p->update() if $p;
454     for my $sv (@svs) {
455         if (exists $maintainers->{$sv->{src_pkg}{pkg}}) {
456             my $pkg = $sv->{src_pkg}{pkg};
457             my $maint = $maints->
458                {$maintainers->{$pkg}};
459             $s->txn_do(sub {$s->resultset('SrcVer')->
460                                 search({maintainer => undef,
461                                         'src_pkg.pkg' => $pkg
462                                        },
463                                       {join => 'src_pkg'}
464                                       )->update({maintainer => $maint})
465                                   });
466         }
467         $p->update() if $p;
468     }
469     $p->remove() if $p;
470 }
471
472 sub add_configuration {
473     my ($options,$opts,$p,$config,$argv) = @_;
474
475     my $s = db_connect($options);
476
477     # tags
478     # add all tags
479     my %tags;
480     for my $tag (@{$config{tags}}) {
481         $tags{$tag} = 1;
482         $s->resultset('Tag')->find_or_create({tag => $tag});
483     }
484     # mark obsolete tags
485     for my $tag ($s->resultset('Tag')->search_rs()->all()) {
486         next if exists $tags{$tag->tag};
487         $tag->obsolete(1);
488         $tag->update;
489     }
490
491     # severities
492     my %sev_names;
493     my $order = -1;
494     for my $sev_name (($config{default_severity},@{$config{severity_list}})) {
495         # add all severitites
496         my $sev = $s->resultset('Severity')->find_or_create({severity => $sev_name});
497         # mark strong severities
498         if (grep {$_ eq $sev_name} @{$config{strong_severities}}) {
499             $sev->strong(1);
500         }
501         $sev->ordering($order);
502         $sev->update();
503         $order++;
504         $sev_names{$sev_name} = 1;
505     }
506     # mark obsolete severities
507     for my $sev ($s->resultset('Severity')->search_rs()->all()) {
508         next if exists $sev_names{$sev->severity()};
509         $sev->obsolete(1);
510         $sev->update();
511     }
512 }
513
514 sub add_suite {
515     my ($options,$opts,$p,$config,$argv) = @_;
516     # suites
517
518     my $s = db_connect($options);
519     my $dist_dir = IO::Dir->new($opts->{ftpdists});
520     my @dist_names =
521         grep { $_ !~ /^\./ and
522                -d $opts->{ftpdists}.'/'.$_ and
523                not -l $opts->{ftpdists}.'/'.$_
524            } $dist_dir->read;
525     while (my $dist = shift @dist_names) {
526         my $dist_dir = $opts->{ftpdists}.'/'.$dist;
527         my ($dist_info,$package_files) =
528             read_release_file($dist_dir.'/Release');
529         load_suite($s,$dist_info);
530     }
531 }
532
533 sub add_logs {
534     my ($options,$opts,$p,$config,$argv) = @_;
535
536     chdir($config->{spool_dir}) or
537         die "chdir $config->{spool_dir} failed: $!";
538
539     my $verbose = $options->{debug};
540
541     my $initialdir = "db-h";
542
543     if (defined $argv->[0] and $argv->[0] eq "archive") {
544         $initialdir = "archive";
545     }
546     my $s = db_connect($options);
547
548
549     my $time = 0;
550     my $start_time = time;
551
552     walk_bugs([(@{$argv}?@{$argv} : $initialdir)],
553               $p,
554               'log',
555               $verbose,
556               sub {
557                   my $bug = shift;
558                   my $stat = stat(getbugcomponent($bug,'log',$initialdir));
559                   if (not defined $stat) {
560                       print STDERR "Unable to stat $bug $!\n";
561                       next;
562                   }
563                   if ($options{quick}) {
564                       my $rs = $s->resultset('Bug')->search({bug=>$bug})->single();
565                       next if defined $rs and $stat->mtime <= $rs->last_modified()->epoch();
566                   }
567                   eval {
568                       load_bug_log(db => $s,
569                                    bug => $bug);
570                   };
571                   if ($@) {
572                       die "failure while trying to load bug log $bug\n$@";
573                   }
574               });
575 }
576
577 sub add_packages {
578     my ($options,$opts,$p,$config,$argv) = @_;
579
580     my $dist_dir = IO::Dir->new($opts->{ftpdists});
581     my @dist_names =
582         grep { $_ !~ /^\./ and
583                -d $opts->{ftpdists}.'/'.$_ and
584                not -l $opts->{ftpdists}.'/'.$_
585            } $dist_dir->read;
586     my %s_p;
587     while (my $dist = shift @dist_names) {
588         my $dist_dir = $opts->{ftpdists}.'/'.$dist;
589         my ($dist_info,$package_files) =
590             read_release_file($dist_dir.'/Release');
591         $s_p{$dist_info->{Codename}} = $package_files;
592     }
593     my $tot = 0;
594     for my $suite (keys %s_p) {
595         for my $component (keys %{$s_p{$suite}}) {
596             $tot += scalar keys %{$s_p{$suite}{$component}};
597         }
598     }
599     $p->target($tot) if $p;
600     my $i = 0;
601     my $avg_pkgs = 0;
602     my $tot_suites = scalar keys %s_p;
603     my $done_suites=0;
604     my $completed_pkgs=0;
605     # parse packages files
606     for my $suite (keys %s_p) {
607         my @pkgs;
608         for my $component (keys %{$s_p{$suite}}) {
609             my @archs = keys %{$s_p{$suite}{$component}};
610             if (grep {$_ eq 'source'} @archs) {
611                 @archs = ('source',grep {$_ ne 'source'} @archs);
612             }
613             for my $arch (@archs) {
614                 my $pfh =  open_compressed_file($s_p{$suite}{$component}{$arch}) or
615                     die "Unable to open $s_p{$suite}{$component}{$arch} for reading: $!";
616                 local $_;
617                 local $/ = '';  # paragraph mode
618                 while (<$pfh>) {
619                     my %pkg;
620                     for my $field (qw(Package Maintainer Version Source)) {
621                         /^\Q$field\E: (.*)/m;
622                         $pkg{$field} = $1;
623                     }
624                     next unless defined $pkg{Package} and
625                         defined $pkg{Version};
626                     push @pkgs,[$arch,$component,\%pkg];
627                 }
628             }
629         }
630         my $s = db_connect($options);
631         if ($avg_pkgs==0) {
632             $avg_pkgs = @pkgs;
633         }
634         $p->target($avg_pkgs*($tot_suites-$done_suites-1)+
635                    $completed_pkgs+@pkgs) if $p;
636         load_packages($s,
637                       $suite,
638                       \@pkgs,
639                       $p);
640         $avg_pkgs=($avg_pkgs*$done_suites + @pkgs)/($done_suites+1);
641         $completed_pkgs += @pkgs;
642         $done_suites++;
643     }
644     $p->remove() if $p;
645 }
646
647 sub handle_subcommand_arguments {
648     my ($argv,$args) = @_;
649     my $subopt = {};
650     Getopt::Long::GetOptionsFromArray($argv,
651                               $subopt,
652                               keys %{$args},
653                              );
654     my @usage_errors;
655     for my $arg  (keys %{$args}) {
656         next unless $args->{$arg};
657         my $r_arg = $arg; # real argument name
658         $r_arg =~ s/[=\|].+//g;
659         if (not defined $subopt->{$r_arg}) {
660             push @usage_errors, "You must give a $r_arg option";
661         }
662     }
663     pod2usage(join("\n",@usage_errors)) if @usage_errors;
664     return $subopt;
665 }
666
667 sub get_lock{
668     my ($subcommand,$config,$options) = @_;
669     if (not lockpid($config->{spool_dir}.'/lock/debbugs-loadsql-$subcommand')) {
670         if ($options->{quick}) {
671             # If this is a quick run, just exit
672             print STDERR "Another debbugs-loadsql is running; stopping\n" if $options->{verbose};
673             exit 0;
674         }
675         print STDERR "Another debbugs-loadsql is running; stopping\n";
676         exit 1;
677     }
678 }
679
680 sub db_connect {
681     my ($options) = @_;
682     # connect to the database; figure out how to handle errors
683     # properly here.
684     my $s = Debbugs::DB->connect($options->{service}) or
685         die "Unable to connect to database: ";
686 }
687
688 sub read_release_file {
689     my ($file) = @_;
690     # parse release
691     my $rfh =  open_compressed_file($file) or
692         die "Unable to open $file for reading: $!";
693     my %dist_info;
694     my $in_sha1;
695     my %p_f;
696     while (<$rfh>) {
697         chomp;
698         if (s/^(\S+):\s*//) {
699             if ($1 eq 'SHA1'or $1 eq 'SHA256') {
700                 $in_sha1 = 1;
701                 next;
702             }
703             $dist_info{$1} = $_;
704         } elsif ($in_sha1) {
705             s/^\s//;
706             my ($sha,$size,$f) = split /\s+/,$_;
707             next unless $f =~ /(?:Packages|Sources)(?:\.gz|\.xz)$/;
708             next unless $f =~ m{^([^/]+)/([^/]+)/([^/]+)$};
709             my ($component,$arch,$package_source) = ($1,$2,$3);
710             $arch =~ s/binary-//;
711             next if exists $p_f{$component}{$arch};
712             $p_f{$component}{$arch} = File::Spec->catfile(dirname($file),$f);
713         }
714     }
715     return (\%dist_info,\%p_f);
716 }
717
718 sub walk_bugs {
719     my ($dirs,$p,$what,$verbose,$sub,$n) = @_;
720     my @dirs = @{$dirs};
721     my $tot_dirs = @dirs;
722     my $done_dirs = 0;
723     my $avg_subfiles = 0;
724     my $completed_files = 0;
725     $n //= 1;
726     while (my $dir = shift @dirs) {
727         printf "Doing dir %s ...\n", $dir if $verbose;
728
729         opendir(DIR, "$dir/.") or die "opendir $dir: $!";
730         my @subdirs = readdir(DIR);
731         closedir(DIR);
732
733         my @list = map { m/^(\d+)\.$what$/?($1):() } @subdirs;
734         $tot_dirs -= @dirs;
735         push @dirs, map { m/^(\d+)$/ && -d "$dir/$1"?("$dir/$1"):() } @subdirs;
736         $tot_dirs += @dirs;
737         if ($avg_subfiles == 0) {
738             $avg_subfiles = @list;
739         }
740
741         $p->target($avg_subfiles*($tot_dirs-$done_dirs)+$completed_files+@list) if $p;
742         $avg_subfiles = ($avg_subfiles * $done_dirs + @list) / ($done_dirs+1);
743         $done_dirs += 1;
744
745         my $it = natatime $n,@list;
746         while (my @bugs = $it->()) {
747           $sub->(@bugs);
748           $completed_files += scalar @bugs;
749           $p->update($completed_files) if $p;
750           print "Up to $completed_files bugs...\n"
751             if ($completed_files % 100 == 0 && $verbose);
752         }
753     }
754     $p->remove() if $p;
755 }
756
757
758
759 __END__