b6353002b7b7128cc8c18268fe2442db7ea7aabd
[git-tools-moved-to-github.git] / aptcheck / aptcheck.pl
1 #!/usr/bin/perl -w
2 #
3 # Check what packages are needed to get upgraded on all machines
4 #
5 # Depends heavily on having ssh key authentication set up to all
6 # boxes. That's why I run it on my own workstation.
7 #
8 # Regular debian upgrades are detected by running 
9 #  apt-get upgrade -s
10 # on every machine, and parsing the output.
11
12 # We have decided to maintain some packages manually on some 
13 # machines, so that system-level upgrades will not disturb 
14 # applications, which may need more hand-holding. These are
15 # extracted from our apt repository, and queried on every 
16 # server with apt-cache policy. This way, as soon as a package
17 # is released on our repo, it will get listed here.
18 #
19 # 11-Mar-2011 Heikki: Started this
20 # 22-Mar-2011 Heikki: Adding manually maintained packages
21 # 15-Aug-2011 Heikki: Adding a total in the headline, for nagiosgrapher
22 # 21-May-2012 Heikki: Added a date since when a package has been pending
23 # 31-May-2012 Heikki: Pointing to the new wiki
24 # 01-Jan-2013 Heikki: Get hosts from nagios-us as well.
25 #
26 # TODO: Assumes that we release our restricted packages for all versions
27 # and architectures at the same time. Gets only the highest version from
28 # all, and reports anything less than this. Good enough for now.
29 #
30
31 #### Init
32 use strict;
33 my $debug= $ARGV[0] || 0; # 0=none, 1=some, 2=more, 3=much
34 my $year =`date +%Y`;
35 #my $wikilink = 'http://twiki.indexdata.dk/cgi-bin/twiki/view/ID/';
36 my $wikilink = 'https://twiki.indexdata.com/twiki/bin/view/ID/';
37 my $restrictedpackages = "ssh -q kebab cat /home/ftp/pub/debian/dists/*/restricted/*/Packages";
38
39 #### Host comments
40 my %hostcomments = (
41       "ariel"    => "<i>Niels Erik</i> does the manual upgrades",
42       "bellone"  => "<i>Niels Erik</i> does the manual upgrades",
43       "cfrepous" => "<i>Wolfram</i> does the manual upgrades",
44       "leopard"  => "<i>Wolfram</i> does the manual upgrades",
45       "lsd"      => "<i>Heikki</i> takes care of all upgrades",
46       );
47       
48
49 #### Get list of hosts
50 # I could use a hard-coded list, but I would forget to maintain it.
51 # Nagios knows most of our hosts. It even knows which are worth 
52 # checking, they have a command to check apts!
53 print "Getting hostlist from nagios\n" if $debug;
54 my $hostlist1 = `ssh nagios grep -l Apt /etc/nagios3/indexdata-conf.d/*.cfg`
55   or die "Could not get host list from nagios (dk)";
56
57 print "Getting hostlist from nagios-us\n" if $debug;
58 my $hostlist2 = `ssh nagios-us grep -l Apt /etc/nagios3/indexdata-conf.d/*.cfg`
59   or die "Could not get host list from nagios (dk)";
60
61 my $hostlist = $hostlist1 . $hostlist2;
62 print "Got list:\n$hostlist\n" if $debug>2;
63
64 ###### Get list of packages that can be manually maintained
65 print "getting restricted package versions\n" if $debug;
66 my %restrpkgs;
67 my $restplines = `$restrictedpackages`
68   or die "Could not get the list of restricted packages " .
69          "from $restrictedpackages: $! ";
70 print "Got package list: \n$restplines\n" if $debug>2;
71 my $pname;
72 my $pver;
73 for my $pline ( split("\n",$restplines) ) {
74     chomp($pline);
75     $pname = $1 if $pline =~ /^Package:\s+(\S*)\s*$/;
76     $pver = $1 if $pline =~ /^Version:\s+(\S*)\s*$/;
77     print "$pline: p=$pname v=$pver\n" if $debug>2;
78     if ( $pname && $pver ) {
79         print "\nPackage $pname version $pver \n" if $debug>2;
80         if ( ! $restrpkgs{$pname} ) {
81             $restrpkgs{$pname} = $pver;
82             print "found $pname, first version $pver\n" if $debug>1;
83         } else {
84             my $bver = $restrpkgs{$pname};
85             `dpkg --compare-versions "$bver" lt "$pver" 2>/dev/null `;
86             if ( ! $? ) {
87                 print "found $pname, better version $pver (better than $bver)\n"
88                     if $debug>1;
89                 $restrpkgs{$pname} = $pver;
90             } else {
91                 print "found $pname, but version $pver is no better than $bver\n"
92                     if $debug>2;
93             }
94         }
95         $pname = ""; # clear for the next one.
96         $pver = "";
97     }
98 }
99
100 print "got " . scalar(keys(%restrpkgs)) . " restricted packages\n" if $debug;
101 if ( $debug >1 ) {
102     for $pname ( sort (keys(%restrpkgs)) ) {
103         print "  $pname " . $restrpkgs{$pname} . "\n";
104     }
105 }
106
107 # Statistics
108 my %summary;
109 my ( %sechosts, %secpkgs );
110 my ( %ownhosts, %ownpkgs );
111 my ( %manhosts, %manpkgs );
112 my ( %normhosts, %normpkgs );
113 my %okhosts;
114 my %skiphosts;
115 my %allhosts;
116 my $sectot = 0;
117 my $owntot = 0;
118 my $mantot = 0;
119 my $normtot = 0;
120 my %updlinks;
121 my %debversions;
122
123 # Pending modification dates
124 my %olddates;  # Read in from the file
125 my %newdates;  # To be written in the new version of the file
126 my $datefilename = "aptcheck.data";
127 my $dateoldfilename = "aptcheck.old";
128 my $thisdate = "*"; # indicates really old stuff
129 my $warndate; # Older than this will be boldfaced
130
131 if ( -f $datefilename ) {
132   print "Reading dates from $datefilename\n" if $debug;
133   open F, $datefilename or die "Could not open date file $datefilename: $!";
134   while (<F>) {
135     chop();
136     my ($pkg, $date) = split;
137     next unless $pkg;  # skip empty lines
138     $olddates{$pkg} = $date;
139     print "Date for '$pkg' is '$date' \n" if $debug;
140   }
141   close F;
142   $thisdate = `date +%F`;
143   chomp($thisdate);
144   $warndate = `date +%F -d "30 days ago"` ; ;
145   chomp($warndate);
146   print "Dates: now: '$thisdate' warn: '$warndate'\n" if $debug;
147 } else {
148   print "No datefile $datefilename found, starting from scratch\n";
149 }
150
151
152 my $table = "<table>\n";
153
154 #for my $hline ( split("\n",$hostlist) ) {
155 for my $hline ( sort( split("\n",$hostlist) ) ) {
156     next unless ( $hline =~ /\/([a-z0-9-]+)\.cfg$/ );
157     my $H = $1;
158     next if ($H =~ /^commands/ );
159     next if ($H =~ /^servicegroups/ );
160     print "Checking $H\n" if $debug;
161     $allhosts{$H}=1;
162     my $cmd0 = "cat /etc/debian_version";
163     my $cmd1 = "apt-cache -q policy " . join(" ",sort(keys(%restrpkgs)));
164     my $cmd2 = "apt-get upgrade -s -o 'Debug::NoLocking=true' ";
165     # Note, do not append -qq, we want some output even when nothing to do
166     print "ssh -q $H \"$cmd0; $cmd1 ; $cmd2 \" 2>/dev/null \n" if ($debug>1);
167     my $apt = `ssh -q $H "$cmd0; $cmd1 ; $cmd2 " 2>/dev/null`;
168     if ( !$apt ) {
169         $table .= "<tr><td colspan='3'>&nbsp;</td></tr>\n";
170         $table .= "<tr><td colspan='3'><b><u>$H</u></b> (skipped)\n";
171         $skiphosts{$H}=1;
172         next;
173     }
174     print "Got apts for $H: \n$apt\n" if $debug>2;
175     my $det = ""; # detail lines
176     my $pkgs = 0;
177     my $secs = 0;
178     my $own = 0;
179     my $man = 0;
180     my $restrname = "";
181     my $restrinst = "";
182     my $restrcand = "";
183     my $debver = 0;
184     for my $p ( split("\n",$apt) ) {
185         if ( !$debver ) {  # first line
186           $debver = 1;
187           $p =~ s/(5[0-9.]+)/$1 LENNY !!!/;
188           $p =~ s/(6[0-9.]+)/$1 squeeze/;
189           $p =~ s/(7[0-9.]+)/$1 wheezy/;
190           $p = "&nbsp;Debian $p";
191           $debversions{$H} = $p;
192           print "Deb version for $H is $p\n" if ($debug>1);
193           next;
194         }
195         # parse apt-cache output
196         $restrname = $1 if $p =~ /^(\S+):$/;
197         $restrinst = $1 if $p =~ /^\s+Installed:\s+(\S+)$/;
198         $restrcand = $1 if $p =~ /^\s+Candidate:\s+(\S+)$/;
199         if ( $p =~ /^\s+Version table:/ ) { # have all for that package
200             my $bver = $restrpkgs{$restrname};
201             if ( ( $restrinst eq $restrcand ) &&
202                  ( $restrinst ne $bver ) ) { 
203                 # if different, it is a regular apt upgrade, and will be seen
204                 # later. AND we want to have a different version in our repo
205                 `dpkg --compare-versions "$bver" lt "$restrinst"  2>/dev/null`;
206                 if ( $? ) { # It was not a downgrade 
207                             # manual packages may be ahead of the repo!
208                     $mantot++;
209                     $man++;
210                     $pkgs++;
211                     $manhosts{$H} = 1;
212                     $manpkgs{$restrname} = 1;
213                     $det .= "<tr>";
214                     $det .= "<td>&nbsp;&nbsp;$restrname <b>(M)</b></td>";
215                     $det .= "<td>". strdiff($bver,$restrinst)."</td>";
216                     $det .= "<td>". strdiff($restrinst,$bver)."</td>";
217                     my $datekey = "$H:$restrname";
218                     if ( $olddates{$datekey} ) {
219                         $newdates{$datekey} = $olddates{$datekey};
220                     } else {
221                         $newdates{$datekey} = $thisdate;
222                     }
223                     my $dispdate = $newdates{$datekey};
224                     # if ( $dispdate lt $warndate ) {
225                     if ( 0 ) { # manual packages don't need to be highlighted
226                         $dispdate = "<b>$dispdate !</b>";
227                     }
228                     $det .= "<td>" . $dispdate . "</td>";
229                     $det .= "</tr>\n";
230                     my $key = "$restrname";
231                     if ( !$summary{$key} ) {
232                         $summary{$key} = "";
233                     }
234                     $summary{$key} .= "$H ";
235                 }
236             }
237             $restrname = ""; # clear for next round
238             $restrinst = "";
239             $restrcand = "";
240         }
241         next unless $p =~
242             /^Inst ([^ ]+) \[([^]]+)\] \(([^ ]+) ([^:]+):/;
243         my ( $pkg,$cur,$new,$src ) = ( $1,$2,$3,$4 );
244         print "$H: $pkg: $cur -> $new ($src)\n" if $debug>1;
245         $det .= "<tr><td>&nbsp;&nbsp;";
246         $pkgs++;
247         my $key = $pkg;
248         if ( $src =~ /Security/ ) {
249             $det .= "<b>$pkg (s)</b> ";
250             $sechosts{$H} = 1;
251             $secpkgs{$pkg} = 1;
252             $secs++;
253             $sectot++;
254         } elsif ( $src =~ /Indexdata/ ) {
255             $det .= "<i><b>$pkg</b> (id) </i>";
256             $ownhosts{$H}=1;
257             $ownpkgs{$pkg}=1;
258             $own++;
259             $owntot++;
260         } else {
261             $det .= "$pkg ";
262             $normhosts{$H}=1;
263             $normpkgs{$pkg}=1;
264             $normtot++;
265         }
266         if ( !$summary{$key} ) {
267             $summary{$key} = "";
268         }
269         $summary{$key} .= "$H ";
270         $new = strdiff($cur,$new);
271         $cur = strdiff($new,$cur);
272         $det .= "</td> ";
273         $det .= "<td>$cur</td> ";
274         $det .= "<td>$new</td> ";
275         my $datekey = "$H:$pkg";
276         if ( $olddates{$datekey} ) {
277             $newdates{$datekey} = $olddates{$datekey};
278         } else {
279             $newdates{$datekey} = $thisdate;
280         }
281         my $dispdate = $newdates{$datekey};
282         if ( ( $dispdate lt $warndate ) && ( $src =~ /Security/) ) {
283             $dispdate = "<b>$dispdate !</b>";
284         }
285         $det .= "<td>" . $dispdate . "</td>";
286         $det .= "</tr>\n";
287
288     }
289     $table .= "<tr><td colspan='4'>&nbsp;</td></tr>\n";
290     $table .= "<tr><td colspan='4'><a name='$H'><b><u>$H</u></b></a> &nbsp;\n";
291     if ( $pkgs ) {
292         $table .= "<b>$pkgs</b> packages to upgrade. ";
293         $table .= "<b>$secs security</b>. " if $secs;
294         $table .= " $own from indexdata. " if $own;
295         $table .= " $man manual. " if $man;
296     } else {
297         $table .= "ok";
298         $okhosts{$H} = 1;
299     }
300     my $updlink = $wikilink . ucfirst($H) . "Updates" . $year;
301     # Fix some pages that do not follow the convention.
302     # Mostly because the host names would not make proper WikiWords
303     $updlink =~ s/Bugzilla3Updates/BugzillaUpdates/; 
304     $updlink =~ s/Opencontent-solrUpdates/OpenContentSolrUpdates/; 
305     $updlinks{$H} = $updlink;
306     $table .= "&nbsp;<a href='$updlink' >Upd</a>";
307     $table .= "&nbsp;" . $debversions{$H};
308     $table .= "</td></tr>\n";
309     $table .= "<tr><td>$hostcomments{$H}</td></tr>\n"
310         if ( $hostcomments{$H} );
311     $table .= $det if $pkgs;
312     print "\n$table\n" if $debug>2;
313     last if $H =~/diane/ && $debug;
314 }
315 $table .= "</table>\n";
316
317 # Save the date file
318 if ( ! $debug ) {
319     `mv -f $datefilename $dateoldfilename`;
320     open F, ">$datefilename" or die "Could not open date file $datefilename for writing";
321     for  my $k (sort(keys(%newdates)) ) {
322         print F "$k " . $newdates{$k}. "\n";
323         print "date for '$k' '" . $newdates{$k}. "'\n" if $debug;
324     }
325     close F
326       or die "Could not close date file $datefilename: $!";
327 } else {
328     print "Not updating the date file, this is a debug run\n";
329 }
330
331 # Page header
332 my $outfile = "/tmp/aptcheck.html";
333 open F, ">$outfile"
334     or die "Could not open $outfile for writing: $!";
335 print F "<html>\n";
336 print F "<head><title>Apt upgrade status</title></head>\n";
337 print F "<body>\n";
338 print F "<H1>Apt package status</H1>\n";
339 print F "<b>" .  ( $sectot + $owntot + $mantot + $normtot ) . 
340         "</b> packages pending (<b>$sectot</b> critical) \n";
341
342 print F "<H2>Debug run, many hosts missing!</H2>\n"
343    if $debug;
344
345
346 # Summary table: one row for per host group
347 print F "<p/>\n";
348 print F "<table border='1' >\n";
349 print F "<tr><td>&nbsp;</td>" ;
350 print F "<td><b>Hosts</b></td>\n";
351 print F "<td><b>Packages</b></td></tr>\n";
352
353 if ( $sectot ) {
354     print F "<tr><td><b>Security</b><br/>" . scalar(keys(%sechosts)) . 
355         "&nbsp;/&nbsp;" .  scalar(keys(%secpkgs)) . "&nbsp;/&nbsp;$sectot </td>\n" ;
356     print F "<td>";
357     for my $HH ( sort(keys(%sechosts)) ) {
358         my $upd = $updlinks{$HH} || "#" ;
359         print F "<a href='#$HH'><b>$HH</b></a><a href='$upd'>,</a> ";
360     }
361     print F "</td>";
362     print F "<td>";
363     for my $PP ( sort(keys(%secpkgs)) ) {
364         print F "<a href='#$PP'>$PP</a> ";
365     }
366     print F "</td>";
367     print F "</tr>\n";
368 }
369 if ( $owntot ) {
370     print F "<tr><td><b>Indexdata</b><br/>" . scalar(keys(%ownhosts)) . 
371         "&nbsp;/&nbsp;" .  scalar(keys(%ownpkgs)) . "&nbsp;/&nbsp;$owntot </td>\n" ;
372     print F "<td>";
373     for my $HH ( sort(keys(%ownhosts)) ) {
374         my $upd = $updlinks{$HH} || "#" ;
375         print F "<a href='#$HH'><b>$HH</b></a><a href='$upd'>,</a> ";
376         #print F "<a href='#$HH'><b>$HH</b></a> ";
377     }
378     print F "</td>";
379     print F "<td>";
380     for my $PP ( sort(keys(%ownpkgs)) ) {
381         print F "<a href='#$PP'>$PP</a> ";
382     }
383     print F "</td>";
384     print F "</tr>\n";
385 }
386 if ( $mantot ) {
387     print F "<tr><td><b>Manual</b><br/>" . scalar(keys(%manhosts)) . 
388         "&nbsp;/&nbsp;" .  scalar(keys(%manpkgs)) . "&nbsp;/&nbsp;$mantot </td>\n" ;
389     print F "<td>";
390     for my $HH ( sort(keys(%manhosts)) ) {
391         my $upd = $updlinks{$HH} || "#" ;
392         print F "<a href='#$HH'><b>$HH</b></a><a href='$upd'>,</a> ";
393         #print F "<a href='#$HH'><b>$HH</b></a> ";
394     }
395     print F "</td>";
396     print F "<td>";
397     for my $PP ( sort(keys(%manpkgs)) ) {
398         print F "<a href='#$PP'>$PP</a> ";
399     }
400     print F "</td>";
401     print F "</tr>\n";
402 }
403 if ( $normtot ) {
404     print F "<tr><td>Normal<br/>" . scalar(keys(%normhosts)) . 
405         "&nbsp;/&nbsp;" .  scalar(keys(%normpkgs)) . "&nbsp;/&nbsp;$normtot </td>\n" ;
406     print F "<td>";
407     for my $HH ( sort(keys(%normhosts)) ) {
408         my $upd = $updlinks{$HH} || "#" ;
409         print F "<a href='#$HH'><b>$HH</b></a><a href='$upd'>,</a> ";
410         #print F "<a href='#$HH'><b>$HH</b></a> ";
411     }
412     print F "</td>";
413     print F "<td>";
414     for my $PP ( sort(keys(%normpkgs)) ) {
415         print F "<a href='#$PP'>$PP</a> ";
416     }
417     print F "</td>";
418     print F "</tr>\n";
419 }
420 if ( %skiphosts ) {
421     print F "<tr><td>Skipped " . scalar(keys(%skiphosts)) . "</td>\n";
422     print F "<td colspan='2'>";
423     for my $HH ( sort(keys(%skiphosts)) ) {
424         my $upd = $updlinks{$HH} ||
425                   $wikilink . ucfirst($HH) . "Updates" . $year;
426         print F "<a href='#$HH'><b>$HH</b></a><a href='$upd'>,</a> ";
427         #print F "<a href='#$HH'><b>$HH</b></a> ";
428     }
429     print F "</td></tr>\n";
430 }
431 #if ( %okhosts ) {
432 if ( 1 ) {
433     print F "<tr><td>Ok " . scalar(keys(%okhosts)) . "</td>\n";
434     print F "<td colspan='2'>";
435     for my $HH ( sort(keys(%okhosts)) ) {
436         my $upd = $updlinks{$HH} || "#" ;
437         print F "<a href='#$HH'><b>$HH</b></a><a href='$upd'>,</a> ";
438         #print F "<a href='#$HH'><b>$HH</b></a> ";
439     }
440     if ( !%okhosts ) {
441         print F "<b>None at all!</b>";
442     }
443     print F "</td></tr>\n";
444 }
445 print F "</table>\n";
446
447 print F "<p/><b>" .  ( $sectot + $owntot + $mantot + $normtot ) . 
448         "</b> packages pending (<b>$sectot</b> critical) \n";
449
450 # Graph 
451 #my $secs = 60*60*24 * 7 * 2; # 2 weeks in secods
452 #my $secs = "1m"; # one month, let nagios do the math
453 my $secs = "45d"; 
454 print F "<p/>" .
455         "<a href='http://nagios.indexdata.com/cgi-bin/nagios3/graphs.cgi?" .
456         "host=nagios&service=Apt%20Summary'>\n".
457         "<img src='http://nagios.indexdata.com/" .
458               "cgi-bin/nagios3/rrd2-system.cgi?" .
459               "host=nagios&service=Apt%20Summary&" .
460               "start=-$secs&" .
461               "width=800&height=100&type=AVERAGE' /> ".
462         "</a>" .
463         "<br/>\n";
464
465 # The host table
466 print F $table;
467
468 # Package table
469 print F "<p/><b><u>Packages</u></b>\n";
470 print F "<table>\n";
471 for my $P ( sort(keys(%summary)) ) {
472     my $PN = $P;
473     $PN = "<b>$P&nbsp;(s)</b>" if ($secpkgs{$P});
474     $PN = "<i>$P&nbsp;(id)</i>" if ($ownpkgs{$P});
475     $PN = "$P&nbsp;<b>(M)</b>" if ($manpkgs{$P});
476     print F "<tr><td><a name='$P'/>$PN</td>\n";
477     print F "<td>";
478     for my $HH ( split(' ',$summary{$P} )) {
479         print F "<a href=#$HH>$HH</a> ";
480     }
481     print F "</td>\n";
482
483 }
484 print F "</table>\n";
485
486 print F "<p/>Produced " . `date`.
487         " on " . `hostname` . " by " . `whoami` .
488         "<br/>\n";
489 print F "</body></html>\n";
490
491 close(F)
492     or die "Could not close $outfile: $!";
493
494 system "scp -q $outfile nagios:/var/www/heikki/index.html";
495
496 exit(0);
497
498 # Helper to take two strings and highligt that part of the second
499 # that is different from the first. 
500 sub strdiff {
501     my $x = shift;
502     my $y = shift;
503     print "strdiff: '$x' '$y' \n" if $debug>2;
504     if ( $x eq $y ) {
505         return "$x <b>??</b>";
506     }
507     my $a = 0;
508     while ( $a < length($y) &&
509         substr($x,$a,1) eq substr($y,$a,1) ) {
510         $a++;
511     }
512     if ( $a == length($y) ) {
513         return "$y";
514     }
515     my $b = 1;
516     while ( $b < length($y)-$a &&
517         substr($x,-$b,1) eq substr($y, -$b,1) ) {
518         $b++;
519     }
520     my $c = length($y) - $b +1;
521     print "strdiff:   a=$a " . substr($y,0,$a) ."\n" if $debug>2;
522     print "strdiff:   b=$b " . "\n" if $debug>2;
523     print "strdiff:   c=$c " . substr($y,$c) ."\n" if $debug>2;
524     print "strdiff:        " . substr($y,$a, $c-$a) ."\n" if $debug>2;
525     my $z =  substr($y,0,$a) .
526              "<b>" . substr($y,$a, $c-$a) . "</b>" .
527              substr($y,$c);
528     print "strdiff:        " . $z ."\n" if $debug>2;
529     print "\n" if $debug>2;
530     return $z;
531 }