]> git.donarmstrong.com Git - debbugs.git/blob - bin/debbugs-loadsql
load_packages now only changes rows it has to
[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(scalar keys %{$maintainers}) if $p;
391     for my $pkg (keys %{$maintainers}) {
392         my $maint = $maintainers->{$pkg};
393         # see if a maintainer already exists; if so, we don't do
394         # anything here
395         my $maint_r = $s->resultset('Maintainer')->
396             find({name => $maint});
397         if (not defined $maint_r) {
398             # get e-mail address of maintainer
399             my $addr = getparsedaddrs($maint);
400             my $e_mail = $addr->address();
401             my $full_name = $addr->phrase();
402             $full_name =~ s/^\"|\"$//g;
403             $full_name =~ s/^\s+|\s+$//g;
404             # find correspondent
405             my $correspondent = $s->resultset('Correspondent')->
406                 find_or_create({addr => $e_mail});
407             if (length $full_name) {
408                 my $c_full_name = $correspondent->find_or_create_related('correspondent_full_names',
409                                                                         {full_name => $full_name}) if length $full_name;
410                 $c_full_name->update({last_seen => 'NOW()'});
411             }
412             $maint_r =
413                 $s->resultset('Maintainer')->
414                 find_or_create({name => $maint,
415                                 correspondent => $correspondent,
416                                });
417         }
418         # add the maintainer to the source package for packages with
419         # no maintainer
420         $s->txn_do(sub {
421                       $s->resultset('SrcPkg')->search({pkg => $pkg})->
422                           search_related_rs('src_vers',{ maintainer => undef})->
423                           update_all({maintainer => $maint_r->id()});
424                   });
425         $p->update() if $p;
426     }
427     $p->remove() if $p;
428 }
429
430 sub add_configuration {
431     my ($options,$opts,$p,$config,$argv) = @_;
432
433     my $s = db_connect($options);
434
435     # tags
436     # add all tags
437     # mark obsolete tags
438
439     # severities
440     my %sev_names;
441     my $order = 0;
442     for my $sev_name (@{$config{severities}}) {
443         # add all severitites
444         my $sev = $s->resultset('Severity')->find_or_create({severity => $sev_name});
445         # mark strong severities
446         if (grep {$_ eq $sev_name} @{$config{strong_severities}}) {
447             $sev->strong(1);
448         }
449         $sev->order($order);
450         $sev->update();
451         $order++;
452         $sev_names{$sev_name} = 1;
453     }
454     # mark obsolete severities
455     for my $sev ($s->resultset('Severity')->find()) {
456         next if exists $sev_names{$sev->severity()};
457         $sev->obsolete(1);
458         $sev->update();
459     }
460 }
461
462 sub add_suite {
463     my ($options,$opts,$p,$config,$argv) = @_;
464     # suites
465
466     my $s = db_connect($options);
467     my $dist_dir = IO::Dir->new($opts->{ftpdists});
468     my @dist_names =
469         grep { $_ !~ /^\./ and
470                -d $opts->{ftpdists}.'/'.$_ and
471                not -l $opts->{ftpdists}.'/'.$_
472            } $dist_dir->read;
473     while (my $dist = shift @dist_names) {
474         my $dist_dir = $opts->{ftpdists}.'/'.$dist;
475         my ($dist_info,$package_files) =
476             read_release_file($dist_dir.'/Release');
477         load_suite($s,$dist_info);
478     }
479 }
480
481 sub add_logs {
482     my ($options,$opts,$p,$config,$argv) = @_;
483
484     chdir($config->{spool_dir}) or
485         die "chdir $config->{spool_dir} failed: $!";
486
487     my $verbose = $options->{debug};
488
489     my $initialdir = "db-h";
490
491     if (defined $argv->[0] and $argv->[0] eq "archive") {
492         $initialdir = "archive";
493     }
494     my $s = db_connect($options);
495
496
497     my $time = 0;
498     my $start_time = time;
499
500     walk_bugs([(@{$argv}?@{$argv} : $initialdir)],
501               $p,
502               'log',
503               $verbose,
504               sub {
505                   my $bug = shift;
506                   eval { 
507                       load_bug_log(db => $s,
508                                    bug => $bug);
509                   };
510                   if ($@) {
511                       die "failure while trying to load bug log $bug\n$@";
512                   }
513               });
514 }
515
516 sub add_packages {
517     my ($options,$opts,$p,$config,$argv) = @_;
518
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     my %s_p;
526     while (my $dist = shift @dist_names) {
527         my $dist_dir = $opts->{ftpdists}.'/'.$dist;
528         my ($dist_info,$package_files) =
529             read_release_file($dist_dir.'/Release');
530         $s_p{$dist_info->{Codename}} = $package_files;
531     }
532     my $tot = 0;
533     for my $suite (keys %s_p) {
534         for my $component (keys %{$s_p{$suite}}) {
535             $tot += scalar keys %{$s_p{$suite}{$component}};
536         }
537     }
538     $p->target($tot) if $p;
539     my $i = 0;
540     my $avg_pkgs = 0;
541     my $tot_suites = scalar keys %s_p;
542     my $done_suites=0;
543     my $completed_pkgs=0;
544     # parse packages files
545     for my $suite (keys %s_p) {
546         my @pkgs;
547         for my $component (keys %{$s_p{$suite}}) {
548             my @archs = keys %{$s_p{$suite}{$component}};
549             if (grep {$_ eq 'source'} @archs) {
550                 @archs = ('source',grep {$_ ne 'source'} @archs);
551             }
552             for my $arch (@archs) {
553                 my $pfh =  open_compressed_file($s_p{$suite}{$component}{$arch}) or
554                     die "Unable to open $s_p{$suite}{$component}{$arch} for reading: $!";
555                 local $_;
556                 local $/ = '';  # paragraph mode
557                 while (<$pfh>) {
558                     my %pkg;
559                     for my $field (qw(Package Maintainer Version Source)) {
560                         /^\Q$field\E: (.*)/m;
561                         $pkg{$field} = $1;
562                     }
563                     next unless defined $pkg{Package} and
564                         defined $pkg{Version};
565                     push @pkgs,[$arch,$component,\%pkg];
566                 }
567             }
568         }
569         my $s = db_connect($options);
570         if ($avg_pkgs==0) {
571             $avg_pkgs = @pkgs;
572         }
573         $p->target($avg_pkgs*($tot_suites-$done_suites-1)+
574                    $completed_pkgs+@pkgs) if $p;
575         load_packages($s,
576                       $suite,
577                       \@pkgs,
578                       $p);
579         $avg_pkgs=($avg_pkgs*$done_suites + @pkgs)/($done_suites+1);
580         $completed_pkgs += @pkgs;
581         $done_suites++;
582     }
583     $p->remove() if $p;
584 }
585
586 sub handle_subcommand_arguments {
587     my ($argv,$args) = @_;
588     my $subopt = {};
589     Getopt::Long::GetOptionsFromArray($argv,
590                               $subopt,
591                               keys %{$args},
592                              );
593     my @usage_errors;
594     for my $arg  (keys %{$args}) {
595         next unless $args->{$arg};
596         my $r_arg = $arg; # real argument name
597         $r_arg =~ s/[=\|].+//g;
598         if (not defined $subopt->{$r_arg}) {
599             push @usage_errors, "You must give a $r_arg option";
600         }
601     }
602     pod2usage(join("\n",@usage_errors)) if @usage_errors;
603     return $subopt;
604 }
605
606 sub get_lock{
607     my ($subcommand,$config,$options) = @_;
608     if (not lockpid($config->{spool_dir}.'/lock/debbugs-loadsql-$subcommand')) {
609         if ($options->{quick}) {
610             # If this is a quick run, just exit
611             print STDERR "Another debbugs-loadsql is running; stopping\n" if $options->{verbose};
612             exit 0;
613         }
614         print STDERR "Another debbugs-loadsql is running; stopping\n";
615         exit 1;
616     }
617 }
618
619 sub db_connect {
620     my ($options) = @_;
621     # connect to the database; figure out how to handle errors
622     # properly here.
623     my $s = Debbugs::DB->connect($options->{service}) or
624         die "Unable to connect to database: ";
625 }
626
627 sub open_compressed_file {
628     my ($file) = @_;
629     my $fh;
630     my $mode = '<:encoding(UTF-8)';
631     my @opts;
632     if ($file =~ /\.gz$/) {
633         $mode = '-|:encoding(UTF-8)';
634         push @opts,'gzip','-dc';
635     }
636     if ($file =~ /\.xz$/) {
637         $mode = '-|:encoding(UTF-8)';
638         push @opts,'xz','-dc';
639     }
640     if ($file =~ /\.bz2$/) {
641         $mode = '-|:encoding(UTF-8)';
642         push @opts,'bzip2','-dc';
643     }
644     open($fh,$mode,@opts,$file);
645     return $fh;
646 }
647
648 sub read_release_file {
649     my ($file) = @_;
650     # parse release
651     my $rfh =  open_compressed_file($file) or
652         die "Unable to open $file for reading: $!";
653     my %dist_info;
654     my $in_sha1;
655     my %p_f;
656     while (<$rfh>) {
657         chomp;
658         if (s/^(\S+):\s*//) {
659             if ($1 eq 'SHA1'or $1 eq 'SHA256') {
660                 $in_sha1 = 1;
661                 next;
662             }
663             $dist_info{$1} = $_;
664         } elsif ($in_sha1) {
665             s/^\s//;
666             my ($sha,$size,$f) = split /\s+/,$_;
667             next unless $f =~ /(?:Packages|Sources)(?:\.gz|\.xz)$/;
668             next unless $f =~ m{^([^/]+)/([^/]+)/([^/]+)$};
669             my ($component,$arch,$package_source) = ($1,$2,$3);
670             $arch =~ s/binary-//;
671             next if exists $p_f{$component}{$arch};
672             $p_f{$component}{$arch} = File::Spec->catfile(dirname($file),$f);
673         }
674     }
675     return (\%dist_info,\%p_f);
676 }
677
678 sub walk_bugs {
679     my ($dirs,$p,$what,$verbose,$sub) = @_;
680     my @dirs = @{$dirs};
681     my $tot_dirs = @dirs;
682     my $done_dirs = 0;
683     my $avg_subfiles = 0;
684     my $completed_files = 0;
685     while (my $dir = shift @dirs) {
686         printf "Doing dir %s ...\n", $dir if $verbose;
687
688         opendir(DIR, "$dir/.") or die "opendir $dir: $!";
689         my @subdirs = readdir(DIR);
690         closedir(DIR);
691
692         my @list = map { m/^(\d+)\.$what$/?($1):() } @subdirs;
693         $tot_dirs -= @dirs;
694         push @dirs, map { m/^(\d+)$/ && -d "$dir/$1"?("$dir/$1"):() } @subdirs;
695         $tot_dirs += @dirs;
696         if ($avg_subfiles == 0) {
697             $avg_subfiles = @list;
698         }
699
700         $p->target($avg_subfiles*($tot_dirs-$done_dirs)+$completed_files+@list) if $p;
701         $avg_subfiles = ($avg_subfiles * $done_dirs + @list) / ($done_dirs+1);
702         $done_dirs += 1;
703
704         for my $bug (@list) {
705             $completed_files++;
706             $p->update($completed_files) if $p;
707             print "Up to $completed_files bugs...\n" if ($completed_files % 100 == 0 && $verbose);
708             $sub->($bug);
709         }
710     }
711     $p->remove() if $p;
712 }
713
714
715
716 __END__