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