Merge remote-tracking branch 'adsb/fordsa'
[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         my $candidate_found = 0;
98         while (defined($line = shift @lines)) {
99                 if ($line =~ /^([^ ]*):$/) {
100                         # when we have multi-arch capable fu, we require that
101                         # apt-cache policy output is in the same order as its
102                         # arguments.
103                         #
104                         # We need this, because the output block in apt-cache
105                         # policy does not show the arch:
106                         #
107                         # | weasel@stanley:~$ apt-cache policy libedit2:amd64
108                         # | libedit2:
109                         # |   Installed: 2.11-20080614-5
110                         # |   Candidate: 2.11-20080614-5
111                         #
112                         # We replace the package name in the output with the
113                         # one we asked for ($pkg:$arch) - but to match this up
114                         # sanely we need the order to be correct.
115                         #
116                         # For squeeze systems (no m-a), apt-cache policy output
117                         # is all different.
118                         $pkgname = $1;
119                         $candidate_found = 0;
120                         if ($has_arch) {
121                                 my $from_list = shift @installed_packages;
122                                 next if ($pkgname eq $from_list); # no :$arch in pkgname we asked for
123
124                                 my $ma_fix_pkgname = $pkgname.':'.$installed->{$from_list}->{'arch'};
125                                 my $ma_fix_from_list = $from_list.':'.$installed->{$from_list}->{'arch'};
126
127                                 if ($pkgname eq $ma_fix_from_list || # e.g. ia32-libs-i386.  dpkg -l: ia32-libs-i386, apt-cache policy: ia32-libs-i386:i386
128                                     $ma_fix_pkgname eq $from_list) {
129                                         $pkgname = $from_list;
130                                 } else {
131                                         die "Unexpected order mismatch in apt-cache policy output (apt-cache policy name: $pkgname - dpkg -l name: $from_list)\n";
132                                 }
133                         }
134                 } elsif ($line =~ /^ +Installed: (.*)$/) {
135                         # etch dpkg -l does not print epochs, so use this info, it's better
136                         $installed->{$pkgname}{'installed'} = $1;
137                         # initialize security-update
138                         $installed->{$pkgname}{'security-update'} = 0;
139                 } elsif ($line =~ /^ +Candidate: (.*)$/) {
140                         $installed->{$pkgname}{'candidate'} = $1;
141                 } elsif ($line =~ /     ([^ ]+) [0-9]+/) {
142                         # check if the next lines show the sources of our candidate
143                         if ($1 eq $installed->{$pkgname}{'candidate'}) {
144                                 $candidate_found = 1;
145                         }
146                 } elsif (($line =~ / +[0-9]+ [^ ]+\/(security\.([^ ]+\.)?debian\.org|debian-security).*\/updates\//) && $candidate_found ) {
147                         $installed->{$pkgname}{'security-update'} = 1;
148                 } elsif ($line =~ /^ +\*\*\*/) {
149                         $line = shift @lines;
150                         my @l = split(/ +/, $line);
151                         $installed->{$pkgname}{'origin'} = $l[2];
152                         $candidate_found = 0;
153                 }
154         }
155
156         my (%current, %obsolete, %outofdate, %security_outofdate);
157         for my $pkgname (keys %$installed) {
158                 my $pkg = $installed->{$pkgname};
159
160                 unless (defined($pkg->{'candidate'}) && defined($pkg->{'origin'})) {
161                         $obsolete{$pkgname} = $pkg;
162                         next;
163                 }
164
165                 if ($pkg->{'candidate'} ne $pkg->{'installed'}) {
166                         if ($pkg->{'security-update'}) {
167                                 $security_outofdate{$pkgname} = $pkg;
168                         } else {
169                                 $outofdate{$pkgname} = $pkg;
170                         }
171                         next;
172                 };
173                 if ($pkg->{'origin'} eq '/var/lib/dpkg/status') {
174                         $obsolete{$pkgname} = $pkg;
175                         next;
176                 }
177                 $current{$pkgname} = $pkg;
178         }
179
180         $pkgs{'current'} = \%current;
181         $pkgs{'outofdate'} = \%outofdate;
182         $pkgs{'security_outofdate'} = \%security_outofdate;
183         $pkgs{'obsolete'} = \%obsolete;
184         return \%pkgs;
185 }
186
187 sub load_ignores {
188         my ($ignorefiles, $require_file) = @_;
189
190         my @ignores;
191
192         for my $ignoreitem (@$ignorefiles) {
193                 next if (!$require_file and ! -e $ignoreitem);
194
195                 my @filestoopen;
196                 if (-d $ignoreitem) {
197                         opendir(DIR, $ignoreitem) or die ("Cannot open dir $ignoreitem: $!\n");
198                         @filestoopen = readdir(DIR);
199                         closedir(DIR);
200
201                         @filestoopen = grep { -f ($ignoreitem.'/'.$_) } @filestoopen;
202                         @filestoopen = grep { /^([a-z0-9_.-]+)+[a-z0-9]+$/i } @filestoopen;
203                         @filestoopen = grep { !/dpkg-(old|dist|new|tmp)$/ } @filestoopen;
204                         @filestoopen = map { ($ignoreitem.'/'.$_) } @filestoopen;
205                 } else {
206                         push @filestoopen, $ignoreitem;
207                 }
208
209                 for my $f (@filestoopen) {
210                         open (F, "< $f") or die ("Cannot open $f: $!\n");
211                         push @ignores, <F>;
212                         close F;
213                 }
214         }
215         chomp(@ignores);
216         return \@ignores;
217 }
218
219 sub check_ignore {
220         my ($pkg, $ignores) = @_;
221
222         my $ignore_this = 0;
223         for my $ignore (@$ignores) {
224                 my $ig = $ignore;
225                 return 1 if ($ig eq $pkg);
226                 if (substr($ig,0,1) eq '/') {
227                         substr($ig, 0, 1, '');
228                         $ig =~ s,/$,,;
229                         return 1 if ($pkg =~ /$ig/);
230                 }
231         }
232         return 0
233 }
234
235 sub filter_ignored {
236         my ($packages, $ignores) = @_;
237
238         my $obs = $packages->{'obsolete'};
239
240         my (%ignored, %bad);
241         for my $pkg (keys %$obs) {
242                 if (check_ignore($pkg, $ignores)) {
243                         $ignored{$pkg} = $obs->{$pkg};
244                 } else {
245                         $bad{$pkg} = $obs->{$pkg};
246                 };
247         }
248         delete $packages->{'obsolete'};
249         $packages->{'obsolete'} = \%bad;
250         $packages->{'obsolete-ignored'} = \%ignored;
251 };
252
253 sub usage {
254         my ($fd, $exit) = @_;
255         print $fd "Usage: $PROGRAM_NAME [<ignorefile|dir> [<ignorefile|dir> ...]]\n";
256         exit $exit;
257 }
258
259 my $ignorefiles = [$IGNORE, $IGNORED];
260 my $ignorefile_userset = 0;
261 if (@ARGV >= 1) {
262         usage(\*STDOUT, 0) if ($ARGV[0] eq "-h");
263         usage(\*STDOUT, 0) if ($ARGV[0] eq "--help");
264         $ignorefile_userset = 1;
265         $ignorefiles = \@ARGV;
266 };
267
268 my $ignores = load_ignores($ignorefiles, $ignorefile_userset);
269 my $packages = get_packages();
270
271 filter_ignored($packages, $ignores);
272
273
274
275 my @reportform = (
276         { 'key' => 'obsolete',
277           'listpackages' => 1,
278           'long' => "%d local or obsolete packages: %s",
279           'short' => "%d obs/loc",
280           'perf' => "obs_loc=%d;1;5;0",
281           'status' => 'WARNING' },
282         { 'key' => 'outofdate',
283           'listpackages' => 1,
284           'long' => "%d out of date packages: %s",
285           'short' => "%d updates",
286           'perf' => "outdated=%d;1;5;0",
287           'status' => 'WARNING' },
288         { 'key' => 'current',
289           'listpackages' => 0,
290           'long' => "%d packages current.",
291           'short' => "%d ok",
292           'perf' => "current=%d;;;0",
293           'status' => 'OK' },
294         { 'key' => 'obsolete-ignored',
295           'listpackages' => 1,
296           'long' => "%d whitelisted local or obsolete packages: %s",
297           'short' => "%d obs/loc(ignored)",
298           'perf' => "obs_ign=%d;;;0",
299           'status' => 'OK' },
300         { 'key' => 'rc',
301           'listpackages' => 1,
302           'long' => "%d packages removed but not purged: %s",
303           'short' => "%d rc",
304           'perf' => "rm_unprg=%d;;;0",
305           'status' => 'OK' },
306         { 'key' => 'hi',
307           'listpackages' => 1,
308           'long' => "%d packages on hold: %s",
309           'short' => "%d hi",
310           'perf' => "hold=%d;;;0",
311           'status' => 'OK' },
312         { 'key' => 'pc',
313           'listpackages' => 1,
314           'long' => "%d packages requested to be purged but conffiles still installed: %s",
315           'short' => "%d pc",
316           'perf' => "prg_conf=%d;1;;0",
317           'status' => 'WARNING' },
318         { 'key' => 'security_outofdate',
319           'listpackages' => 1,
320           'long' => "%d packages with outstanding security updates: %s",
321           'short' => "%d security-updates",
322           'perf' => "security_outdated=%d;;1;0",
323           'status' => 'CRITICAL' },
324         );
325
326 my @longout;
327 my @perfout;
328 my @shortout;
329 for my $form (@reportform) {
330         my $pkgs = $packages->{$form->{'key'}};
331         delete $packages->{$form->{'key'}};
332         my $num = scalar keys %$pkgs;
333         push @perfout, sprintf($form->{'perf'}, $num);
334         next unless ($num > 0);
335         if ($form->{'listpackages'}) {
336                 my $list = join(", ", keys %$pkgs);
337                 push @longout, sprintf($form->{'long'}, $num, $list);
338         } else {
339                 push @longout, sprintf($form->{'long'}, $num);
340         };
341         push @shortout, sprintf($form->{'short'}, $num);
342         record($form->{'status'});
343 };
344 if (scalar keys %$packages) {
345         record('WARNING');
346         unshift @shortout, "unk: ".join(", ", keys %$packages);
347         for my $status (sort {$b cmp $a} keys %$packages) {
348                 my $pkgs = $packages->{$status};
349                 my $list = join(", ", keys %$pkgs);
350                 unshift @longout, "Unknown package status $status: $list";
351         };
352 }
353
354 my $shortout = $EXITCODE.": ".join(", ", @shortout);
355 my $longout = join("\n", @longout);
356 my $perfout = "|".join(" ", @perfout);
357
358 print $shortout,"\n";
359 print $longout,"\n";
360 print $perfout,"\n";
361
362 exit $CODE{$EXITCODE};