]> git.donarmstrong.com Git - debbugs.git/blob - bin/debbugs-loadsql
implement load bug logs
[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     my %tags;
444     for my $tag (@{$config{tags}}) {
445         $tags{$tag} = 1;
446         $s->resultset('Tag')->find_or_create({tag => $tag});
447     }
448     # mark obsolete tags
449     for my $tag ($s->resultset('Tag')->search_rs()->all()) {
450         next if exists $tags{$tag->tag};
451         $tag->obsolete(1);
452         $tag->update;
453     }
454
455     # severities
456     my %sev_names;
457     my $order = -1;
458     for my $sev_name (($config{default_severity},@{$config{severity_list}})) {
459         # add all severitites
460         my $sev = $s->resultset('Severity')->find_or_create({severity => $sev_name});
461         # mark strong severities
462         if (grep {$_ eq $sev_name} @{$config{strong_severities}}) {
463             $sev->strong(1);
464         }
465         $sev->ordering($order);
466         $sev->update();
467         $order++;
468         $sev_names{$sev_name} = 1;
469     }
470     # mark obsolete severities
471     for my $sev ($s->resultset('Severity')->search_rs()->all()) {
472         next if exists $sev_names{$sev->severity()};
473         $sev->obsolete(1);
474         $sev->update();
475     }
476 }
477
478 sub add_suite {
479     my ($options,$opts,$p,$config,$argv) = @_;
480     # suites
481
482     my $s = db_connect($options);
483     my $dist_dir = IO::Dir->new($opts->{ftpdists});
484     my @dist_names =
485         grep { $_ !~ /^\./ and
486                -d $opts->{ftpdists}.'/'.$_ and
487                not -l $opts->{ftpdists}.'/'.$_
488            } $dist_dir->read;
489     while (my $dist = shift @dist_names) {
490         my $dist_dir = $opts->{ftpdists}.'/'.$dist;
491         my ($dist_info,$package_files) =
492             read_release_file($dist_dir.'/Release');
493         load_suite($s,$dist_info);
494     }
495 }
496
497 sub add_logs {
498     my ($options,$opts,$p,$config,$argv) = @_;
499
500     chdir($config->{spool_dir}) or
501         die "chdir $config->{spool_dir} failed: $!";
502
503     my $verbose = $options->{debug};
504
505     my $initialdir = "db-h";
506
507     if (defined $argv->[0] and $argv->[0] eq "archive") {
508         $initialdir = "archive";
509     }
510     my $s = db_connect($options);
511
512
513     my $time = 0;
514     my $start_time = time;
515
516     walk_bugs([(@{$argv}?@{$argv} : $initialdir)],
517               $p,
518               'log',
519               $verbose,
520               sub {
521                   my $bug = shift;
522                   my $stat = stat(getbugcomponent($bug,'log',$initialdir));
523                   if (not defined $stat) {
524                       print STDERR "Unable to stat $bug $!\n";
525                       next;
526                   }
527                   if ($options{quick}) {
528                       my $rs = $s->resultset('Bug')->search({bug=>$bug})->single();
529                       next if defined $rs and $stat->mtime < $rs->last_modified()->epoch();
530                   }
531                   eval {
532                       load_bug_log(db => $s,
533                                    bug => $bug);
534                   };
535                   if ($@) {
536                       die "failure while trying to load bug log $bug\n$@";
537                   }
538               });
539 }
540
541 sub add_packages {
542     my ($options,$opts,$p,$config,$argv) = @_;
543
544     my $dist_dir = IO::Dir->new($opts->{ftpdists});
545     my @dist_names =
546         grep { $_ !~ /^\./ and
547                -d $opts->{ftpdists}.'/'.$_ and
548                not -l $opts->{ftpdists}.'/'.$_
549            } $dist_dir->read;
550     my %s_p;
551     while (my $dist = shift @dist_names) {
552         my $dist_dir = $opts->{ftpdists}.'/'.$dist;
553         my ($dist_info,$package_files) =
554             read_release_file($dist_dir.'/Release');
555         $s_p{$dist_info->{Codename}} = $package_files;
556     }
557     my $tot = 0;
558     for my $suite (keys %s_p) {
559         for my $component (keys %{$s_p{$suite}}) {
560             $tot += scalar keys %{$s_p{$suite}{$component}};
561         }
562     }
563     $p->target($tot) if $p;
564     my $i = 0;
565     my $avg_pkgs = 0;
566     my $tot_suites = scalar keys %s_p;
567     my $done_suites=0;
568     my $completed_pkgs=0;
569     # parse packages files
570     for my $suite (keys %s_p) {
571         my @pkgs;
572         for my $component (keys %{$s_p{$suite}}) {
573             my @archs = keys %{$s_p{$suite}{$component}};
574             if (grep {$_ eq 'source'} @archs) {
575                 @archs = ('source',grep {$_ ne 'source'} @archs);
576             }
577             for my $arch (@archs) {
578                 my $pfh =  open_compressed_file($s_p{$suite}{$component}{$arch}) or
579                     die "Unable to open $s_p{$suite}{$component}{$arch} for reading: $!";
580                 local $_;
581                 local $/ = '';  # paragraph mode
582                 while (<$pfh>) {
583                     my %pkg;
584                     for my $field (qw(Package Maintainer Version Source)) {
585                         /^\Q$field\E: (.*)/m;
586                         $pkg{$field} = $1;
587                     }
588                     next unless defined $pkg{Package} and
589                         defined $pkg{Version};
590                     push @pkgs,[$arch,$component,\%pkg];
591                 }
592             }
593         }
594         my $s = db_connect($options);
595         if ($avg_pkgs==0) {
596             $avg_pkgs = @pkgs;
597         }
598         $p->target($avg_pkgs*($tot_suites-$done_suites-1)+
599                    $completed_pkgs+@pkgs) if $p;
600         load_packages($s,
601                       $suite,
602                       \@pkgs,
603                       $p);
604         $avg_pkgs=($avg_pkgs*$done_suites + @pkgs)/($done_suites+1);
605         $completed_pkgs += @pkgs;
606         $done_suites++;
607     }
608     $p->remove() if $p;
609 }
610
611 sub handle_subcommand_arguments {
612     my ($argv,$args) = @_;
613     my $subopt = {};
614     Getopt::Long::GetOptionsFromArray($argv,
615                               $subopt,
616                               keys %{$args},
617                              );
618     my @usage_errors;
619     for my $arg  (keys %{$args}) {
620         next unless $args->{$arg};
621         my $r_arg = $arg; # real argument name
622         $r_arg =~ s/[=\|].+//g;
623         if (not defined $subopt->{$r_arg}) {
624             push @usage_errors, "You must give a $r_arg option";
625         }
626     }
627     pod2usage(join("\n",@usage_errors)) if @usage_errors;
628     return $subopt;
629 }
630
631 sub get_lock{
632     my ($subcommand,$config,$options) = @_;
633     if (not lockpid($config->{spool_dir}.'/lock/debbugs-loadsql-$subcommand')) {
634         if ($options->{quick}) {
635             # If this is a quick run, just exit
636             print STDERR "Another debbugs-loadsql is running; stopping\n" if $options->{verbose};
637             exit 0;
638         }
639         print STDERR "Another debbugs-loadsql is running; stopping\n";
640         exit 1;
641     }
642 }
643
644 sub db_connect {
645     my ($options) = @_;
646     # connect to the database; figure out how to handle errors
647     # properly here.
648     my $s = Debbugs::DB->connect($options->{service}) or
649         die "Unable to connect to database: ";
650 }
651
652 sub open_compressed_file {
653     my ($file) = @_;
654     my $fh;
655     my $mode = '<:encoding(UTF-8)';
656     my @opts;
657     if ($file =~ /\.gz$/) {
658         $mode = '-|:encoding(UTF-8)';
659         push @opts,'gzip','-dc';
660     }
661     if ($file =~ /\.xz$/) {
662         $mode = '-|:encoding(UTF-8)';
663         push @opts,'xz','-dc';
664     }
665     if ($file =~ /\.bz2$/) {
666         $mode = '-|:encoding(UTF-8)';
667         push @opts,'bzip2','-dc';
668     }
669     open($fh,$mode,@opts,$file);
670     return $fh;
671 }
672
673 sub read_release_file {
674     my ($file) = @_;
675     # parse release
676     my $rfh =  open_compressed_file($file) or
677         die "Unable to open $file for reading: $!";
678     my %dist_info;
679     my $in_sha1;
680     my %p_f;
681     while (<$rfh>) {
682         chomp;
683         if (s/^(\S+):\s*//) {
684             if ($1 eq 'SHA1'or $1 eq 'SHA256') {
685                 $in_sha1 = 1;
686                 next;
687             }
688             $dist_info{$1} = $_;
689         } elsif ($in_sha1) {
690             s/^\s//;
691             my ($sha,$size,$f) = split /\s+/,$_;
692             next unless $f =~ /(?:Packages|Sources)(?:\.gz|\.xz)$/;
693             next unless $f =~ m{^([^/]+)/([^/]+)/([^/]+)$};
694             my ($component,$arch,$package_source) = ($1,$2,$3);
695             $arch =~ s/binary-//;
696             next if exists $p_f{$component}{$arch};
697             $p_f{$component}{$arch} = File::Spec->catfile(dirname($file),$f);
698         }
699     }
700     return (\%dist_info,\%p_f);
701 }
702
703 sub walk_bugs {
704     my ($dirs,$p,$what,$verbose,$sub) = @_;
705     my @dirs = @{$dirs};
706     my $tot_dirs = @dirs;
707     my $done_dirs = 0;
708     my $avg_subfiles = 0;
709     my $completed_files = 0;
710     while (my $dir = shift @dirs) {
711         printf "Doing dir %s ...\n", $dir if $verbose;
712
713         opendir(DIR, "$dir/.") or die "opendir $dir: $!";
714         my @subdirs = readdir(DIR);
715         closedir(DIR);
716
717         my @list = map { m/^(\d+)\.$what$/?($1):() } @subdirs;
718         $tot_dirs -= @dirs;
719         push @dirs, map { m/^(\d+)$/ && -d "$dir/$1"?("$dir/$1"):() } @subdirs;
720         $tot_dirs += @dirs;
721         if ($avg_subfiles == 0) {
722             $avg_subfiles = @list;
723         }
724
725         $p->target($avg_subfiles*($tot_dirs-$done_dirs)+$completed_files+@list) if $p;
726         $avg_subfiles = ($avg_subfiles * $done_dirs + @list) / ($done_dirs+1);
727         $done_dirs += 1;
728
729         for my $bug (@list) {
730             $completed_files++;
731             $p->update($completed_files) if $p;
732             print "Up to $completed_files bugs...\n" if ($completed_files % 100 == 0 && $verbose);
733             $sub->($bug);
734         }
735     }
736     $p->remove() if $p;
737 }
738
739
740
741 __END__