From a6e30cc02eb24d5b2bbf2cb1b59c48c62d09658f Mon Sep 17 00:00:00 2001 From: Wesley Schwengle Date: Tue, 23 Jan 2024 15:41:33 -0400 Subject: Configure the amount of kernels to keep This commit introduces the following configuration for keeping a configurable amount of kernels: APT::NeverAutoRemove::KernelCount The logic dictates that the running kernel and the latest kernel are not autoremoved. In case the running kernel is the latest kernel, the previous kernel is kept. Any count lower than two is therefore disregarded. This is in line with the previous behavior. The default is therefore similar to: APT::NeverAutoRemove::KernelCount 2; This will be ignored and we will still keep two: APT::NeverAutoRemove::KernelCount 1; This will keep 3 kernels (including the runnig, and most recent) APT::NeverAutoRemove::KernelCount 3; Signed-off-by: Wesley Schwengle --- apt-pkg/algorithms.cc | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) (limited to 'apt-pkg') diff --git a/apt-pkg/algorithms.cc b/apt-pkg/algorithms.cc index 3d4096a94..0d9b50e2c 100644 --- a/apt-pkg/algorithms.cc +++ b/apt-pkg/algorithms.cc @@ -1554,30 +1554,37 @@ std::string GetProtectedKernelsRegex(pkgCache *cache, bool ReturnRemove) if (version2unames.size() == 0) return ""; - auto latest = version2unames.rbegin(); - auto previous = latest; - ++previous; - + auto versions = version2unames.rbegin(); std::set keep; + auto keepKernels = (unsigned long)_config->FindI("APT::NeverAutoRemove::KernelCount", 2); + if (keepKernels < 2) + keepKernels = 2; + + if (Debug) + std::clog << "Amount of kernels to keep " << keepKernels << std::endl; + if (not bootedVersion.empty()) { if (Debug) std::clog << "Keeping booted kernel " << bootedVersion << std::endl; keep.insert(bootedVersion); } - if (latest != version2unames.rend()) - { - if (Debug) - std::clog << "Keeping latest kernel " << latest->first << std::endl; - keep.insert(latest->first); - } - if (keep.size() < 2 && previous != version2unames.rend()) + + while (keep.size() < keepKernels && versions != version2unames.rend()) { + auto v = versions->first; + if (v == bootedVersion) + { + versions++; + continue; + } if (Debug) - std::clog << "Keeping previous kernel " << previous->first << std::endl; - keep.insert(previous->first); + std::clog << "Keeping previous kernel " << v << std::endl; + keep.insert(v); + versions++; } + // Escape special characters '.' and '+' in version strings so we can build a regular expression auto escapeSpecial = [](std::string input) -> std::string { for (size_t pos = 0; (pos = input.find_first_of(".+", pos)) != input.npos; pos += 2) { -- cgit v1.2.3-70-g09d2