]> git.donarmstrong.com Git - debbugs.git/blob - bin/debbugs-loadsql
a8839e35e793c8afe8f7fa0d7a4d91e09daf648d
[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 use Debbugs::Config qw(:config);
103 use Debbugs::Status qw(read_bug split_status_fields);
104 use Debbugs::Log;
105 use Debbugs::DB;
106 use Debbugs::DB::Load qw(load_bug handle_load_bug_queue :load_package);
107 use DateTime;
108 use File::stat;
109 use IO::Dir;
110 use IO::Uncompress::AnyUncompress;
111
112 my %options =
113     (debug           => 0,
114      help            => 0,
115      man             => 0,
116      verbose         => 0,
117      quiet           => 0,
118      quick           => 0,
119      service         => $config{debbugs_db},
120      progress        => 0,
121     );
122
123 Getopt::Long::Configure('pass_through');
124 GetOptions(\%options,
125            'quick|q',
126            'service|s=s',
127            'sysconfdir|c=s',
128            'progress!',
129            'spool_dir|spool-dir=s',
130            'verbose|v+',
131            'quiet+',
132            'debug|d+','help|h|?','man|m');
133 Getopt::Long::Configure('default');
134
135 pod2usage() if $options{help};
136 pod2usage({verbose=>2}) if $options{man};
137
138 $DEBUG = $options{debug};
139
140 my %subcommands =
141     ('bugs' => {function => \&add_bugs,
142                },
143      'versions' => {function => \&add_versions,
144                    },
145      'debinfo' => {function => \&add_debinfo,
146                    arguments => {'0|null' => 0},
147                   },
148      'maintainers' => {function => \&add_maintainers,
149                       },
150      'configuration' => {function => \&add_configuration,
151                         },
152      'suites' => {function => \&add_suites,
153                  },
154      'logs' => {function => \&add_logs,
155                },
156      'packages' => {function => \&add_packages,
157                     arguments => {'ftpdists=s' => 1,
158                                  },
159                    },
160      'help' => {function => sub {pod2usage({verbose => 2});}}
161     );
162
163 my @USAGE_ERRORS;
164 $options{verbose} = $options{verbose} - $options{quiet};
165
166 if ($options{progress}) {
167     eval "use Term::ProgressBar";
168     push @USAGE_ERRORS, "You asked for a progress bar, but Term::ProgressBar isn't installed" if $@;
169 }
170
171
172 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
173
174 if (exists $options{sysconfdir}) {
175     if (not defined $options{sysconfdir} or not length $options{sysconfdir}) {
176         delete $ENV{PGSYSCONFDIR};
177     } else {
178         $ENV{PGSYSCONFDIR} = $options{sysconfdir};
179     }
180 }
181
182 if (exists $options{spool_dir} and defined $options{spool_dir}) {
183     $config{spool_dir} = $options{spool_dir};
184 }
185
186 my $prog_bar;
187 if ($options{progress}) {
188     $prog_bar = eval "Term::ProgressBar->new({count => 1,ETA=>q(linear)})";
189     warn "Unable to initialize progress bar: $@" if not $prog_bar;
190 }
191
192
193 my ($subcommand) = shift @ARGV;
194 if (not defined $subcommand) {
195     $subcommand = 'help';
196     print STDERR "You must provide a subcommand; displaying usage.\n";
197     pod2usage();
198 } elsif (not exists $subcommands{$subcommand}) {
199     print STDERR "$subcommand is not a valid subcommand; displaying usage.\n";
200     pod2usage();
201 }
202
203 my $opts =
204     handle_subcommand_arguments(\@ARGV,$subcommands{$subcommand}{arguments});
205 $subcommands{$subcommand}{function}->(\%options,$opts,$prog_bar,\%config,\@ARGV);
206
207 sub add_bugs {
208     my ($options,$opts,$p,$config,$argv) = @_;
209     chdir($config->{spool_dir}) or
210         die "chdir $config->{spool_dir} failed: $!";
211
212     my $verbose = $options->{debug};
213
214     my $initialdir = "db-h";
215
216     if (defined $argv->[0] and $argv->[0] eq "archive") {
217         $initialdir = "archive";
218     }
219     my $s = db_connect($options);
220
221
222     my $time = 0;
223     my $start_time = time;
224     my %tags;
225     my %severities;
226     my %queue;
227
228     walk_bugs([(@{$argv}?@{$argv} : $initialdir)],
229               $p,
230               'summary',
231               $verbose,
232               sub {
233                   my $bug = shift;
234                   my $stat = stat(getbugcomponent($bug,'summary',$initialdir));
235                   if (not defined $stat) {
236                       print STDERR "Unable to stat $bug $!\n";
237                       next;
238                   }
239                   if ($options{quick}) {
240                       my $rs = $s->resultset('Bug')->search({bug=>$bug})->single();
241                       next if defined $rs and $stat->mtime < $rs->last_modified()->epoch();
242                   }
243                   my $data = read_bug(bug => $bug,
244                                       location => $initialdir);
245                   eval {
246                       load_bug(db => $s,
247                                data => split_status_fields($data),
248                                tags => \%tags,
249                                severities => \%severities,
250                                queue => \%queue);
251                   };
252                   if ($@) {
253                       use Data::Dumper;
254                       print STDERR Dumper($data) if $DEBUG;
255                       die "failure while trying to load bug $bug\n$@";
256                   }
257               }
258              );
259     handle_load_bug_queue(db => $s,
260                           queue => \%queue);
261 }
262
263 sub add_versions {
264     my ($options,$opts,$p,$config,$argv) = @_;
265
266     my $s = db_connect($options);
267
268     my @files = @{$argv};
269     $p->target(scalar @files) if $p;
270     for my $file (@files) {
271         my $fh = IO::File->new($file,'r') or
272             die "Unable to open $file for reading: $!";
273         my @versions;
274         my %src_pkgs;
275         while (<$fh>) {
276             chomp;
277             next unless length $_;
278             if (/(\w[-+0-9a-z.]+) \(([^\(\) \t]+)\)/) {
279                 push @versions, [$1,$2];
280             }
281         }
282         close($fh);
283         my $ancestor_sv;
284         for my $i (reverse 0..($#versions)) {
285             my $sp;
286             if (not defined $src_pkgs{$versions[$i][0]}) {
287                 $src_pkgs{$versions[$i][0]} =
288                     $s->resultset('SrcPkg')->find_or_create({pkg => $versions[$i][0]});
289             }
290             $sp = $src_pkgs{$versions[$i][0]};
291             # There's probably something wrong if the source package
292             # doesn't exist, but we'll skip it for now
293             next unless defined $sp;
294             my $sv = $s->resultset('SrcVer')->find({src_pkg=>$sp->id(),
295                                                     ver => $versions[$i][1],
296                                                    });
297             if (defined $ancestor_sv and defined $sv and not defined $sv->based_on()) {
298                 $sv->update({based_on => $ancestor_sv->id()})
299             }
300             $ancestor_sv = $sv;
301         }
302         $p->update() if $p;
303     }
304     $p->remove() if $p;
305 }
306
307 sub add_debinfo {
308     my ($options,$opts,$p,$config,$argv) = @_;
309
310     my @files = @{$argv};
311     if (not @files) {
312        {
313            if ($opts->{0}) {
314                local $/ = "\0";
315            }
316            while (<STDIN>) {
317                push @files, $_;
318            }
319        }
320     }
321     return unless @files;
322     my $s = db_connect($options);
323     my %arch;
324     $p->target(scalar @files) if $p;
325     for my $file (@files) {
326         my $fh = IO::File->new($file,'r') or
327             die "Unable to open $file for reading: $!";
328         my $f_stat = stat($file);
329         while (<$fh>) {
330             chomp;
331             next unless length $_;
332             my ($binname, $binver, $binarch, $srcname, $srcver) = split;
333             # if $srcver is not defined, this is probably a broken
334             # .debinfo file [they were causing #686106, see commit
335             # 49c85ab8 in dak.] Basically, $binarch didn't get put into
336             # the file, so we'll fudge it from the filename.
337             if (not defined $srcver) {
338                 ($srcname,$srcver) = ($binarch,$srcname);
339                 ($binarch) = $file =~ /_([^\.]+)\.debinfo/;
340             }
341             my $sp = $s->resultset('SrcPkg')->find_or_create({pkg => $srcname});
342             # update the creation date if the data we have is earlier
343             my $ct_date = DateTime->from_epoch(epoch => $f_stat->ctime);
344             if ($ct_date < $sp->creation) {
345                 $sp->creation($ct_date);
346                 $sp->last_modified(DateTime->now);
347                 $sp->update;
348             }
349             my $sv = $s->resultset('SrcVer')->find_or_create({src_pkg =>$sp->id(),
350                                                               ver => $srcver});
351             if (not defined $sv->upload_date() or $ct_date < $sv->upload_date()) {
352                 $sv->upload_date($ct_date);
353                 $sv->update;
354             }
355             my $arch;
356             if (defined $arch{$binarch}) {
357                 $arch = $arch{$binarch};
358             } else {
359                 $arch = $s->resultset('Arch')->find_or_create({arch => $binarch});
360                 $arch{$binarch} = $arch;
361             }
362             my $bp = $s->resultset('BinPkg')->find_or_create({pkg => $binname});
363             $s->resultset('BinVer')->find_or_create({bin_pkg => $bp->id(),
364                                                      src_ver => $sv->id(),
365                                                      arch    => $arch->id(),
366                                                      ver        => $binver,
367                                                     });
368         }
369         $p->update() if $p;
370     }
371     $p->remove() if $p;
372 }
373
374 sub add_maintainers {
375     my ($options,$opts,$p,$config,$argv) = @_;
376
377     my $s = db_connect($options);
378     my $maintainers = getsourcemaintainers();
379     $p->target(scalar keys %{$maintainers}) if $p;
380     for my $pkg (keys %{$maintainers}) {
381         my $maint = $maintainers->{$pkg};
382         # see if a maintainer already exists; if so, we don't do
383         # anything here
384         my $maint_r = $s->resultset('Maintainer')->
385             find({name => $maint});
386         if (not defined $maint_r) {
387             # get e-mail address of maintainer
388             my $addr = getparsedaddrs($maint);
389             my $e_mail = $addr->address();
390             my $full_name = $addr->phrase();
391             $full_name =~ s/^\"|\"$//g;
392             $full_name =~ s/^\s+|\s+$//g;
393             # find correspondent
394             my $correspondent = $s->resultset('Correspondent')->
395                 find_or_create({addr => $e_mail});
396             if (length $full_name) {
397                 my $c_full_name = $correspondent->find_or_create_related('correspondent_full_names',
398                                                                         {full_name => $full_name}) if length $full_name;
399                 $c_full_name->update({last_seen => 'NOW()'});
400             }
401             $maint_r =
402                 $s->resultset('Maintainer')->
403                 find_or_create({name => $maint,
404                                 correspondent => $correspondent,
405                                });
406         }
407         # add the maintainer to the source package for packages with
408         # no maintainer
409         $s->txn_do(sub {
410                       $s->resultset('SrcPkg')->search({pkg => $pkg})->
411                           search_related_rs('src_vers',{ maintainer => undef})->
412                           update_all({maintainer => $maint_r->id()});
413                   });
414         $p->update() if $p;
415     }
416     $p->remove() if $p;
417 }
418
419 sub add_configuration {
420     my ($options,$opts,$p,$config,$argv) = @_;
421
422     my $s = db_connect($options);
423
424     # tags
425     # add all tags
426     # mark obsolete tags
427
428     # severities
429     my %sev_names;
430     my $order = 0;
431     for my $sev_name (@{$config{severities}}) {
432         # add all severitites
433         my $sev = $s->resultset('Severity')->find_or_create({severity => $sev_name});
434         # mark strong severities
435         if (grep {$_ eq $sev_name} @{$config{strong_severities}}) {
436             $sev->strong(1);
437         }
438         $sev->order($order);
439         $sev->update();
440         $order++;
441         $sev_names{$sev_name} = 1;
442     }
443     # mark obsolete severities
444     for my $sev ($s->resultset('Severity')->find()) {
445         next if exists $sev_names{$sev->severity()};
446         $sev->obsolete(1);
447         $sev->update();
448     }
449 }
450
451 sub add_suite {
452     my ($options,$opts,$p,$config,$argv) = @_;
453     # suites
454     die "add_suite is currently not implemented; modify suites manually using SQL."
455 }
456
457 sub add_logs {
458     my ($options,$opts,$p,$config,$argv) = @_;
459
460     chdir($config->{spool_dir}) or
461         die "chdir $config->{spool_dir} failed: $!";
462
463     my $verbose = $options->{debug};
464
465     my $initialdir = "db-h";
466
467     if (defined $argv->[0] and $argv->[0] eq "archive") {
468         $initialdir = "archive";
469     }
470     my $s = db_connect($options);
471
472
473     my $time = 0;
474     my $start_time = time;
475
476     walk_bugs([(@{$argv}?@{$argv} : $initialdir)],
477               $p,
478               'log',
479               $verbose,
480               sub {
481                   my $bug = shift;
482                   eval { 
483                       load_bug_log(db => $s,
484                                    bug => $bug);
485                   };
486                   if ($@) {
487                       die "failure while trying to load bug log $bug\n$@";
488                   }
489               });
490 }
491
492 sub add_packages {
493     my ($options,$opts,$p,$config,$argv) = @_;
494
495     my $s = db_connect($options);
496
497     my $dist_dir = IO::Dir->new($opts->{ftpdists});
498     my @dist_names =
499         grep { $_ !~ /^\./ and
500                -d $opts->{ftpdists}.'/'.$_ and
501                not -l $opts->{ftpdists}.'/'.$_
502            } $dist_dir->read;
503     my %s_p;
504     my %s_info;
505     while (my $dist = shift @dist_names) {
506         my $dist_dir = $opts->{ftpdists}.'/'.$dist;
507         # parse release
508         my $rfh =  IO::Uncompress::AnyUncompress->new($dist_dir.'/Release');
509         my %dist_info;
510         my $in_sha1;
511         my %p_f;
512         while (<$rfh>) {
513             chomp;
514             if (s/^(\S+):\s*//) {
515                 if ($1 eq 'SHA1'or $1 eq 'SHA256') {
516                     $in_sha1 = 1;
517                     next;
518                 }
519                 $dist_info{$1} = $_;
520             } elsif ($in_sha1) {
521                 s/^\s//;
522                 my ($sha,$size,$file) = split /\s+/,$_;
523                 next unless $file =~ /(?:Packages|Sources)(?:\.gz|\.xz)$/;
524                 next unless $file =~ m{^([^/]+)/([^/]+)/([^/]+)$};
525                 my ($component,$arch,$package_source) = ($1,$2,$3);
526                 $arch =~ s/binary-//;
527                 next if exists $p_f{$component}{$arch};
528                 $p_f{$component}{$arch} = $dist_dir.'/'.$file;
529             }
530         }
531         $s_p{$dist_info{Suite}} = \%p_f;
532         $s_info{$dist_info{Suite}} = \%s_info;
533     }
534     # parse packages files
535     for my $suite (keys %s_p) {
536         for my $component (keys %{$s_p{$suite}}) {
537             for my $arch (keys %{$s_p{$suite}{$component}}) {
538                 my $pfh =  IO::Uncompress::AnyUncompress->new($s_p{$suite}{$component}{$arch}) or
539                     die "Unable to open $s_p{$suite}{$component}{$arch} for reading: $!";
540                 my $lastkey;
541                 my %pkg;
542                 while (<$pfh>) {
543                     if (/^$/) {
544                         load_package($s,$suite,$component,$arch,\%pkg);
545                         %pkg = ();
546                         next;
547                     }
548                     if (my ($key, $value) = m/^(\S+): (.*)/) {
549                         $pkg{$key} = $value;
550                         $lastkey=$key;
551                     }
552                     else {
553                         s/ //;
554                         s/^\.$//;
555                         chomp;
556                         $pkg{$lastkey} .= "\n" . $_;
557                     }
558                 }
559                 if (keys %pkg) {
560                     load_package($s,$suite,$component,$arch,\%pkg);
561                 }
562             }
563         }
564     }
565     use Data::Printer;
566     p %s_p;
567 }
568
569 sub handle_subcommand_arguments {
570     my ($argv,$args) = @_;
571     my $subopt = {};
572     Getopt::Long::GetOptionsFromArray($argv,
573                               $subopt,
574                               keys %{$args},
575                              );
576     my @usage_errors;
577     for my $arg  (keys %{$args}) {
578         next unless $args->{$arg};
579         my $r_arg = $arg; # real argument name
580         $r_arg =~ s/[=\|].+//g;
581         if (not defined $subopt->{$r_arg}) {
582             push @usage_errors, "You must give a $r_arg option";
583         }
584     }
585     pod2usage(join("\n",@usage_errors)) if @usage_errors;
586     return $subopt;
587 }
588
589 sub get_lock{
590     my ($subcommand,$config,$options) = @_;
591     if (not lockpid($config->{spool_dir}.'/lock/debbugs-loadsql-$subcommand')) {
592         if ($options->{quick}) {
593             # If this is a quick run, just exit
594             print STDERR "Another debbugs-loadsql is running; stopping\n" if $options->{verbose};
595             exit 0;
596         }
597         print STDERR "Another debbugs-loadsql is running; stopping\n";
598         exit 1;
599     }
600 }
601
602 sub db_connect {
603     my ($options) = @_;
604     # connect to the database; figure out how to handle errors
605     # properly here.
606     my $s = Debbugs::DB->connect($options->{service}) or
607         die "Unable to connect to database: ";
608 }
609
610 sub walk_bugs {
611     my ($dirs,$p,$what,$verbose,$sub) = @_;
612     my @dirs = @{$dirs};
613     my $tot_dirs = @dirs;
614     my $done_dirs = 0;
615     my $avg_subfiles = 0;
616     my $completed_files = 0;
617     while (my $dir = shift @dirs) {
618         printf "Doing dir %s ...\n", $dir if $verbose;
619
620         opendir(DIR, "$dir/.") or die "opendir $dir: $!";
621         my @subdirs = readdir(DIR);
622         closedir(DIR);
623
624         my @list = map { m/^(\d+)\.$what$/?($1):() } @subdirs;
625         $tot_dirs -= @dirs;
626         push @dirs, map { m/^(\d+)$/ && -d "$dir/$1"?("$dir/$1"):() } @subdirs;
627         $tot_dirs += @dirs;
628         if ($avg_subfiles == 0) {
629             $avg_subfiles = @list;
630         }
631
632         $p->target($avg_subfiles*($tot_dirs-$done_dirs)+$completed_files+@list) if $p;
633         $avg_subfiles = ($avg_subfiles * $done_dirs + @list) / ($done_dirs+1);
634         $done_dirs += 1;
635
636         for my $bug (@list) {
637             $completed_files++;
638             $p->update($completed_files) if $p;
639             print "Up to $completed_files bugs...\n" if ($completed_files % 100 == 0 && $verbose);
640             $sub->($bug);
641         }
642     }
643     $p->remove() if $p;
644 }
645
646
647
648 __END__