27#include <unordered_map>
28#include <sys/utsname.h>
33#undef ZYPP_BASE_LOGGER_LOGGROUP
34#define ZYPP_BASE_LOGGER_LOGGROUP "PurgeKernels"
57 using GroupMap = std::unordered_map<std::string, GroupInfo>;
62 struct utsname unameData;
63 if ( uname( &unameData) == 0 ) {
68 setUnameR( std::string( unameData.release ) );
74 MIL <<
"Edition variant: " << edVar <<
"\n";
78 MIL <<
"Failed to detect running kernel: " << errno << std::endl;
86 MIL <<
"Set uname " << uname << std::endl;
96 auto makeRcVariant = [ &release ]( std::string myVersion,
const std::string &replace ){
101 return Edition( myVersion, release );
110 MIL <<
"Parsed info from uname: " << std::endl;
112 MIL <<
"Kernel Edition Variants: \n";
114 MIL <<
" " << var <<
"\n";
121 void fillKeepList(
const GroupMap &installedKernels, std::set<sat::Solvable> &keepList , std::set<sat::Solvable> &removeList )
const;
153 if ( !
pool.resolver().resolvePool() ) {
154 MIL <<
"Pool failed to resolve, not doing anything" << std::endl;
158 MIL <<
"Request to remove package: " << pi << std::endl;
166 const str::regex validRemovals(
"(kernel-syms(-.*)?|kgraft-patch(-.*)?|kernel-(.*)-livepatch(-.*)?|kernel-livepatch(-.*)?|kernel-.+-uki-.+-[0-9].*|.*-kmp(-.*)?)");
169 MIL <<
"Package " << pi <<
" is locked by the user, not removing." << std::endl;
174 std::set<sat::Solvable> currentSetOfRemovals;
175 for (
const PoolItem & p :
pool.byStatus( toBeUninstalledFilter ) ) {
176 currentSetOfRemovals.insert( p.satSolvable() );
181 if ( !
pool.resolver().resolvePool() ) {
182 MIL <<
"Failed to resolve pool, skipping " << pi << std::endl;
183 pool.resolver().problems();
189 std::set<sat::Solvable> removedInThisRun;
190 removedInThisRun.insert( slv );
192 for (
const PoolItem & p :
pool.byStatus( toBeUninstalledFilter ) ) {
195 if ( p.status().isByUser()
196 || (currentSetOfRemovals.find( p.satSolvable() ) != currentSetOfRemovals.end())
201 removedInThisRun.insert( p.satSolvable() );
203 MIL <<
"Package " << p <<
" was marked by the solver for removal." << std::endl;
206 if ( removeList.find( p.satSolvable() ) != removeList.end() )
209 if ( keepList.find( p.satSolvable() ) != keepList.end() ) {
210 MIL <<
"Package " << p <<
" is in keep spec, skipping" << pi << std::endl;
225 bool mostLikelyKmod =
false;
228 for (
const auto &prov : p.dep_provides() ) {
229 if ( matchMod.
doMatch( prov.detail().name().c_str()) || matchSym.
doMatch( prov.detail().name().c_str() ) ) {
230 mostLikelyKmod =
true;
235 if ( mostLikelyKmod ) {
236 MIL <<
"Package " << p <<
" is most likely a kmod " << std::endl;
240 MIL <<
"Package " << p <<
" should not be removed, skipping " << pi << std::endl;
247 MIL <<
"Successfully marked package: " << pi <<
" for removal."<<std::endl;
250 MIL <<
"Trying to remove debuginfo for: " << pi <<
"."<<std::endl;
253 if ( solvable.arch() == Arch_noarch ||
257 for (
const char * suffix : {
"-debugsource",
"-debuginfo" } ) {
266 if ( debugPackage.arch() != solvable.arch() )
269 MIL <<
"Found debug package for " << solvable <<
" : " << debugPackage << std::endl;
275 MIL <<
"Finished removing debuginfo for: " << pi <<
"."<<std::endl;
291 std::string versionStr =
b.asString();
293 if ( buildCntRegex.
matches( versionStr.data(), matches ) ) {
294 if ( matches.
size() >= 2 ) {
295 versionStr.replace( matches.
begin(0), (matches.
end(0) - matches.
begin(0))+1, matches[1] );
310 const unsigned tokenGrp = 1;
311 const unsigned modifierGrp = 2;
316 std::vector<std::string> words;
318 if ( words.empty() ) {
319 WAR <<
"Invalid keep spec: " <<
_keepSpec <<
" using default latest,running." << std::endl;
327 for (
const std::string &word : words ) {
328 if ( word ==
"running" ) {
335 std::string_view edition(word);
336 const auto firstDash = word.find_first_of (
'-');
337 if ( firstDash != std::string::npos ) {
338 const auto secondDash = word.find_first_of (
'-', firstDash+1 );
339 if ( secondDash != std::string::npos ) {
340 WAR <<
"Ignoring possible flavor postfix:'"<< word.substr (secondDash) <<
"' in keep spec: " << word << std::endl;
341 edition = std::string_view( word.c_str (), secondDash );
348 auto addKeepOff = [](
const auto &off,
auto &set,
const auto &constraint ){
350 if ( !constraint(num) )
return false;
351 set.insert(
static_cast<size_t>(std::abs(num)) );
355 if ( what[tokenGrp] ==
"oldest" ) {
358 WAR <<
"Ignoring invalid modifier in keep spec: " << word <<
", oldest supports only positive modifiers." << std::endl;
366 WAR <<
"Ignoring invalid modifier in keep spec: " << word <<
", latest supports only negative modifiers." << std::endl;
388 const auto markAsKeep = [ &keepList, &removeList ](
sat::Solvable pck ) {
389 MIL <<
"Marking package " << pck <<
" as to keep." << std::endl;
390 keepList.insert( pck ) ;
391 removeList.erase( pck );
394 const auto versionPredicate = [](
const auto &editionVariants ){
395 return [ &editionVariants ](
const auto &elem ) {
396 const auto &f = std::bind(
versionMatch, _1, elem.first );
397 return std::any_of( editionVariants.begin(), editionVariants.end(), f );
401 for (
const auto &groupInfo : installedKernels ) {
403 MIL <<
"Starting with group " << groupInfo.first << std::endl;
405 for (
const auto &archMap : groupInfo.second.archToEdMap ) {
407 MIL <<
"Starting with arch " << archMap.first << std::endl;
410 size_t currROff = archMap.second.size() - 1;
425 auto it = std::find_if( map.begin(), map.end(), editionPredicate );
426 if ( it == map.end() ) {
432 MIL <<
" Possible Variant:" << var <<
"\n";
433 MIL <<
"Not installed! \n";
436 for (
const auto &kernelMap : map ) {
445 MIL <<
"Found possible running candidate edition: " << it->first << std::endl;
447 for ( nit++ ; nit != map.end() && editionPredicate( *nit ) ; nit++ ) {
448 MIL <<
"Found possible more recent running candidate edition: " << nit->first << std::endl;
454 if ( it != map.end() ) {
461 for (
const auto &kernelMap : map ) {
464 std::for_each( kernelMap.second.begin(), kernelMap.second.end(), markAsKeep );
472 std::for_each( kernelMap.second.begin(), kernelMap.second.end(), [ & ](
sat::Solvable solv ){
473 for ( Capability prov : solv.dep_provides() ) {
474 if ( prov.detail().name() == solv.name() && _keepSpecificEditions.count( prov.detail().ed() ) ) {
493 MIL << std::endl <<
"--------------------- Starting to mark obsolete kernels ---------------------"<<std::endl;
496 WAR <<
"Keep spec is empty, removing nothing." << std::endl;
503 WAR <<
"Unable to detect running kernel, but keeping the running kernel was requested. Not removing any packages." << std::endl;
508 pool.resolver().setForceResolve(
true );
513 const str::regex kernelFlavourRegex(
"^kernel-(.*)$");
521 std::set<sat::Solvable> packagesToRemove;
523 const auto addPackageToMap = [&installedKrnlPackages, &packagesToRemove] (
const GroupInfo::GroupType type,
const std::string &ident,
const std::string &flavour,
const sat::Solvable &installedKrnlPck ) {
525 if ( !installedKrnlPackages.count( ident ) )
526 installedKrnlPackages.insert( std::make_pair( ident,
GroupInfo(type, flavour) ) );
528 auto &groupInfo = installedKrnlPackages[ ident ];
529 if ( groupInfo.groupType != type || groupInfo.groupFlavour != flavour ) {
530 ERR <<
"Got inconsistent type and flavour for ident this is a BUG: " << ident << std::endl
531 <<
"Original Flavour-Type: "<<groupInfo.groupFlavour<<
"-"<<groupInfo.groupType << std::endl
532 <<
"Competing Flavour-Type: "<< flavour <<
"-" << type << std::endl;
535 const auto currArch = installedKrnlPck.arch();
536 if ( !groupInfo.archToEdMap.count( currArch ) )
539 auto &editionToSolvableMap = groupInfo.archToEdMap[ currArch ];
545 auto currCount = INT_MAX;
547 for (
Capability prov : installedKrnlPck.dep_provides() ) {
548 if ( prov.detail().name() == installedKrnlPck.name() ) {
550 edToUse = installedKrnlPck.edition();
551 const auto &relStr = edToUse.
release();
552 currCount = std::count( relStr.begin(), relStr.end(),
'.');
554 const auto &pckEd = prov.detail().ed();
555 const auto &relStr = pckEd.release();
556 if (
const auto pntCnt = std::count( relStr.begin(), relStr.end(),
'.'); pntCnt < currCount ) {
564 if ( !editionToSolvableMap.count( edToUse ) )
565 editionToSolvableMap.insert( std::make_pair( edToUse,
SolvableList{} ) );
567 editionToSolvableMap[edToUse].push_back( installedKrnlPck );
570 packagesToRemove.insert( installedKrnlPck );
574 std::set<sat::Solvable> packagesToKeep;
583 MIL <<
"Searching for obsolete multiversion kernel packages." << std::endl;
587 MIL <<
"Found installed multiversion kernel package " << installedKrnlPck << std::endl;
589 if ( installedKrnlPck.dep_provides().matches(
Capability(
"kernel-uname-r")) ) {
590 MIL <<
"Identified as a kernel package " << std::endl;
595 if ( what[1].empty() ) {
596 WAR <<
"Could not detect flavour for: " << installedKrnlPck <<
" ...skipping" << std::endl;
600 std::string flavour = what[1];
603 const auto dash = flavour.find_first_of(
'-');
604 if ( dash != std::string::npos ) {
605 flavour = flavour.substr( 0, dash );
614 const str::regex explicitlyHandled(
"kernel-syms(-.*)?|kernel(-.*)?-devel");
616 MIL <<
"Not a kernel package, inspecting more closely " << std::endl;
619 if ( installedKrnlPck.arch() == Arch_noarch ) {
621 MIL <<
"Handling package explicitly due to architecture (noarch)."<< std::endl;
633 if ( match.size() > 1 && match[1].size() )
634 flav = match[1].substr(1);
636 else if ( match.size() > 2 && match[2].size() )
637 flav = match[2].substr(1);
638 else if ( installedKrnlPck.name() ==
"kernel-syms" )
641 MIL <<
"Handling package explicitly due to name match."<< std::endl;
644 MIL <<
"Package not explicitly handled" << std::endl;
650 MIL <<
"Grouped packages: " << std::endl;
651 std::for_each( installedKrnlPackages.begin(), installedKrnlPackages.end(),[](
const auto &ident ){
652 MIL <<
"\tGroup ident: "<<ident.first<<std::endl;
653 MIL <<
"\t Group type: "<<ident.second.groupType<<std::endl;
654 MIL <<
"\t Group flav: "<<ident.second.groupFlavour<<std::endl;
655 std::for_each( ident.second.archToEdMap.begin(), ident.second.archToEdMap.end(), []( const auto &arch) {
656 MIL <<
"\t\tArch: "<<arch.first<<std::endl;
657 std::for_each( arch.second.begin(), arch.second.end(), []( const auto &edition) {
658 MIL <<
"\t\t\tEdition: "<<edition.first<<std::endl;
659 std::for_each( edition.second.begin(), edition.second.end(), []( const auto &packageId) {
660 MIL <<
"\t\t\t\t "<<sat::Solvable(packageId)<<std::endl;
666 _pimpl->fillKeepList( installedKrnlPackages, packagesToKeep, packagesToRemove );
669 _pimpl->removePackageAndCheck( slv, packagesToKeep, packagesToRemove );
Arch()
Default ctor Arc_noarch.
Capability()
Default ctor, Empty capability.
Edition represents [epoch:]version[-release].
Edition()
Default ctor: noedition.
std::string release() const
Release.
static const Edition noedition
Value representing noedition ("") This is in fact a valid Edition.
constexpr IdString()
Default ctor, empty string.
Combining sat::Solvable and ResStatus.
ResStatus & status() const
Returns the current status.
ResStatus & statusReset() const
Resets status to the default state (KEEP_STATE bySOLVER; clears any lock!).
void setMatchExact()
Set to match exact string instead of substring.
void addKind(const ResKind &kind)
Filter by selectable kind.
void addAttribute(const sat::SolvAttr &attr, const std::string &value="")
Filter by the value of the specified attr attribute.
void setInstalledOnly()
Return only @System repo packages.
void addDependency(const sat::SolvAttr &attr, const std::string &name, const Rel &op, const Edition &edition)
Query "name|global op edition".
std::string unameR() const
void setKeepSpec(const std::string &val)
std::string keepSpec() const
void setUnameR(const std::string &val)
RW_pointer< Impl > _pimpl
void setKernelArch(const zypp::Arch &arch)
void markObsoleteKernels()
static const ResKind package
static ResPool instance()
Singleton ctor.
bool setToBeUninstalled(TransactByValue causer)
bool isToBeUninstalled() const
String matching (STRING|SUBSTRING|GLOB|REGEX).
bool doMatch(const char *string_r) const
Return whether string matches.
static ZConfig & instance()
Singleton ctor.
std::string multiversionKernels() const
Filter solvables according to their status.
static const SolvAttr dep_provides
A Solvable object within the sat Pool.
@ match_extended
Use POSIX Extended Regular Expression syntax when interpreting regex.
bool matches(const char *s, str::smatch &matches, int flags=none) const
Regular expression match result.
std::string::size_type end(unsigned i) const
End index of subexpression i in match_str (or std::string::npos).
std::string::size_type begin(unsigned i) const
Begin index of subexpression i in match_str (or std::string::npos).
bool regex_match(const char *s, smatch &matches, const regex ®ex) ZYPP_API
Regular expression matching.
unsigned split(const C_Str &line_r, TOutputIterator result_r, const C_Str &sepchars_r=" \t", const Trim trim_r=NO_TRIM)
Split line_r into words.
TInt strtonum(const C_Str &str)
Parsing numbers from string.
std::string regex_substitute(const std::string &s, const regex ®ex, const std::string &replacement, bool global=true) ZYPP_API
Replaces the matched regex with the string passed in replacement.
Easy-to use interface to the ZYPP dependency resolver.
std::map< Arch, EditionToSolvableMap > ArchToEditionMap
const Arch Arch_empty(IdString::Empty)
std::unordered_map< std::string, GroupInfo > GroupMap
std::list< sat::Solvable > SolvableList
std::map< Edition, SolvableList > EditionToSolvableMap
enum zypp::GroupInfo::GroupType groupType
ArchToEditionMap archToEdMap
GroupInfo(const GroupType type=None, std::string flav="")
static bool versionMatch(const Edition &a, const Edition &b)
std::set< Edition > _keepSpecificEditions
bool removePackageAndCheck(const sat::Solvable slv, const std::set< sat::Solvable > &keepList, const std::set< sat::Solvable > &removeList) const
std::set< Edition > _runningKernelEditionVariants
std::set< size_t > _keepLatestOffsets
void setUnameR(const std::string &uname)
std::set< size_t > _keepOldestOffsets
void fillKeepList(const GroupMap &installedKernels, std::set< sat::Solvable > &keepList, std::set< sat::Solvable > &removeList) const
Flavour _runningKernelFlavour