dsa-check-packages: work better with weird multi-arch cases
[mirror/dsa-nagios.git] / dsa-nagios-checks / checks / dsa-check-packages
1 #!/usr/bin/perl
2
3 # dsa-check-packages
4
5 # checks for obsolete/local and upgradeable packages.
6 #
7 # packages for the obsolete/local check can be ignored, by
8 # listing their full name in /etc/nagios/obsolete-packages-ignore
9 # or by having a regex (starting a line with "/") that matches
10 # the packagename in said file.
11 #
12 # Takes one optional argument, the location of the ignore file.
13
14
15 # Copyright (C) 2008, 2009 Peter Palfrader <peter@palfrader.org>
16 #
17 # Permission is hereby granted, free of charge, to any person obtaining
18 # a copy of this software and associated documentation files (the
19 # "Software"), to deal in the Software without restriction, including
20 # without limitation the rights to use, copy, modify, merge, publish,
21 # distribute, sublicense, and/or sell copies of the Software, and to
22 # permit persons to whom the Software is furnished to do so, subject to
23 # the following conditions:
24 #
25 # The above copyright notice and this permission notice shall be
26 # included in all copies or substantial portions of the Software.
27 #
28 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
29 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
31 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
32 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
33 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
34 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
36 use strict;
37 use warnings;
38 use English;
39
40 my $IGNORE = "/etc/nagios/obsolete-packages-ignore";
41 my $IGNORED = "/etc/nagios/obsolete-packages-ignore.d";
42
43 my %CODE = (
44         'OK'            => 0,
45         'WARNING'       => 1,
46         'CRITICAL'      => 2,
47         'UNKNOWN'       => 3
48 );
49 my $EXITCODE = 'OK';
50 sub record($) {
51         my ($newexit) = @_;
52         die "code $newexit not defined\n" unless defined $CODE{$newexit};
53
54         if ($CODE{$newexit} > $CODE{$EXITCODE}) {
55                 $EXITCODE = $newexit;
56         };
57 }
58
59
60
61 sub get_packages {
62         $ENV{'COLUMNS'} = 1000;
63         $ENV{'LC_ALL'} = 'C';
64         open(F, "dpkg -l|") or die ("Cannot run dpkg: $!\n");
65         my @lines = <F>;
66         close(F);
67         chomp(@lines);
68
69         my $line;
70         my $has_arch = 0;
71         while (defined($line = shift @lines) && ($line !~ /\+\+\+/)) {
72                 if ($line =~ /Architecture/) { $has_arch = 1; }
73         }
74
75         my %pkgs;
76         for $line (@lines) {
77                 my ($state, $pkg, $version, $arch, undef) = split(/  */, $line);
78                 $arch = '' unless $has_arch;
79                 $pkgs{$state}{$pkg} = { 'installed' => $version, arch => $arch }
80         }
81
82         my $installed = $pkgs{'ii'};
83         delete $pkgs{'ii'};
84
85         my @installed_packages = keys(%$installed);
86         my @cmd = ("apt-cache", "policy", @installed_packages);
87
88         open my $olderr, ">&STDERR"   or die "Can't dup STDERR: $!";
89         open     STDERR, ">/dev/null" or die "Can't dup STDOUT: $!";
90         open (F, "-|", @cmd) or die ("Cannot run apt-cache policy: $!\n");
91         @lines = <F>;
92         close(F);
93         open STDERR, ">&", $olderr  or die "Can't dup OLDERR: $!";
94         chomp(@lines);
95
96         my $pkgname = undef;
97         while (defined($line = shift @lines)) {
98                 if ($line =~ /^([^ ]*):$/) {
99                         # when we have multi-arch capable fu, we require that
100                         # apt-cache policy output is in the same order as its
101                         # arguments.
102                         #
103                         # We needs thi, because the output block in apt-cache
104                         # policy does not show the arch:
105                         #
106                         # | weasel@stanley:~$ apt-cache policy libedit2:amd64
107                         # | libedit2:
108                         # |   Installed: 2.11-20080614-5
109                         # |   Candidate: 2.11-20080614-5
110                         #
111                         # We replace the package name in the output with the
112                         # one we asked for ($pkg:$arch) - but to match this up
113                         # sanely we need the order to be correct.
114                         #
115                         # For squeeze systems (no m-a), apt-cache policy output
116                         # is all different.
117                         $pkgname = $1;
118                         if ($has_arch) {
119                                 my $from_list = shift @installed_packages;
120                                 next if ($pkgname eq $from_list); # no :$arch in pkgname we asked for
121
122                                 my $ma_fix_pkgname = $pkgname.':'.$installed->{$from_list}->{'arch'};
123                                 my $ma_fix_from_list = $from_list.':'.$installed->{$from_list}->{'arch'};
124
125                                 if ($pkgname eq $ma_fix_from_list || # e.g. ia32-libs-i386.  dpkg -l: ia32-libs-i386, apt-cache policy: ia32-libs-i386:i386
126                                     $ma_fix_pkgname eq $from_list) {
127                                         $pkgname = $from_list;
128                                 } else {
129                                         die "Unexpected order mismatch in apt-cache policy output (apt-cache policy name: $pkgname - dpkg -l name: $from_list)\n";
130                                 }
131                         }
132                 } elsif ($line =~ /^ +Installed: (.*)$/) {
133                         # etch dpkg -l does not print epochs, so use this info, it's better
134                         $installed->{$pkgname}{'installed'} = $1;
135                 } elsif ($line =~ /^ +Candidate: (.*)$/) {
136                         $installed->{$pkgname}{'candidate'} = $1;
137                 } elsif ($line =~ /^ +\*\*\*/) {
138                         $line = shift @lines;
139                         my @l = split(/ +/, $line);
140                         $installed->{$pkgname}{'origin'} = $l[2];
141                 }
142         }
143
144         my (%current, %obsolete, %outofdate);
145         for my $pkgname (keys %$installed) {
146                 my $pkg = $installed->{$pkgname};
147
148                 unless (defined($pkg->{'candidate'}) && defined($pkg->{'origin'})) {
149                         $obsolete{$pkgname} = $pkg;
150                         next;
151                 }
152
153                 if ($pkg->{'candidate'} ne $pkg->{'installed'}) {
154                         $outofdate{$pkgname} = $pkg;
155                         next;
156                 };
157                 if ($pkg->{'origin'} eq '/var/lib/dpkg/status') {
158                         $obsolete{$pkgname} = $pkg;
159                         next;
160                 }
161                 $current{$pkgname} = $pkg;
162         }
163
164         $pkgs{'current'} = \%current;
165         $pkgs{'outofdate'} = \%outofdate;
166         $pkgs{'obsolete'} = \%obsolete;
167         return \%pkgs;
168 }
169
170 sub load_ignores {
171         my ($ignorefiles, $require_file) = @_;
172
173         my @ignores;
174
175         for my $ignoreitem (@$ignorefiles) {
176                 next if (!$require_file and ! -e $ignoreitem);
177
178                 my @filestoopen;
179                 if (-d $ignoreitem) {
180                         opendir(DIR, $ignoreitem) or die ("Cannot open dir $ignoreitem: $!\n");
181                         @filestoopen = readdir(DIR);
182                         closedir(DIR);
183
184                         @filestoopen = grep { -f ($ignoreitem.'/'.$_) } @filestoopen;
185                         @filestoopen = grep { /^([a-z0-9_.-]+)+[a-z0-9]+$/i } @filestoopen;
186                         @filestoopen = grep { !/dpkg-(old|dist|new|tmp)$/ } @filestoopen;
187                         @filestoopen = map { ($ignoreitem.'/'.$_) } @filestoopen;
188                 } else {
189                         push @filestoopen, $ignoreitem;
190                 }
191
192                 for my $f (@filestoopen) {
193                         open (F, "< $f") or die ("Cannot open $f: $!\n");
194                         push @ignores, <F>;
195                         close F;
196                 }
197         }
198         chomp(@ignores);
199         return \@ignores;
200 }
201
202 sub check_ignore {
203         my ($pkg, $ignores) = @_;
204
205         my $ignore_this = 0;
206         for my $ignore (@$ignores) {
207                 my $ig = $ignore;
208                 return 1 if ($ig eq $pkg);
209                 if (substr($ig,0,1) eq '/') {
210                         substr($ig, 0, 1, '');
211                         $ig =~ s,/$,,;
212                         return 1 if ($pkg =~ /$ig/);
213                 }
214         }
215         return 0
216 }
217
218 sub filter_ignored {
219         my ($packages, $ignores) = @_;
220
221         my $obs = $packages->{'obsolete'};
222
223         my (%ignored, %bad);
224         for my $pkg (keys %$obs) {
225                 if (check_ignore($pkg, $ignores)) {
226                         $ignored{$pkg} = $obs->{$pkg};
227                 } else {
228                         $bad{$pkg} = $obs->{$pkg};
229                 };
230         }
231         delete $packages->{'obsolete'};
232         $packages->{'obsolete'} = \%bad;
233         $packages->{'obsolete-ignored'} = \%ignored;
234 };
235
236 sub usage {
237         my ($fd, $exit) = @_;
238         print $fd "Usage: $PROGRAM_NAME [<ignorefile|dir> [<ignorefile|dir> ...]]\n";
239         exit $exit;
240 }
241
242 my $ignorefiles = [$IGNORE, $IGNORED];
243 my $ignorefile_userset = 0;
244 if (@ARGV >= 1) {
245         usage(\*STDOUT, 0) if ($ARGV[0] eq "-h");
246         usage(\*STDOUT, 0) if ($ARGV[0] eq "--help");
247         $ignorefile_userset = 1;
248         $ignorefiles = \@ARGV;
249 };
250
251 my $ignores = load_ignores($ignorefiles, $ignorefile_userset);
252 my $packages = get_packages();
253
254 filter_ignored($packages, $ignores);
255
256
257
258 my @reportform = (
259         { 'key' => 'obsolete',
260           'listpackages' => 1,
261           'long' => "%d local or obsolete packages: %s",
262           'short' => "%d obs/loc",
263           'perf' => "obs_loc=%d;1;5;0",
264           'status' => 'WARNING' },
265         { 'key' => 'outofdate',
266           'listpackages' => 1,
267           'long' => "%d out of date packages: %s",
268           'short' => "%d updates",
269           'perf' => "outdated=%d;1;5;0",
270           'status' => 'WARNING' },
271         { 'key' => 'current',
272           'listpackages' => 0,
273           'long' => "%d packages current.",
274           'short' => "%d ok",
275           'perf' => "current=%d;;;0",
276           'status' => 'OK' },
277         { 'key' => 'obsolete-ignored',
278           'listpackages' => 1,
279           'long' => "%d whitelisted local or obsolete packages: %s",
280           'short' => "%d obs/loc(ignored)",
281           'perf' => "obs_ign=%d;;;0",
282           'status' => 'OK' },
283         { 'key' => 'rc',
284           'listpackages' => 1,
285           'long' => "%d packages removed but not purged: %s",
286           'short' => "%d rc",
287           'perf' => "rm_unprg=%d;;;0",
288           'status' => 'OK' },
289         { 'key' => 'hi',
290           'listpackages' => 1,
291           'long' => "%d packages on hold: %s",
292           'short' => "%d hi",
293           'perf' => "hold=%d;;;0",
294           'status' => 'OK' },
295         { 'key' => 'pc',
296           'listpackages' => 1,
297           'long' => "%d packages requested to be purged but conffiles still installed: %s",
298           'short' => "%d pc",
299           'perf' => "prg_conf=%d;1;;0",
300           'status' => 'WARNING' },
301         );
302
303 my @longout;
304 my @perfout;
305 my @shortout;
306 for my $form (@reportform) {
307         my $pkgs = $packages->{$form->{'key'}};
308         delete $packages->{$form->{'key'}};
309         my $num = scalar keys %$pkgs;
310         push @perfout, sprintf($form->{'perf'}, $num);
311         next unless ($num > 0);
312         if ($form->{'listpackages'}) {
313                 my $list = join(", ", keys %$pkgs);
314                 push @longout, sprintf($form->{'long'}, $num, $list);
315         } else {
316                 push @longout, sprintf($form->{'long'}, $num);
317         };
318         push @shortout, sprintf($form->{'short'}, $num);
319         record($form->{'status'});
320 };
321 if (scalar keys %$packages) {
322         record('WARNING');
323         unshift @shortout, "unk: ".join(", ", keys %$packages);
324         for my $status (sort {$b cmp $a} keys %$packages) {
325                 my $pkgs = $packages->{$status};
326                 my $list = join(", ", keys %$pkgs);
327                 unshift @longout, "Unknown package status $status: $list";
328         };
329 }
330
331 my $shortout = $EXITCODE.": ".join(", ", @shortout);
332 my $longout = join("\n", @longout);
333 my $perfout = "|".join(" ", @perfout);
334
335 print $shortout,"\n";
336 print $longout,"\n";
337 print $perfout,"\n";
338
339 exit $CODE{$EXITCODE};