1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/target/TargetImpl.cc
19 #include <sys/types.h>
22 #include "zypp/base/LogTools.h"
23 #include "zypp/base/Exception.h"
24 #include "zypp/base/Iterator.h"
25 #include "zypp/base/Gettext.h"
26 #include "zypp/base/IOStream.h"
27 #include "zypp/base/Functional.h"
28 #include "zypp/base/UserRequestException.h"
29 #include "zypp/base/Json.h"
31 #include "zypp/ZConfig.h"
32 #include "zypp/ZYppFactory.h"
34 #include "zypp/PoolItem.h"
35 #include "zypp/ResObjects.h"
37 #include "zypp/TmpPath.h"
38 #include "zypp/RepoStatus.h"
39 #include "zypp/ExternalProgram.h"
40 #include "zypp/Repository.h"
42 #include "zypp/ResFilters.h"
43 #include "zypp/HistoryLog.h"
44 #include "zypp/target/TargetImpl.h"
45 #include "zypp/target/TargetCallbackReceiver.h"
46 #include "zypp/target/rpm/librpmDb.h"
47 #include "zypp/target/CommitPackageCache.h"
48 #include "zypp/target/RpmPostTransCollector.h"
50 #include "zypp/parser/ProductFileReader.h"
51 #include "zypp/repo/SrcPackageProvider.h"
53 #include "zypp/sat/Pool.h"
54 #include "zypp/sat/detail/PoolImpl.h"
55 #include "zypp/sat/Transaction.h"
57 #include "zypp/PluginExecutor.h"
61 ///////////////////////////////////////////////////////////////////
64 /////////////////////////////////////////////////////////////////
67 // HACK for bnc#906096: let pool re-evaluate multiversion spec
68 // if target root changes. ZConfig returns data sensitive to
69 // current target root.
70 inline void sigMultiversionSpecChanged()
72 sat::detail::PoolMember::myPool().multiversionSpecChanged();
75 /////////////////////////////////////////////////////////////////
77 ///////////////////////////////////////////////////////////////////
80 // Lazy via template specialisation / should switch to overloading
83 inline std::string toJSON( const ZYppCommitResult::TransactionStepList & steps_r )
85 using sat::Transaction;
88 for ( const Transaction::Step & step : steps_r )
89 // ignore implicit deletes due to obsoletes and non-package actions
90 if ( step.stepType() != Transaction::TRANSACTION_IGNORE )
96 /** See \ref commitbegin on page \ref plugin-commit for the specs. */
98 inline std::string toJSON( const sat::Transaction::Step & step_r )
100 static const std::string strType( "type" );
101 static const std::string strStage( "stage" );
102 static const std::string strSolvable( "solvable" );
104 static const std::string strTypeDel( "-" );
105 static const std::string strTypeIns( "+" );
106 static const std::string strTypeMul( "M" );
108 static const std::string strStageDone( "ok" );
109 static const std::string strStageFailed( "err" );
111 static const std::string strSolvableN( "n" );
112 static const std::string strSolvableE( "e" );
113 static const std::string strSolvableV( "v" );
114 static const std::string strSolvableR( "r" );
115 static const std::string strSolvableA( "a" );
117 using sat::Transaction;
120 switch ( step_r.stepType() )
122 case Transaction::TRANSACTION_IGNORE: /*empty*/ break;
123 case Transaction::TRANSACTION_ERASE: ret.add( strType, strTypeDel ); break;
124 case Transaction::TRANSACTION_INSTALL: ret.add( strType, strTypeIns ); break;
125 case Transaction::TRANSACTION_MULTIINSTALL: ret.add( strType, strTypeMul ); break;
128 switch ( step_r.stepStage() )
130 case Transaction::STEP_TODO: /*empty*/ break;
131 case Transaction::STEP_DONE: ret.add( strStage, strStageDone ); break;
132 case Transaction::STEP_ERROR: ret.add( strStage, strStageFailed ); break;
139 if ( sat::Solvable solv = step_r.satSolvable() )
141 ident = solv.ident();
147 // deleted package; post mortem data stored in Transaction::Step
148 ident = step_r.ident();
149 ed = step_r.edition();
150 arch = step_r.arch();
154 { strSolvableN, ident.asString() },
155 { strSolvableV, ed.version() },
156 { strSolvableR, ed.release() },
157 { strSolvableA, arch.asString() }
159 if ( Edition::epoch_t epoch = ed.epoch() )
160 s.add( strSolvableE, epoch );
162 ret.add( strSolvable, s );
168 ///////////////////////////////////////////////////////////////////
170 ///////////////////////////////////////////////////////////////////
173 ///////////////////////////////////////////////////////////////////
176 SolvIdentFile::Data getUserInstalledFromHistory( const Pathname & historyFile_r )
178 SolvIdentFile::Data onSystemByUserList;
179 // go and parse it: 'who' must constain an '@', then it was installed by user request.
180 // 2009-09-29 07:25:19|install|lirc-remotes|0.8.5-3.2|x86_64|root@opensuse|InstallationImage|a204211eb0...
181 std::ifstream infile( historyFile_r.c_str() );
182 for( iostr::EachLine in( infile ); in; in.next() )
184 const char * ch( (*in).c_str() );
186 if ( *ch < '1' || '9' < *ch )
188 const char * sep1 = ::strchr( ch, '|' ); // | after date
192 // if logs an install or delete
193 bool installs = true;
194 if ( ::strncmp( sep1, "install|", 8 ) )
196 if ( ::strncmp( sep1, "remove |", 8 ) )
197 continue; // no install and no remove
199 installs = false; // remove
201 sep1 += 8; // | after what
202 // get the package name
203 const char * sep2 = ::strchr( sep1, '|' ); // | after name
204 if ( !sep2 || sep1 == sep2 )
206 (*in)[sep2-ch] = '\0';
207 IdString pkg( sep1 );
208 // we're done, if a delete
211 onSystemByUserList.erase( pkg );
214 // now guess whether user installed or not (3rd next field contains 'user@host')
215 if ( (sep1 = ::strchr( sep2+1, '|' )) // | after version
216 && (sep1 = ::strchr( sep1+1, '|' )) // | after arch
217 && (sep2 = ::strchr( sep1+1, '|' )) ) // | after who
219 (*in)[sep2-ch] = '\0';
220 if ( ::strchr( sep1+1, '@' ) )
223 onSystemByUserList.insert( pkg );
228 MIL << "onSystemByUserList found: " << onSystemByUserList.size() << endl;
229 return onSystemByUserList;
232 ///////////////////////////////////////////////////////////////////
234 ///////////////////////////////////////////////////////////////////
237 inline PluginFrame transactionPluginFrame( const std::string & command_r, ZYppCommitResult::TransactionStepList & steps_r )
239 return PluginFrame( command_r, json::Object {
240 { "TransactionStepList", steps_r }
244 ///////////////////////////////////////////////////////////////////
246 /** \internal Manage writing a new testcase when doing an upgrade. */
247 void writeUpgradeTestcase()
249 unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
250 MIL << "Testcases to keep: " << toKeep << endl;
253 Target_Ptr target( getZYpp()->getTarget() );
256 WAR << "No Target no Testcase!" << endl;
260 std::string stem( "updateTestcase" );
261 Pathname dir( target->assertRootPrefix("/var/log/") );
262 Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
265 std::list<std::string> content;
266 filesystem::readdir( content, dir, /*dots*/false );
267 std::set<std::string> cases;
268 for_( c, content.begin(), content.end() )
270 if ( str::startsWith( *c, stem ) )
273 if ( cases.size() >= toKeep )
275 unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
276 for_( c, cases.begin(), cases.end() )
278 filesystem::recursive_rmdir( dir/(*c) );
285 MIL << "Write new testcase " << next << endl;
286 getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
289 ///////////////////////////////////////////////////////////////////
291 { /////////////////////////////////////////////////////////////////
293 /** Execute script and report against report_r.
294 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
295 * execution was successfull (<tt>first = true</tt>), or the desired
296 * \c PatchScriptReport::Action in case execution failed
297 * (<tt>first = false</tt>).
299 * \note The packager is responsible for setting the correct permissions
300 * of the script. If the script is not executable it is reported as an
301 * error. We must not modify the permessions.
303 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
304 const Pathname & script_r,
305 callback::SendReport<PatchScriptReport> & report_r )
307 MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
309 HistoryLog historylog;
310 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
311 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
313 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
315 historylog.comment(output);
316 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
318 WAR << "User request to abort script " << script_r << endl;
320 // the rest is handled by exit code evaluation
321 // in case the script has meanwhile finished.
325 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
327 if ( prog.close() != 0 )
329 ret.second = report_r->problem( prog.execError() );
330 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
331 std::ostringstream sstr;
332 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
333 historylog.comment(sstr.str(), /*timestamp*/true);
342 /** Execute script and report against report_r.
343 * Return \c false if user requested \c ABORT.
345 bool executeScript( const Pathname & root_r,
346 const Pathname & script_r,
347 callback::SendReport<PatchScriptReport> & report_r )
349 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
352 action = doExecuteScript( root_r, script_r, report_r );
354 return true; // success
356 switch ( action.second )
358 case PatchScriptReport::ABORT:
359 WAR << "User request to abort at script " << script_r << endl;
360 return false; // requested abort.
363 case PatchScriptReport::IGNORE:
364 WAR << "User request to skip script " << script_r << endl;
365 return true; // requested skip.
368 case PatchScriptReport::RETRY:
371 } while ( action.second == PatchScriptReport::RETRY );
373 // THIS is not intended to be reached:
374 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
375 return false; // abort.
378 /** Look for update scripts named 'name-version-release-*' and
379 * execute them. Return \c false if \c ABORT was requested.
381 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
383 bool RunUpdateScripts( const Pathname & root_r,
384 const Pathname & scriptsPath_r,
385 const std::vector<sat::Solvable> & checkPackages_r,
388 if ( checkPackages_r.empty() )
389 return true; // no installed packages to check
391 MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
392 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
393 if ( ! PathInfo( scriptsDir ).isDir() )
394 return true; // no script dir
396 std::list<std::string> scripts;
397 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
398 if ( scripts.empty() )
399 return true; // no scripts in script dir
401 // Now collect and execute all matching scripts.
402 // On ABORT: at least log all outstanding scripts.
403 // - "name-version-release"
404 // - "name-version-release-*"
406 std::map<std::string, Pathname> unify; // scripts <md5,path>
407 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
409 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
410 for_( sit, scripts.begin(), scripts.end() )
412 if ( ! str::hasPrefix( *sit, prefix ) )
415 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
416 continue; // if not exact match it had to continue with '-'
418 PathInfo script( scriptsDir / *sit );
419 Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
420 std::string unifytag; // must not stay empty
422 if ( script.isFile() )
424 // Assert it's set executable, unify by md5sum.
425 filesystem::addmod( script.path(), 0500 );
426 unifytag = filesystem::md5sum( script.path() );
428 else if ( ! script.isExist() )
430 // Might be a dangling symlink, might be ok if we are in
431 // instsys (absolute symlink within the system below /mnt).
432 // readlink will tell....
433 unifytag = filesystem::readlink( script.path() ).asString();
436 if ( unifytag.empty() )
440 if ( unify[unifytag].empty() )
442 unify[unifytag] = localPath;
446 // translators: We may find the same script content in files with different names.
447 // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
448 // message for a log file. Preferably start translation with "%s"
449 std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
450 MIL << "Skip update script: " << msg << endl;
451 HistoryLog().comment( msg, /*timestamp*/true );
455 if ( abort || aborting_r )
457 WAR << "Aborting: Skip update script " << *sit << endl;
458 HistoryLog().comment(
459 localPath.asString() + _(" execution skipped while aborting"),
464 MIL << "Found update script " << *sit << endl;
465 callback::SendReport<PatchScriptReport> report;
466 report->start( make<Package>( *it ), script.path() );
468 if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
469 abort = true; // requested abort.
476 ///////////////////////////////////////////////////////////////////
478 ///////////////////////////////////////////////////////////////////
480 inline void copyTo( std::ostream & out_r, const Pathname & file_r )
482 std::ifstream infile( file_r.c_str() );
483 for( iostr::EachLine in( infile ); in; in.next() )
485 out_r << *in << endl;
489 inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
491 std::string ret( cmd_r );
492 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
493 SUBST_IF( "%p", notification_r.solvable().asString() );
494 SUBST_IF( "%P", notification_r.file().asString() );
499 void sendNotification( const Pathname & root_r,
500 const UpdateNotifications & notifications_r )
502 if ( notifications_r.empty() )
505 std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
506 MIL << "Notification command is '" << cmdspec << "'" << endl;
507 if ( cmdspec.empty() )
510 std::string::size_type pos( cmdspec.find( '|' ) );
511 if ( pos == std::string::npos )
513 ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
514 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
518 std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
519 std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
521 enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
522 Format format = UNKNOWN;
523 if ( formatStr == "none" )
525 else if ( formatStr == "single" )
527 else if ( formatStr == "digest" )
529 else if ( formatStr == "bulk" )
533 ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
534 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
538 // Take care: commands are ececuted chroot(root_r). The message file
539 // pathnames in notifications_r are local to root_r. For physical access
540 // to the file they need to be prefixed.
542 if ( format == NONE || format == SINGLE )
544 for_( it, notifications_r.begin(), notifications_r.end() )
546 std::vector<std::string> command;
547 if ( format == SINGLE )
548 command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
549 str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
551 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
552 if ( true ) // Wait for feedback
554 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
558 int ret = prog.close();
561 ERR << "Notification command returned with error (" << ret << ")." << endl;
562 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
568 else if ( format == DIGEST || format == BULK )
570 filesystem::TmpFile tmpfile;
571 ofstream out( tmpfile.path().c_str() );
572 for_( it, notifications_r.begin(), notifications_r.end() )
574 if ( format == DIGEST )
576 out << it->file() << endl;
578 else if ( format == BULK )
580 copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
584 std::vector<std::string> command;
585 command.push_back( "<"+tmpfile.path().asString() ); // redirect input
586 str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
588 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
589 if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
591 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
595 int ret = prog.close();
598 ERR << "Notification command returned with error (" << ret << ")." << endl;
599 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
606 INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
607 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
613 /** Look for update messages named 'name-version-release-*' and
614 * send notification according to \ref ZConfig::updateMessagesNotify.
616 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
618 void RunUpdateMessages( const Pathname & root_r,
619 const Pathname & messagesPath_r,
620 const std::vector<sat::Solvable> & checkPackages_r,
621 ZYppCommitResult & result_r )
623 if ( checkPackages_r.empty() )
624 return; // no installed packages to check
626 MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
627 Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
628 if ( ! PathInfo( messagesDir ).isDir() )
629 return; // no messages dir
631 std::list<std::string> messages;
632 filesystem::readdir( messages, messagesDir, /*dots*/false );
633 if ( messages.empty() )
634 return; // no messages in message dir
636 // Now collect all matching messages in result and send them
637 // - "name-version-release"
638 // - "name-version-release-*"
639 HistoryLog historylog;
640 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
642 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
643 for_( sit, messages.begin(), messages.end() )
645 if ( ! str::hasPrefix( *sit, prefix ) )
648 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
649 continue; // if not exact match it had to continue with '-'
651 PathInfo message( messagesDir / *sit );
652 if ( ! message.isFile() || message.size() == 0 )
655 MIL << "Found update message " << *sit << endl;
656 Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
657 result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
658 historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
661 sendNotification( root_r, result_r.updateMessages() );
664 /////////////////////////////////////////////////////////////////
666 ///////////////////////////////////////////////////////////////////
668 void XRunUpdateMessages( const Pathname & root_r,
669 const Pathname & messagesPath_r,
670 const std::vector<sat::Solvable> & checkPackages_r,
671 ZYppCommitResult & result_r )
672 { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
674 ///////////////////////////////////////////////////////////////////
676 IMPL_PTR_TYPE(TargetImpl);
678 ///////////////////////////////////////////////////////////////////
680 // METHOD NAME : TargetImpl::TargetImpl
681 // METHOD TYPE : Ctor
683 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
685 , _requestedLocalesFile( home() / "RequestedLocales" )
686 , _autoInstalledFile( home() / "AutoInstalled" )
687 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
689 _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
691 HistoryLog::setRoot(_root);
694 sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
695 MIL << "Initialized target on " << _root << endl;
699 * generates a random id using uuidgen
701 static std::string generateRandomId()
703 std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
704 return iostr::getline( uuidprovider );
708 * updates the content of \p filename
709 * if \p condition is true, setting the content
710 * the the value returned by \p value
712 void updateFileContent( const Pathname &filename,
713 boost::function<bool ()> condition,
714 boost::function<string ()> value )
716 string val = value();
717 // if the value is empty, then just dont
718 // do anything, regardless of the condition
724 MIL << "updating '" << filename << "' content." << endl;
726 // if the file does not exist we need to generate the uuid file
728 std::ofstream filestr;
729 // make sure the path exists
730 filesystem::assert_dir( filename.dirname() );
731 filestr.open( filename.c_str() );
733 if ( filestr.good() )
740 // FIXME, should we ignore the error?
741 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
746 /** helper functor */
747 static bool fileMissing( const Pathname &pathname )
749 return ! PathInfo(pathname).isExist();
752 void TargetImpl::createAnonymousId() const
754 // bsc#1024741: Omit creating a new uid for chrooted systems (if it already has one, fine)
758 // Create the anonymous unique id, used for download statistics
759 Pathname idpath( home() / "AnonymousUniqueId");
763 updateFileContent( idpath,
764 boost::bind(fileMissing, idpath),
767 catch ( const Exception &e )
769 WAR << "Can't create anonymous id file" << endl;
774 void TargetImpl::createLastDistributionFlavorCache() const
776 // create the anonymous unique id
777 // this value is used for statistics
778 Pathname flavorpath( home() / "LastDistributionFlavor");
780 // is there a product
781 Product::constPtr p = baseProduct();
784 WAR << "No base product, I won't create flavor cache" << endl;
788 string flavor = p->flavor();
793 updateFileContent( flavorpath,
794 // only if flavor is not empty
795 functor::Constant<bool>( ! flavor.empty() ),
796 functor::Constant<string>(flavor) );
798 catch ( const Exception &e )
800 WAR << "Can't create flavor cache" << endl;
805 ///////////////////////////////////////////////////////////////////
807 // METHOD NAME : TargetImpl::~TargetImpl
808 // METHOD TYPE : Dtor
810 TargetImpl::~TargetImpl()
812 _rpm.closeDatabase();
813 sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
814 MIL << "Targets closed" << endl;
817 ///////////////////////////////////////////////////////////////////
819 // solv file handling
821 ///////////////////////////////////////////////////////////////////
823 Pathname TargetImpl::defaultSolvfilesPath() const
825 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
828 void TargetImpl::clearCache()
830 Pathname base = solvfilesPath();
831 filesystem::recursive_rmdir( base );
834 bool TargetImpl::buildCache()
836 Pathname base = solvfilesPath();
837 Pathname rpmsolv = base/"solv";
838 Pathname rpmsolvcookie = base/"cookie";
840 bool build_rpm_solv = true;
841 // lets see if the rpm solv cache exists
843 RepoStatus rpmstatus( RepoStatus(_root/"var/lib/rpm/Name") && RepoStatus(_root/"etc/products.d") );
845 bool solvexisted = PathInfo(rpmsolv).isExist();
848 // see the status of the cache
849 PathInfo cookie( rpmsolvcookie );
850 MIL << "Read cookie: " << cookie << endl;
851 if ( cookie.isExist() )
853 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
854 // now compare it with the rpm database
855 if ( status == rpmstatus )
856 build_rpm_solv = false;
857 MIL << "Read cookie: " << rpmsolvcookie << " says: "
858 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
862 if ( build_rpm_solv )
864 // if the solvfile dir does not exist yet, we better create it
865 filesystem::assert_dir( base );
867 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
869 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
872 // Can't create temporary solv file, usually due to insufficient permission
873 // (user query while @System solv needs refresh). If so, try switching
874 // to a location within zypps temp. space (will be cleaned at application end).
876 bool switchingToTmpSolvfile = false;
877 Exception ex("Failed to cache rpm database.");
878 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
880 if ( ! solvfilesPathIsTemp() )
882 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
883 rpmsolv = base/"solv";
884 rpmsolvcookie = base/"cookie";
886 filesystem::assert_dir( base );
887 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
891 WAR << "Using a temporary solv file at " << base << endl;
892 switchingToTmpSolvfile = true;
893 _tmpSolvfilesPath = base;
897 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
901 if ( ! switchingToTmpSolvfile )
907 // Take care we unlink the solvfile on exception
908 ManagedFile guard( base, filesystem::recursive_rmdir );
910 ExternalProgram::Arguments cmd;
911 cmd.push_back( "rpmdb2solv" );
912 if ( ! _root.empty() ) {
913 cmd.push_back( "-r" );
914 cmd.push_back( _root.asString() );
916 cmd.push_back( "-X" ); // autogenerate pattern/product/... from -package
917 cmd.push_back( "-A" ); // autogenerate application pseudo packages
918 cmd.push_back( "-p" );
919 cmd.push_back( Pathname::assertprefix( _root, "/etc/products.d" ).asString() );
921 if ( ! oldSolvFile.empty() )
922 cmd.push_back( oldSolvFile.asString() );
924 cmd.push_back( "-o" );
925 cmd.push_back( tmpsolv.path().asString() );
927 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
928 std::string errdetail;
930 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
931 WAR << " " << output;
932 if ( errdetail.empty() ) {
933 errdetail = prog.command();
939 int ret = prog.close();
942 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
943 ex.remember( errdetail );
947 ret = filesystem::rename( tmpsolv, rpmsolv );
949 ZYPP_THROW(Exception("Failed to move cache to final destination"));
950 // if this fails, don't bother throwing exceptions
951 filesystem::chmod( rpmsolv, 0644 );
953 rpmstatus.saveToCookieFile(rpmsolvcookie);
956 guard.resetDispose();
957 sat::updateSolvFileIndex( rpmsolv ); // content digest for zypper bash completion
959 // system-hook: Finally send notification to plugins
962 PluginExecutor plugins;
963 plugins.load( ZConfig::instance().pluginsPath()/"system" );
965 plugins.send( PluginFrame( "PACKAGESETCHANGED" ) );
970 // On the fly add missing solv.idx files for bash completion.
971 if ( ! PathInfo(base/"solv.idx").isExist() )
972 sat::updateSolvFileIndex( rpmsolv );
974 return build_rpm_solv;
977 void TargetImpl::reload()
982 void TargetImpl::unload()
984 Repository system( sat::Pool::instance().findSystemRepo() );
986 system.eraseFromPool();
989 void TargetImpl::load( bool force )
991 bool newCache = buildCache();
992 MIL << "New cache built: " << (newCache?"true":"false") <<
993 ", force loading: " << (force?"true":"false") << endl;
995 // now add the repos to the pool
996 sat::Pool satpool( sat::Pool::instance() );
997 Pathname rpmsolv( solvfilesPath() / "solv" );
998 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
1000 // Providing an empty system repo, unload any old content
1001 Repository system( sat::Pool::instance().findSystemRepo() );
1003 if ( system && ! system.solvablesEmpty() )
1005 if ( newCache || force )
1007 system.eraseFromPool(); // invalidates system
1011 return; // nothing to do
1017 system = satpool.systemRepo();
1022 MIL << "adding " << rpmsolv << " to system" << endl;
1023 system.addSolv( rpmsolv );
1025 catch ( const Exception & exp )
1028 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1032 system.addSolv( rpmsolv );
1034 satpool.rootDir( _root );
1036 // (Re)Load the requested locales et al.
1037 // If the requested locales are empty, we leave the pool untouched
1038 // to avoid undoing changes the application applied. We expect this
1039 // to happen on a bare metal installation only. An already existing
1040 // target should be loaded before its settings are changed.
1042 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1043 if ( ! requestedLocales.empty() )
1045 satpool.initRequestedLocales( requestedLocales );
1049 if ( ! PathInfo( _autoInstalledFile.file() ).isExist() )
1051 // Initialize from history, if it does not exist
1052 Pathname historyFile( Pathname::assertprefix( _root, ZConfig::instance().historyLogFile() ) );
1053 if ( PathInfo( historyFile ).isExist() )
1055 SolvIdentFile::Data onSystemByUser( getUserInstalledFromHistory( historyFile ) );
1056 SolvIdentFile::Data onSystemByAuto;
1057 for_( it, system.solvablesBegin(), system.solvablesEnd() )
1059 IdString ident( (*it).ident() );
1060 if ( onSystemByUser.find( ident ) == onSystemByUser.end() )
1061 onSystemByAuto.insert( ident );
1063 _autoInstalledFile.setData( onSystemByAuto );
1065 // on the fly removed any obsolete SoftLocks file
1066 filesystem::unlink( home() / "SoftLocks" );
1068 // read from AutoInstalled file
1070 for ( const auto & idstr : _autoInstalledFile.data() )
1071 q.push( idstr.id() );
1072 satpool.setAutoInstalled( q );
1074 if ( ZConfig::instance().apply_locks_file() )
1076 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1077 if ( ! hardLocks.empty() )
1079 ResPool::instance().setHardLockQueries( hardLocks );
1083 // now that the target is loaded, we can cache the flavor
1084 createLastDistributionFlavorCache();
1086 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1089 ///////////////////////////////////////////////////////////////////
1093 ///////////////////////////////////////////////////////////////////
1094 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1096 // ----------------------------------------------------------------- //
1097 ZYppCommitPolicy policy_r( policy_rX );
1099 // Fake outstanding YCP fix: Honour restriction to media 1
1100 // at installation, but install all remaining packages if post-boot.
1101 if ( policy_r.restrictToMedia() > 1 )
1102 policy_r.allMedia();
1104 if ( policy_r.downloadMode() == DownloadDefault ) {
1105 if ( root() == "/" )
1106 policy_r.downloadMode(DownloadInHeaps);
1108 policy_r.downloadMode(DownloadAsNeeded);
1110 // DownloadOnly implies dry-run.
1111 else if ( policy_r.downloadMode() == DownloadOnly )
1112 policy_r.dryRun( true );
1113 // ----------------------------------------------------------------- //
1115 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1117 ///////////////////////////////////////////////////////////////////
1118 // Compute transaction:
1119 ///////////////////////////////////////////////////////////////////
1120 ZYppCommitResult result( root() );
1121 result.rTransaction() = pool_r.resolver().getTransaction();
1122 result.rTransaction().order();
1123 // steps: this is our todo-list
1124 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1125 if ( policy_r.restrictToMedia() )
1127 // Collect until the 1st package from an unwanted media occurs.
1128 // Further collection could violate install order.
1129 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1130 for_( it, result.transaction().begin(), result.transaction().end() )
1132 if ( makeResObject( *it )->mediaNr() > 1 )
1134 steps.push_back( *it );
1139 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1141 MIL << "Todo: " << result << endl;
1143 ///////////////////////////////////////////////////////////////////
1144 // Prepare execution of commit plugins:
1145 ///////////////////////////////////////////////////////////////////
1146 PluginExecutor commitPlugins;
1147 if ( root() == "/" && ! policy_r.dryRun() )
1149 commitPlugins.load( ZConfig::instance().pluginsPath()/"commit" );
1151 if ( commitPlugins )
1152 commitPlugins.send( transactionPluginFrame( "COMMITBEGIN", steps ) );
1154 ///////////////////////////////////////////////////////////////////
1155 // Write out a testcase if we're in dist upgrade mode.
1156 ///////////////////////////////////////////////////////////////////
1157 if ( pool_r.resolver().upgradeMode() || pool_r.resolver().upgradingRepos() )
1159 if ( ! policy_r.dryRun() )
1161 writeUpgradeTestcase();
1165 DBG << "dryRun: Not writing upgrade testcase." << endl;
1169 ///////////////////////////////////////////////////////////////////
1170 // Store non-package data:
1171 ///////////////////////////////////////////////////////////////////
1172 if ( ! policy_r.dryRun() )
1174 filesystem::assert_dir( home() );
1175 // requested locales
1176 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1179 SolvIdentFile::Data newdata;
1180 for ( sat::Queue::value_type id : result.rTransaction().autoInstalled() )
1181 newdata.insert( IdString(id) );
1182 _autoInstalledFile.setData( newdata );
1185 if ( ZConfig::instance().apply_locks_file() )
1187 HardLocksFile::Data newdata;
1188 pool_r.getHardLockQueries( newdata );
1189 _hardLocksFile.setData( newdata );
1194 DBG << "dryRun: Not stroring non-package data." << endl;
1197 ///////////////////////////////////////////////////////////////////
1198 // First collect and display all messages
1199 // associated with patches to be installed.
1200 ///////////////////////////////////////////////////////////////////
1201 if ( ! policy_r.dryRun() )
1203 for_( it, steps.begin(), steps.end() )
1205 if ( ! it->satSolvable().isKind<Patch>() )
1209 if ( ! pi.status().isToBeInstalled() )
1212 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1213 if ( ! patch ||patch->message().empty() )
1216 MIL << "Show message for " << patch << endl;
1217 callback::SendReport<target::PatchMessageReport> report;
1218 if ( ! report->show( patch ) )
1220 WAR << "commit aborted by the user" << endl;
1221 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1227 DBG << "dryRun: Not checking patch messages." << endl;
1230 ///////////////////////////////////////////////////////////////////
1231 // Remove/install packages.
1232 ///////////////////////////////////////////////////////////////////
1233 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1234 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1236 // Prepare the package cache. Pass all items requiring download.
1237 CommitPackageCache packageCache;
1238 packageCache.setCommitList( steps.begin(), steps.end() );
1241 if ( policy_r.downloadMode() != DownloadAsNeeded )
1243 // Preload the cache. Until now this means pre-loading all packages.
1244 // Once DownloadInHeaps is fully implemented, this will change and
1245 // we may actually have more than one heap.
1246 for_( it, steps.begin(), steps.end() )
1248 switch ( it->stepType() )
1250 case sat::Transaction::TRANSACTION_INSTALL:
1251 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1252 // proceed: only install actionas may require download.
1256 // next: no download for or non-packages and delete actions.
1262 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1264 ManagedFile localfile;
1267 localfile = packageCache.get( pi );
1268 localfile.resetDispose(); // keep the package file in the cache
1270 catch ( const AbortRequestException & exp )
1272 it->stepStage( sat::Transaction::STEP_ERROR );
1274 WAR << "commit cache preload aborted by the user" << endl;
1275 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1278 catch ( const SkipRequestException & exp )
1281 it->stepStage( sat::Transaction::STEP_ERROR );
1283 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1286 catch ( const Exception & exp )
1288 // bnc #395704: missing catch causes abort.
1289 // TODO see if packageCache fails to handle errors correctly.
1291 it->stepStage( sat::Transaction::STEP_ERROR );
1293 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1298 packageCache.preloaded( true ); // try to avoid duplicate infoInCache CBs in commit
1303 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1307 if ( ! policy_r.dryRun() )
1309 // if cache is preloaded, check for file conflicts
1310 commitFindFileConflicts( policy_r, result );
1311 commit( policy_r, packageCache, result );
1315 DBG << "dryRun/downloadOnly: Not installing/deleting anything." << endl;
1321 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1324 ///////////////////////////////////////////////////////////////////
1325 // Send result to commit plugins:
1326 ///////////////////////////////////////////////////////////////////
1327 if ( commitPlugins )
1328 commitPlugins.send( transactionPluginFrame( "COMMITEND", steps ) );
1330 ///////////////////////////////////////////////////////////////////
1331 // Try to rebuild solv file while rpm database is still in cache
1332 ///////////////////////////////////////////////////////////////////
1333 if ( ! policy_r.dryRun() )
1338 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1342 ///////////////////////////////////////////////////////////////////
1346 ///////////////////////////////////////////////////////////////////
1349 struct NotifyAttemptToModify
1351 NotifyAttemptToModify( ZYppCommitResult & result_r ) : _result( result_r ) {}
1354 { if ( _guard ) { _result.attemptToModify( true ); _guard = false; } }
1357 ZYppCommitResult & _result;
1361 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1362 CommitPackageCache & packageCache_r,
1363 ZYppCommitResult & result_r )
1365 // steps: this is our todo-list
1366 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1367 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1369 HistoryLog().stampCommand();
1371 // Send notification once upon 1st call to rpm
1372 NotifyAttemptToModify attemptToModify( result_r );
1376 RpmPostTransCollector postTransCollector( _root );
1377 std::vector<sat::Solvable> successfullyInstalledPackages;
1378 TargetImpl::PoolItemList remaining;
1380 for_( step, steps.begin(), steps.end() )
1382 PoolItem citem( *step );
1383 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1385 if ( citem->isKind<Package>() )
1387 // for packages this means being obsoleted (by rpm)
1388 // thius no additional action is needed.
1389 step->stepStage( sat::Transaction::STEP_DONE );
1394 if ( citem->isKind<Package>() )
1396 Package::constPtr p = citem->asKind<Package>();
1397 if ( citem.status().isToBeInstalled() )
1399 ManagedFile localfile;
1402 localfile = packageCache_r.get( citem );
1404 catch ( const AbortRequestException &e )
1406 WAR << "commit aborted by the user" << endl;
1408 step->stepStage( sat::Transaction::STEP_ERROR );
1411 catch ( const SkipRequestException &e )
1414 WAR << "Skipping package " << p << " in commit" << endl;
1415 step->stepStage( sat::Transaction::STEP_ERROR );
1418 catch ( const Exception &e )
1420 // bnc #395704: missing catch causes abort.
1421 // TODO see if packageCache fails to handle errors correctly.
1423 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1424 step->stepStage( sat::Transaction::STEP_ERROR );
1428 #warning Exception handling
1429 // create a installation progress report proxy
1430 RpmInstallPackageReceiver progress( citem.resolvable() );
1431 progress.connect(); // disconnected on destruction.
1433 bool success = false;
1434 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1435 // Why force and nodeps?
1437 // Because zypp builds the transaction and the resolver asserts that
1438 // everything is fine.
1439 // We use rpm just to unpack and register the package in the database.
1440 // We do this step by step, so rpm is not aware of the bigger context.
1441 // So we turn off rpms internal checks, because we do it inside zypp.
1442 flags |= rpm::RPMINST_NODEPS;
1443 flags |= rpm::RPMINST_FORCE;
1445 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1446 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1447 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1448 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1453 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1454 if ( postTransCollector.collectScriptFromPackage( localfile ) )
1455 flags |= rpm::RPMINST_NOPOSTTRANS;
1456 rpm().installPackage( localfile, flags );
1457 HistoryLog().install(citem);
1459 if ( progress.aborted() )
1461 WAR << "commit aborted by the user" << endl;
1462 localfile.resetDispose(); // keep the package file in the cache
1464 step->stepStage( sat::Transaction::STEP_ERROR );
1470 step->stepStage( sat::Transaction::STEP_DONE );
1473 catch ( Exception & excpt_r )
1475 ZYPP_CAUGHT(excpt_r);
1476 localfile.resetDispose(); // keep the package file in the cache
1478 if ( policy_r.dryRun() )
1480 WAR << "dry run failed" << endl;
1481 step->stepStage( sat::Transaction::STEP_ERROR );
1485 if ( progress.aborted() )
1487 WAR << "commit aborted by the user" << endl;
1492 WAR << "Install failed" << endl;
1494 step->stepStage( sat::Transaction::STEP_ERROR );
1498 if ( success && !policy_r.dryRun() )
1500 citem.status().resetTransact( ResStatus::USER );
1501 successfullyInstalledPackages.push_back( citem.satSolvable() );
1502 step->stepStage( sat::Transaction::STEP_DONE );
1507 RpmRemovePackageReceiver progress( citem.resolvable() );
1508 progress.connect(); // disconnected on destruction.
1510 bool success = false;
1511 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1512 flags |= rpm::RPMINST_NODEPS;
1513 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1518 rpm().removePackage( p, flags );
1519 HistoryLog().remove(citem);
1521 if ( progress.aborted() )
1523 WAR << "commit aborted by the user" << endl;
1525 step->stepStage( sat::Transaction::STEP_ERROR );
1531 step->stepStage( sat::Transaction::STEP_DONE );
1534 catch (Exception & excpt_r)
1536 ZYPP_CAUGHT( excpt_r );
1537 if ( progress.aborted() )
1539 WAR << "commit aborted by the user" << endl;
1541 step->stepStage( sat::Transaction::STEP_ERROR );
1545 WAR << "removal of " << p << " failed";
1546 step->stepStage( sat::Transaction::STEP_ERROR );
1548 if ( success && !policy_r.dryRun() )
1550 citem.status().resetTransact( ResStatus::USER );
1551 step->stepStage( sat::Transaction::STEP_DONE );
1555 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1557 // Status is changed as the buddy package buddy
1558 // gets installed/deleted. Handle non-buddies only.
1559 if ( ! citem.buddy() )
1561 if ( citem->isKind<Product>() )
1563 Product::constPtr p = citem->asKind<Product>();
1564 if ( citem.status().isToBeInstalled() )
1566 ERR << "Can't install orphan product without release-package! " << citem << endl;
1570 // Deleting the corresponding product entry is all we con do.
1571 // So the product will no longer be visible as installed.
1572 std::string referenceFilename( p->referenceFilename() );
1573 if ( referenceFilename.empty() )
1575 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1579 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1580 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1582 ERR << "Delete orphan product failed: " << referenceFile << endl;
1587 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1589 // SrcPackage is install-only
1590 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1591 installSrcPackage( p );
1594 citem.status().resetTransact( ResStatus::USER );
1595 step->stepStage( sat::Transaction::STEP_DONE );
1598 } // other resolvables
1602 // process all remembered posttrans scripts.
1604 postTransCollector.executeScripts();
1606 postTransCollector.discardScripts();
1608 // Check presence of update scripts/messages. If aborting,
1609 // at least log omitted scripts.
1610 if ( ! successfullyInstalledPackages.empty() )
1612 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1613 successfullyInstalledPackages, abort ) )
1615 WAR << "Commit aborted by the user" << endl;
1618 // send messages after scripts in case some script generates output,
1619 // that should be kept in t %ghost message file.
1620 RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1621 successfullyInstalledPackages,
1627 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1631 ///////////////////////////////////////////////////////////////////
1633 rpm::RpmDb & TargetImpl::rpm()
1638 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1640 return _rpm.hasFile(path_str, name_str);
1644 Date TargetImpl::timestamp() const
1646 return _rpm.timestamp();
1649 ///////////////////////////////////////////////////////////////////
1652 parser::ProductFileData baseproductdata( const Pathname & root_r )
1654 parser::ProductFileData ret;
1655 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1657 if ( baseproduct.isFile() )
1661 ret = parser::ProductFileReader::scanFile( baseproduct.path() );
1663 catch ( const Exception & excpt )
1665 ZYPP_CAUGHT( excpt );
1668 else if ( PathInfo( Pathname::assertprefix( root_r, "/etc/products.d" ) ).isDir() )
1670 ERR << "baseproduct symlink is dangling or missing: " << baseproduct << endl;
1675 inline Pathname staticGuessRoot( const Pathname & root_r )
1677 if ( root_r.empty() )
1679 // empty root: use existing Target or assume "/"
1680 Pathname ret ( ZConfig::instance().systemRoot() );
1682 return Pathname("/");
1688 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1690 std::ifstream idfile( file_r.c_str() );
1691 for( iostr::EachLine in( idfile ); in; in.next() )
1693 std::string line( str::trim( *in ) );
1694 if ( ! line.empty() )
1697 return std::string();
1700 ///////////////////////////////////////////////////////////////////
1702 Product::constPtr TargetImpl::baseProduct() const
1704 ResPool pool(ResPool::instance());
1705 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1707 Product::constPtr p = (*it)->asKind<Product>();
1708 if ( p->isTargetDistribution() )
1714 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1716 const Pathname needroot( staticGuessRoot(root_r) );
1717 const Target_constPtr target( getZYpp()->getTarget() );
1718 if ( target && target->root() == needroot )
1719 return target->requestedLocales();
1720 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1723 void TargetImpl::updateAutoInstalled()
1725 MIL << "updateAutoInstalled if changed..." << endl;
1726 SolvIdentFile::Data newdata;
1727 for ( auto id : sat::Pool::instance().autoInstalled() )
1728 newdata.insert( IdString(id) ); // explicit ctor!
1729 _autoInstalledFile.setData( std::move(newdata) );
1732 std::string TargetImpl::targetDistribution() const
1733 { return baseproductdata( _root ).registerTarget(); }
1735 std::string TargetImpl::targetDistribution( const Pathname & root_r )
1736 { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1738 std::string TargetImpl::targetDistributionRelease() const
1739 { return baseproductdata( _root ).registerRelease(); }
1741 std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1742 { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1744 std::string TargetImpl::targetDistributionFlavor() const
1745 { return baseproductdata( _root ).registerFlavor(); }
1747 std::string TargetImpl::targetDistributionFlavor( const Pathname & root_r )
1748 { return baseproductdata( staticGuessRoot(root_r) ).registerFlavor();}
1750 Target::DistributionLabel TargetImpl::distributionLabel() const
1752 Target::DistributionLabel ret;
1753 parser::ProductFileData pdata( baseproductdata( _root ) );
1754 ret.shortName = pdata.shortName();
1755 ret.summary = pdata.summary();
1759 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1761 Target::DistributionLabel ret;
1762 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1763 ret.shortName = pdata.shortName();
1764 ret.summary = pdata.summary();
1768 std::string TargetImpl::distributionVersion() const
1770 if ( _distributionVersion.empty() )
1772 _distributionVersion = TargetImpl::distributionVersion(root());
1773 if ( !_distributionVersion.empty() )
1774 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1776 return _distributionVersion;
1779 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1781 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1782 if ( distributionVersion.empty() )
1784 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1785 // On RHEL, Fedora and others the "product version" is determined by the first package
1786 // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1787 // with the $distroverpkg variable.
1788 scoped_ptr<rpm::RpmDb> tmprpmdb;
1789 if ( ZConfig::instance().systemRoot() == Pathname() )
1793 tmprpmdb.reset( new rpm::RpmDb );
1794 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1801 rpm::librpmDb::db_const_iterator it;
1802 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1803 distributionVersion = it->tag_version();
1805 return distributionVersion;
1809 std::string TargetImpl::distributionFlavor() const
1811 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1814 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1816 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1819 ///////////////////////////////////////////////////////////////////
1822 std::string guessAnonymousUniqueId( const Pathname & root_r )
1824 // bsc#1024741: Omit creating a new uid for chrooted systems (if it already has one, fine)
1825 std::string ret( firstNonEmptyLineIn( root_r / "/var/lib/zypp/AnonymousUniqueId" ) );
1826 if ( ret.empty() && root_r != "/" )
1828 // if it has nonoe, use the outer systems one
1829 ret = firstNonEmptyLineIn( "/var/lib/zypp/AnonymousUniqueId" );
1835 std::string TargetImpl::anonymousUniqueId() const
1837 return guessAnonymousUniqueId( root() );
1840 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1842 return guessAnonymousUniqueId( staticGuessRoot(root_r) );
1845 ///////////////////////////////////////////////////////////////////
1847 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1849 // provide on local disk
1850 ManagedFile localfile = provideSrcPackage(srcPackage_r);
1851 // create a installation progress report proxy
1852 RpmInstallPackageReceiver progress( srcPackage_r );
1853 progress.connect(); // disconnected on destruction.
1855 rpm().installPackage ( localfile );
1858 ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1860 // provide on local disk
1861 repo::RepoMediaAccess access_r;
1862 repo::SrcPackageProvider prov( access_r );
1863 return prov.provideSrcPackage( srcPackage_r );
1865 ////////////////////////////////////////////////////////////////
1866 } // namespace target
1867 ///////////////////////////////////////////////////////////////////
1868 /////////////////////////////////////////////////////////////////
1870 ///////////////////////////////////////////////////////////////////