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