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