Linux – Why does apt autoremove not remove all old kernel packages at once

aptlinux-kernel

I have been upgrading the kernel of our Ubuntu servers since they released a patch for the Meltdown vulnerability. I noticed that pretty much on all the servers, after I reboot I have to run apt autoremove twice for it to clean up all the old kernels that are still on the system.

If I run it the first time, it removes two old versions of the kernel at first:

% sudo apt autoremove
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages will be REMOVED:
  linux-headers-4.4.0-103 linux-headers-4.4.0-103-generic linux-headers-4.4.0-104 linux-headers-4.4.0-104-generic linux-image-4.4.0-103-generic linux-image-4.4.0-104-generic
  linux-image-extra-4.4.0-103-generic linux-image-extra-4.4.0-104-generic
0 upgraded, 0 newly installed, 8 to remove and 2 not upgraded.
After this operation, 596 MB disk space will be freed.

But then, after it is done and I run apt autoremove again, it removes yet an older version:

% sudo apt autoremove
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages will be REMOVED:
  linux-headers-4.4.0-96 linux-headers-4.4.0-96-generic linux-image-4.4.0-96-generic linux-image-extra-4.4.0-96-generic
0 upgraded, 0 newly installed, 4 to remove and 2 not upgraded.
After this operation, 298 MB disk space will be freed.

I am wondering, why can it not do this in one run?

Best Answer

The kernel’s maintainer scripts, specifically /etc/kernel/postinst.d/apt-auto-removal, build a list of kernels to keep, stored as APT configuration in /etc/apt/apt.conf.d/01autoremove-kernels. This process keeps the currently running kernel, the kernel being configured, and the two latest installed kernels.

Presumably the last time the script was run before your first clean-up, -96 ended up protected because it fell into one of those categories. After your first clean-up it no longer did and became a candidate for removal. If you want to figure out why, the 01autoremove-kernels file contains debug information; looking at it before the first clean-up, and again after, should reveal why various kernel versions are protected.

Kernel auto-removal is purposefully conservative and errs on the side of caution. You can deal with this automatically (eventually) using unattended-upgrades; see the Ubuntu wiki for details.

Related Question