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