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