]> git.donarmstrong.com Git - debbugs.git/blob - bin/debbugs-loadsql
start add_packages and support add_configuration
[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             my $sv = $s->resultset('SrcVer')->find_or_create({src_pkg =>$sp->id(),
327                                                               ver => $srcver});
328             my $arch;
329             if (defined $arch{$binarch}) {
330                 $arch = $arch{$binarch};
331             } else {
332                 $arch = $s->resultset('Arch')->find_or_create({arch => $binarch});
333                 $arch{$binarch} = $arch;
334             }
335             my $bp = $s->resultset('BinPkg')->find_or_create({pkg => $binname});
336             $s->resultset('BinVer')->find_or_create({bin_pkg => $bp->id(),
337                                                      src_ver => $sv->id(),
338                                                      arch    => $arch->id(),
339                                                      ver        => $binver,
340                                                     });
341         }
342         $p->update() if $p;
343     }
344     $p->remove() if $p;
345 }
346
347 sub add_maintainers {
348     my ($options,$opts,$p,$config,$argv) = @_;
349
350     my $s = db_connect($options);
351     my $maintainers = getsourcemaintainers();
352     $p->target(scalar keys %{$maintainers}) if $p;
353     for my $pkg (keys %{$maintainers}) {
354         my $maint = $maintainers->{$pkg};
355         # see if a maintainer already exists; if so, we don't do
356         # anything here
357         my $maint_r = $s->resultset('Maintainer')->
358             find({name => $maint});
359         if (not defined $maint_r) {
360             # get e-mail address of maintainer
361             my $addr = getparsedaddrs($maint);
362             my $e_mail = $addr->address();
363             my $full_name = $addr->phrase();
364             $full_name =~ s/^\"|\"$//g;
365             $full_name =~ s/^\s+|\s+$//g;
366             # find correspondent
367             my $correspondent = $s->resultset('Correspondent')->
368                 find_or_create({addr => $e_mail});
369             if (length $full_name) {
370                 my $c_full_name = $correspondent->find_or_create_related('correspondent_full_names',
371                                                                         {full_name => $full_name}) if length $full_name;
372                 $c_full_name->update({last_seen => 'NOW()'});
373             }
374             $maint_r =
375                 $s->resultset('Maintainer')->
376                 find_or_create({name => $maint,
377                                 correspondent => $correspondent,
378                                });
379         }
380         # add the maintainer to the source package for packages with
381         # no maintainer
382         $s->txn_do(sub {
383                       $s->resultset('SrcPkg')->search({pkg => $pkg})->
384                           search_related_rs('src_vers',{ maintainer => undef})->
385                           update_all({maintainer => $maint_r->id()});
386                   });
387         $p->update() if $p;
388     }
389     $p->remove() if $p;
390 }
391
392 sub add_configuration {
393     my ($options,$opts,$p,$config,$argv) = @_;
394
395     my $s = db_connect($options);
396
397     # tags
398     # add all tags
399     # mark obsolete tags
400
401     # severities
402     my %sev_names;
403     my $order = 0;
404     for my $sev_name (@{$config{severities}}) {
405         # add all severitites
406         my $sev = $s->resultset('Severity')->find_or_create({severity => $sev_name});
407         # mark strong severities
408         if (grep $sev_name $config{strong_severities}) {
409             $sev->strong(1);
410         }
411         $sev->order($order);
412         $sev->update();
413         $order++;
414         $sev_names{$sev_name} = 1;
415     }
416     # mark obsolete severities
417     for my $sev ($s->resultset('Severity')->find()) {
418         next if exists $sev_names{$sev->severity()};
419         $sev->obsolete(1);
420         $sev->update();
421     }
422 }
423
424 sub add_suite {
425     my ($options,$opts,$p,$config,$argv) = @_;
426     # suites
427     die "add_suite is currently not implemented; modify suites manually using SQL."
428 }
429
430 sub add_logs {
431     my ($options,$opts,$p,$config,$argv) = @_;
432
433     chdir($config->{spool_dir}) or
434         die "chdir $config->{spool_dir} failed: $!";
435
436     my $verbose = $options->{debug};
437
438     my $initialdir = "db-h";
439
440     if (defined $argv->[0] and $argv->[0] eq "archive") {
441         $initialdir = "archive";
442     }
443     my $s = db_connect($options);
444
445
446     my $time = 0;
447     my $start_time = time;
448
449     walk_bugs([(@{$argv}?@{$argv} : $initialdir)],
450               $p,
451               'log',
452               $verbose,
453               sub {
454                   my $bug = shift;
455                   eval { 
456                       load_bug_log(db => $s,
457                                    bug => $bug);
458                   };
459                   if ($@) {
460                       die "failure while trying to load bug log $bug\n$@";
461                   }
462               });
463 }
464
465 sub add_packages {
466
467 }
468
469 sub handle_subcommand_arguments {
470     my ($argv,$args) = @_;
471     my $subopt = {};
472     Getopt::Long::GetOptionsFromArray($argv,
473                               $subopt,
474                               keys %{$args},
475                              );
476     my @usage_errors;
477     for my $arg  (keys %{$args}) {
478         next unless $args->{$arg};
479         my $r_arg = $arg; # real argument name
480         $r_arg =~ s/[=\|].+//g;
481         if (not defined $subopt->{$r_arg}) {
482             push @usage_errors, "You must give a $r_arg option";
483         }
484     }
485     pod2usage(join("\n",@usage_errors)) if @usage_errors;
486     return $subopt;
487 }
488
489 sub get_lock{
490     my ($subcommand,$config,$options) = @_;
491     if (not lockpid($config->{spool_dir}.'/lock/debbugs-loadsql-$subcommand')) {
492         if ($options->{quick}) {
493             # If this is a quick run, just exit
494             print STDERR "Another debbugs-loadsql is running; stopping\n" if $options->{verbose};
495             exit 0;
496         }
497         print STDERR "Another debbugs-loadsql is running; stopping\n";
498         exit 1;
499     }
500 }
501
502 sub db_connect {
503     my ($options) = @_;
504     # connect to the database; figure out how to handle errors
505     # properly here.
506     my $s = Debbugs::DB->connect('dbi:Pg:service='.$options->{service}) or
507         die "Unable to connect to database: ";
508 }
509
510 sub walk_bugs {
511     my ($dirs,$p,$what,$verbose,$sub) = @_;
512     my @dirs = @{$dirs};
513     my $tot_dirs = @dirs;
514     my $done_dirs = 0;
515     my $avg_subfiles = 0;
516     my $completed_files = 0;
517     while (my $dir = shift @dirs) {
518         printf "Doing dir %s ...\n", $dir if $verbose;
519
520         opendir(DIR, "$dir/.") or die "opendir $dir: $!";
521         my @subdirs = readdir(DIR);
522         closedir(DIR);
523
524         my @list = map { m/^(\d+)\.$what$/?($1):() } @subdirs;
525         $tot_dirs -= @dirs;
526         push @dirs, map { m/^(\d+)$/ && -d "$dir/$1"?("$dir/$1"):() } @subdirs;
527         $tot_dirs += @dirs;
528         if ($avg_subfiles == 0) {
529             $avg_subfiles = @list;
530         }
531
532         $p->target($avg_subfiles*($tot_dirs-$done_dirs)+$completed_files+@list) if $p;
533         $avg_subfiles = ($avg_subfiles * $done_dirs + @list) / ($done_dirs+1);
534         $done_dirs += 1;
535
536         for my $bug (@list) {
537             $completed_files++;
538             $p->update($completed_files) if $p;
539             print "Up to $completed_files bugs...\n" if ($completed_files % 100 == 0 && $verbose);
540             $sub->($bug);
541         }
542     }
543     $p->remove() if $p;
544 }
545
546
547
548 __END__