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"
30 #include "zypp/ZConfig.h"
31 #include "zypp/ZYppFactory.h"
33 #include "zypp/PoolItem.h"
34 #include "zypp/ResObjects.h"
36 #include "zypp/TmpPath.h"
37 #include "zypp/RepoStatus.h"
38 #include "zypp/ExternalProgram.h"
39 #include "zypp/Repository.h"
41 #include "zypp/ResFilters.h"
42 #include "zypp/HistoryLog.h"
43 #include "zypp/target/TargetImpl.h"
44 #include "zypp/target/TargetCallbackReceiver.h"
45 #include "zypp/target/rpm/librpmDb.h"
46 #include "zypp/target/CommitPackageCache.h"
48 #include "zypp/parser/ProductFileReader.h"
50 #include "zypp/pool/GetResolvablesToInsDel.h"
51 #include "zypp/solver/detail/Testcase.h"
53 #include "zypp/repo/DeltaCandidates.h"
54 #include "zypp/repo/PackageProvider.h"
55 #include "zypp/repo/SrcPackageProvider.h"
57 #include "zypp/sat/Pool.h"
58 #include "zypp/sat/Transaction.h"
60 #include "zypp/PluginScript.h"
64 ///////////////////////////////////////////////////////////////////
66 { /////////////////////////////////////////////////////////////////
67 ///////////////////////////////////////////////////////////////////
69 { /////////////////////////////////////////////////////////////////
71 /** Helper for commit plugin execution.
74 class CommitPlugins : private base::NonCopyable
79 /** Default ctor: Empty plugin list */
83 /** Dtor: Send PLUGINEND message and close plugins. */
86 for_( it, _scripts.begin(), _scripts.end() )
88 MIL << "Unload plugin: " << *it << endl;
90 it->send( PluginFrame( "PLUGINEND" ) );
91 PluginFrame ret( it->receive() );
92 if ( ! ret.isAckCommand() )
94 WAR << "Failed to unload plugin: Bad plugin response." << endl;
98 catch( const zypp::Exception & )
100 WAR << "Failed to unload plugin." << endl;
103 // _scripts dtor will disconnect all remaining plugins!
106 /** Find and launch plugins sending PLUGINSTART message.
108 * If \a path_r is a directory all executable files whithin are
109 * expected to be plugins. Otherwise \a path_r must point to an
112 void load( const Pathname & path_r )
114 PathInfo pi( path_r );
117 std::list<Pathname> entries;
118 if ( filesystem::readdir( entries, pi.path(), false ) != 0 )
120 WAR << "Plugin dir is not readable: " << pi << endl;
123 for_( it, entries.begin(), entries.end() )
126 if ( pii.isFile() && pii.userMayRX() )
130 else if ( pi.isFile() )
132 if ( pi.userMayRX() )
135 WAR << "Plugin file is not executable: " << pi << endl;
139 WAR << "Plugin path is neither dir nor file: " << pi << endl;
144 void doLoad( const PathInfo & pi_r )
146 MIL << "Load plugin: " << pi_r << endl;
148 PluginFrame frame( "PLUGINBEGIN" );
149 if ( ZConfig::instance().hasUserData() )
150 frame.setHeader( "userdata", ZConfig::instance().userData() );
152 PluginScript plugin( pi_r.path() );
154 plugin.send( frame );
155 PluginFrame ret( plugin.receive() );
156 if ( ret.isAckCommand() )
158 _scripts.push_back( plugin );
162 WAR << "Failed to load plugin: Bad plugin response." << endl;
165 catch( const zypp::Exception & )
167 WAR << "Failed to load plugin." << endl;
172 std::list<PluginScript> _scripts;
175 void testCommitPlugins( const Pathname & path_r ) // for testing only
177 USR << "+++++" << endl;
181 USR << "=====" << endl;
183 USR << "-----" << endl;
186 ///////////////////////////////////////////////////////////////////
188 /** \internal Manage writing a new testcase when doing an upgrade. */
189 void writeUpgradeTestcase()
191 unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
192 MIL << "Testcases to keep: " << toKeep << endl;
195 Target_Ptr target( getZYpp()->getTarget() );
198 WAR << "No Target no Testcase!" << endl;
202 std::string stem( "updateTestcase" );
203 Pathname dir( target->assertRootPrefix("/var/log/") );
204 Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
207 std::list<std::string> content;
208 filesystem::readdir( content, dir, /*dots*/false );
209 std::set<std::string> cases;
210 for_( c, content.begin(), content.end() )
212 if ( str::startsWith( *c, stem ) )
215 if ( cases.size() >= toKeep )
217 unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
218 for_( c, cases.begin(), cases.end() )
220 filesystem::recursive_rmdir( dir/(*c) );
227 MIL << "Write new testcase " << next << endl;
228 getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
231 ///////////////////////////////////////////////////////////////////
233 { /////////////////////////////////////////////////////////////////
235 /** Execute script and report against report_r.
236 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
237 * execution was successfull (<tt>first = true</tt>), or the desired
238 * \c PatchScriptReport::Action in case execution failed
239 * (<tt>first = false</tt>).
241 * \note The packager is responsible for setting the correct permissions
242 * of the script. If the script is not executable it is reported as an
243 * error. We must not modify the permessions.
245 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
246 const Pathname & script_r,
247 callback::SendReport<PatchScriptReport> & report_r )
249 MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
251 HistoryLog historylog;
252 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
253 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
255 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
257 historylog.comment(output);
258 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
260 WAR << "User request to abort script " << script_r << endl;
262 // the rest is handled by exit code evaluation
263 // in case the script has meanwhile finished.
267 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
269 if ( prog.close() != 0 )
271 ret.second = report_r->problem( prog.execError() );
272 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
273 std::ostringstream sstr;
274 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
275 historylog.comment(sstr.str(), /*timestamp*/true);
284 /** Execute script and report against report_r.
285 * Return \c false if user requested \c ABORT.
287 bool executeScript( const Pathname & root_r,
288 const Pathname & script_r,
289 callback::SendReport<PatchScriptReport> & report_r )
291 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
294 action = doExecuteScript( root_r, script_r, report_r );
296 return true; // success
298 switch ( action.second )
300 case PatchScriptReport::ABORT:
301 WAR << "User request to abort at script " << script_r << endl;
302 return false; // requested abort.
305 case PatchScriptReport::IGNORE:
306 WAR << "User request to skip script " << script_r << endl;
307 return true; // requested skip.
310 case PatchScriptReport::RETRY:
313 } while ( action.second == PatchScriptReport::RETRY );
315 // THIS is not intended to be reached:
316 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
317 return false; // abort.
320 /** Look for update scripts named 'name-version-release-*' and
321 * execute them. Return \c false if \c ABORT was requested.
323 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
325 bool RunUpdateScripts( const Pathname & root_r,
326 const Pathname & scriptsPath_r,
327 const std::vector<sat::Solvable> & checkPackages_r,
330 if ( checkPackages_r.empty() )
331 return true; // no installed packages to check
333 MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
334 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
335 if ( ! PathInfo( scriptsDir ).isDir() )
336 return true; // no script dir
338 std::list<std::string> scripts;
339 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
340 if ( scripts.empty() )
341 return true; // no scripts in script dir
343 // Now collect and execute all matching scripts.
344 // On ABORT: at least log all outstanding scripts.
345 // - "name-version-release"
346 // - "name-version-release-*"
348 std::map<std::string, Pathname> unify; // scripts <md5,path>
349 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
351 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
352 for_( sit, scripts.begin(), scripts.end() )
354 if ( ! str::hasPrefix( *sit, prefix ) )
357 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
358 continue; // if not exact match it had to continue with '-'
360 PathInfo script( scriptsDir / *sit );
361 Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
362 std::string unifytag; // must not stay empty
364 if ( script.isFile() )
366 // Assert it's set executable, unify by md5sum.
367 filesystem::addmod( script.path(), 0500 );
368 unifytag = filesystem::md5sum( script.path() );
370 else if ( ! script.isExist() )
372 // Might be a dangling symlink, might be ok if we are in
373 // instsys (absolute symlink within the system below /mnt).
374 // readlink will tell....
375 unifytag = filesystem::readlink( script.path() ).asString();
378 if ( unifytag.empty() )
382 if ( unify[unifytag].empty() )
384 unify[unifytag] = localPath;
388 // translators: We may find the same script content in files with different names.
389 // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
390 // message for a log file. Preferably start translation with "%s"
391 std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
392 MIL << "Skip update script: " << msg << endl;
393 HistoryLog().comment( msg, /*timestamp*/true );
397 if ( abort || aborting_r )
399 WAR << "Aborting: Skip update script " << *sit << endl;
400 HistoryLog().comment(
401 localPath.asString() + _(" execution skipped while aborting"),
406 MIL << "Found update script " << *sit << endl;
407 callback::SendReport<PatchScriptReport> report;
408 report->start( make<Package>( *it ), script.path() );
410 if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
411 abort = true; // requested abort.
418 ///////////////////////////////////////////////////////////////////
420 ///////////////////////////////////////////////////////////////////
422 inline void copyTo( std::ostream & out_r, const Pathname & file_r )
424 std::ifstream infile( file_r.c_str() );
425 for( iostr::EachLine in( infile ); in; in.next() )
427 out_r << *in << endl;
431 inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
433 std::string ret( cmd_r );
434 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
435 SUBST_IF( "%p", notification_r.solvable().asString() );
436 SUBST_IF( "%P", notification_r.file().asString() );
441 void sendNotification( const Pathname & root_r,
442 const UpdateNotifications & notifications_r )
444 if ( notifications_r.empty() )
447 std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
448 MIL << "Notification command is '" << cmdspec << "'" << endl;
449 if ( cmdspec.empty() )
452 std::string::size_type pos( cmdspec.find( '|' ) );
453 if ( pos == std::string::npos )
455 ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
456 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
460 std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
461 std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
463 enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
464 Format format = UNKNOWN;
465 if ( formatStr == "none" )
467 else if ( formatStr == "single" )
469 else if ( formatStr == "digest" )
471 else if ( formatStr == "bulk" )
475 ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
476 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
480 // Take care: commands are ececuted chroot(root_r). The message file
481 // pathnames in notifications_r are local to root_r. For physical access
482 // to the file they need to be prefixed.
484 if ( format == NONE || format == SINGLE )
486 for_( it, notifications_r.begin(), notifications_r.end() )
488 std::vector<std::string> command;
489 if ( format == SINGLE )
490 command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
491 str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
493 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
494 if ( true ) // Wait for feedback
496 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
500 int ret = prog.close();
503 ERR << "Notification command returned with error (" << ret << ")." << endl;
504 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
510 else if ( format == DIGEST || format == BULK )
512 filesystem::TmpFile tmpfile;
513 ofstream out( tmpfile.path().c_str() );
514 for_( it, notifications_r.begin(), notifications_r.end() )
516 if ( format == DIGEST )
518 out << it->file() << endl;
520 else if ( format == BULK )
522 copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
526 std::vector<std::string> command;
527 command.push_back( "<"+tmpfile.path().asString() ); // redirect input
528 str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
530 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
531 if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
533 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
537 int ret = prog.close();
540 ERR << "Notification command returned with error (" << ret << ")." << endl;
541 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
548 INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
549 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
555 /** Look for update messages named 'name-version-release-*' and
556 * send notification according to \ref ZConfig::updateMessagesNotify.
558 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
560 void RunUpdateMessages( const Pathname & root_r,
561 const Pathname & messagesPath_r,
562 const std::vector<sat::Solvable> & checkPackages_r,
563 ZYppCommitResult & result_r )
565 if ( checkPackages_r.empty() )
566 return; // no installed packages to check
568 MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
569 Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
570 if ( ! PathInfo( messagesDir ).isDir() )
571 return; // no messages dir
573 std::list<std::string> messages;
574 filesystem::readdir( messages, messagesDir, /*dots*/false );
575 if ( messages.empty() )
576 return; // no messages in message dir
578 // Now collect all matching messages in result and send them
579 // - "name-version-release"
580 // - "name-version-release-*"
581 HistoryLog historylog;
582 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
584 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
585 for_( sit, messages.begin(), messages.end() )
587 if ( ! str::hasPrefix( *sit, prefix ) )
590 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
591 continue; // if not exact match it had to continue with '-'
593 PathInfo message( messagesDir / *sit );
594 if ( ! message.isFile() || message.size() == 0 )
597 MIL << "Found update message " << *sit << endl;
598 Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
599 result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
600 historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
603 sendNotification( root_r, result_r.updateMessages() );
606 /////////////////////////////////////////////////////////////////
608 ///////////////////////////////////////////////////////////////////
610 void XRunUpdateMessages( const Pathname & root_r,
611 const Pathname & messagesPath_r,
612 const std::vector<sat::Solvable> & checkPackages_r,
613 ZYppCommitResult & result_r )
614 { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
616 /** Helper for PackageProvider queries during commit. */
617 struct QueryInstalledEditionHelper
619 bool operator()( const std::string & name_r,
620 const Edition & ed_r,
621 const Arch & arch_r ) const
623 rpm::librpmDb::db_const_iterator it;
624 for ( it.findByName( name_r ); *it; ++it )
626 if ( arch_r == it->tag_arch()
627 && ( ed_r == Edition::noedition || ed_r == it->tag_edition() ) )
637 * \short Let the Source provide the package.
638 * \p pool_r \ref ResPool used to get candidates
639 * \p pi item to be commited
641 struct RepoProvidePackage
644 repo::RepoMediaAccess &_access;
646 RepoProvidePackage( repo::RepoMediaAccess &access, ResPool pool_r )
647 : _pool(pool_r), _access(access)
650 ManagedFile operator()( const PoolItem & pi )
652 // Redirect PackageProvider queries for installed editions
653 // (in case of patch/delta rpm processing) to rpmDb.
654 repo::PackageProviderPolicy packageProviderPolicy;
655 packageProviderPolicy.queryInstalledCB( QueryInstalledEditionHelper() );
657 Package::constPtr p = asKind<Package>(pi.resolvable());
659 // Build a repository list for repos
660 // contributing to the pool
661 std::list<Repository> repos( _pool.knownRepositoriesBegin(), _pool.knownRepositoriesEnd() );
662 repo::DeltaCandidates deltas(repos, p->name());
663 repo::PackageProvider pkgProvider( _access, p, deltas, packageProviderPolicy );
665 ManagedFile ret( pkgProvider.providePackage() );
669 ///////////////////////////////////////////////////////////////////
671 IMPL_PTR_TYPE(TargetImpl);
673 TargetImpl_Ptr TargetImpl::_nullimpl;
675 /** Null implementation */
676 TargetImpl_Ptr TargetImpl::nullimpl()
679 _nullimpl = new TargetImpl;
683 ///////////////////////////////////////////////////////////////////
685 // METHOD NAME : TargetImpl::TargetImpl
686 // METHOD TYPE : Ctor
688 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
690 , _requestedLocalesFile( home() / "RequestedLocales" )
691 , _softLocksFile( home() / "SoftLocks" )
692 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
694 _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
696 HistoryLog::setRoot(_root);
700 MIL << "Initialized target on " << _root << endl;
704 * generates a random id using uuidgen
706 static std::string generateRandomId()
708 std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
709 return iostr::getline( uuidprovider );
713 * updates the content of \p filename
714 * if \p condition is true, setting the content
715 * the the value returned by \p value
717 void updateFileContent( const Pathname &filename,
718 boost::function<bool ()> condition,
719 boost::function<string ()> value )
721 string val = value();
722 // if the value is empty, then just dont
723 // do anything, regardless of the condition
729 MIL << "updating '" << filename << "' content." << endl;
731 // if the file does not exist we need to generate the uuid file
733 std::ofstream filestr;
734 // make sure the path exists
735 filesystem::assert_dir( filename.dirname() );
736 filestr.open( filename.c_str() );
738 if ( filestr.good() )
745 // FIXME, should we ignore the error?
746 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
751 /** helper functor */
752 static bool fileMissing( const Pathname &pathname )
754 return ! PathInfo(pathname).isExist();
757 void TargetImpl::createAnonymousId() const
760 // create the anonymous unique id
761 // this value is used for statistics
762 Pathname idpath( home() / "AnonymousUniqueId");
766 updateFileContent( idpath,
767 boost::bind(fileMissing, idpath),
770 catch ( const Exception &e )
772 WAR << "Can't create anonymous id file" << endl;
777 void TargetImpl::createLastDistributionFlavorCache() const
779 // create the anonymous unique id
780 // this value is used for statistics
781 Pathname flavorpath( home() / "LastDistributionFlavor");
783 // is there a product
784 Product::constPtr p = baseProduct();
787 WAR << "No base product, I won't create flavor cache" << endl;
791 string flavor = p->flavor();
796 updateFileContent( flavorpath,
797 // only if flavor is not empty
798 functor::Constant<bool>( ! flavor.empty() ),
799 functor::Constant<string>(flavor) );
801 catch ( const Exception &e )
803 WAR << "Can't create flavor cache" << endl;
808 ///////////////////////////////////////////////////////////////////
810 // METHOD NAME : TargetImpl::~TargetImpl
811 // METHOD TYPE : Dtor
813 TargetImpl::~TargetImpl()
815 _rpm.closeDatabase();
816 MIL << "Targets closed" << endl;
819 ///////////////////////////////////////////////////////////////////
821 // solv file handling
823 ///////////////////////////////////////////////////////////////////
825 Pathname TargetImpl::defaultSolvfilesPath() const
827 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
830 void TargetImpl::clearCache()
832 Pathname base = solvfilesPath();
833 filesystem::recursive_rmdir( base );
836 bool TargetImpl::buildCache()
838 Pathname base = solvfilesPath();
839 Pathname rpmsolv = base/"solv";
840 Pathname rpmsolvcookie = base/"cookie";
842 bool build_rpm_solv = true;
843 // lets see if the rpm solv cache exists
845 RepoStatus rpmstatus( RepoStatus( _root/"/var/lib/rpm/Name" )
846 && (_root/"/etc/products.d") );
848 bool solvexisted = PathInfo(rpmsolv).isExist();
851 // see the status of the cache
852 PathInfo cookie( rpmsolvcookie );
853 MIL << "Read cookie: " << cookie << endl;
854 if ( cookie.isExist() )
856 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
857 // now compare it with the rpm database
858 if ( status.checksum() == rpmstatus.checksum() )
859 build_rpm_solv = false;
860 MIL << "Read cookie: " << rpmsolvcookie << " says: "
861 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
865 if ( build_rpm_solv )
867 // if the solvfile dir does not exist yet, we better create it
868 filesystem::assert_dir( base );
870 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
872 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
875 // Can't create temporary solv file, usually due to insufficient permission
876 // (user query while @System solv needs refresh). If so, try switching
877 // to a location within zypps temp. space (will be cleaned at application end).
879 bool switchingToTmpSolvfile = false;
880 Exception ex("Failed to cache rpm database.");
881 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
883 if ( ! solvfilesPathIsTemp() )
885 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
886 rpmsolv = base/"solv";
887 rpmsolvcookie = base/"cookie";
889 filesystem::assert_dir( base );
890 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
894 WAR << "Using a temporary solv file at " << base << endl;
895 switchingToTmpSolvfile = true;
896 _tmpSolvfilesPath = base;
900 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
904 if ( ! switchingToTmpSolvfile )
910 // Take care we unlink the solvfile on exception
911 ManagedFile guard( base, filesystem::recursive_rmdir );
913 std::ostringstream cmd;
915 if ( ! _root.empty() )
916 cmd << " -r '" << _root << "'";
918 cmd << " -p '" << Pathname::assertprefix( _root, "/etc/products.d" ) << "'";
920 if ( ! oldSolvFile.empty() )
921 cmd << " '" << oldSolvFile << "'";
923 cmd << " > '" << tmpsolv.path() << "'";
925 MIL << "Executing: " << cmd << endl;
926 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
929 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
930 WAR << " " << output;
931 cmd << " " << output;
934 int ret = prog.close();
937 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
938 ex.remember( cmd.str() );
942 ret = filesystem::rename( tmpsolv, rpmsolv );
944 ZYPP_THROW(Exception("Failed to move cache to final destination"));
945 // if this fails, don't bother throwing exceptions
946 filesystem::chmod( rpmsolv, 0644 );
948 rpmstatus.saveToCookieFile(rpmsolvcookie);
951 guard.resetDispose();
953 // Finally send notification to plugins
954 // NOTE: quick hack looking for spacewalk plugin only
956 Pathname script( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"system/spacewalk" ) );
957 if ( PathInfo( script ).isX() )
959 PluginScript spacewalk( script );
962 PluginFrame notify( "PACKAGESETCHANGED" );
963 spacewalk.send( notify );
965 PluginFrame ret( spacewalk.receive() );
967 if ( ret.command() == "ERROR" )
968 ret.writeTo( WAR ) << endl;
970 catch ( const Exception & excpt )
972 WAR << excpt.asUserHistory() << endl;
976 return build_rpm_solv;
979 void TargetImpl::reload()
984 void TargetImpl::unload()
986 Repository system( sat::Pool::instance().findSystemRepo() );
988 system.eraseFromPool();
991 void TargetImpl::load( bool force )
993 bool newCache = buildCache();
994 MIL << "New cache built: " << (newCache?"true":"false") <<
995 ", force loading: " << (force?"true":"false") << endl;
997 // now add the repos to the pool
998 sat::Pool satpool( sat::Pool::instance() );
999 Pathname rpmsolv( solvfilesPath() / "solv" );
1000 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
1002 // Providing an empty system repo, unload any old content
1003 Repository system( sat::Pool::instance().findSystemRepo() );
1005 if ( system && ! system.solvablesEmpty() )
1007 if ( newCache || force )
1009 system.eraseFromPool(); // invalidates system
1013 return; // nothing to do
1019 system = satpool.systemRepo();
1024 MIL << "adding " << rpmsolv << " to system" << endl;
1025 system.addSolv( rpmsolv );
1027 catch ( const Exception & exp )
1030 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1034 system.addSolv( rpmsolv );
1037 // (Re)Load the requested locales et al.
1038 // If the requested locales are empty, we leave the pool untouched
1039 // to avoid undoing changes the application applied. We expect this
1040 // to happen on a bare metal installation only. An already existing
1041 // target should be loaded before its settings are changed.
1043 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1044 if ( ! requestedLocales.empty() )
1046 satpool.setRequestedLocales( requestedLocales );
1050 SoftLocksFile::Data softLocks( _softLocksFile.data() );
1051 if ( ! softLocks.empty() )
1053 // Don't soft lock any installed item.
1054 for_( it, system.solvablesBegin(), system.solvablesEnd() )
1056 softLocks.erase( it->ident() );
1058 ResPool::instance().setAutoSoftLocks( softLocks );
1061 if ( ZConfig::instance().apply_locks_file() )
1063 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1064 if ( ! hardLocks.empty() )
1066 ResPool::instance().setHardLockQueries( hardLocks );
1070 // now that the target is loaded, we can cache the flavor
1071 createLastDistributionFlavorCache();
1073 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1076 ///////////////////////////////////////////////////////////////////
1080 ///////////////////////////////////////////////////////////////////
1081 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1083 // ----------------------------------------------------------------- //
1084 ZYppCommitPolicy policy_r( policy_rX );
1086 // Fake outstanding YCP fix: Honour restriction to media 1
1087 // at installation, but install all remaining packages if post-boot.
1088 if ( policy_r.restrictToMedia() > 1 )
1089 policy_r.allMedia();
1091 if ( policy_r.downloadMode() == DownloadDefault ) {
1092 if ( root() == "/" )
1093 policy_r.downloadMode(DownloadInHeaps);
1095 policy_r.downloadMode(DownloadAsNeeded);
1097 // DownloadOnly implies dry-run.
1098 else if ( policy_r.downloadMode() == DownloadOnly )
1099 policy_r.dryRun( true );
1100 // ----------------------------------------------------------------- //
1102 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1104 ///////////////////////////////////////////////////////////////////
1105 // Prepare execution of commit plugins:
1106 ///////////////////////////////////////////////////////////////////
1107 CommitPlugins commitPlugins;
1108 if ( root() == "/" && ! policy_r.dryRun() )
1110 Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
1111 commitPlugins.load( plugindir );
1114 ///////////////////////////////////////////////////////////////////
1115 // Write out a testcase if we're in dist upgrade mode.
1116 ///////////////////////////////////////////////////////////////////
1117 if ( getZYpp()->resolver()->upgradeMode() )
1119 if ( ! policy_r.dryRun() )
1121 writeUpgradeTestcase();
1125 DBG << "dryRun: Not writing upgrade testcase." << endl;
1129 ///////////////////////////////////////////////////////////////////
1130 // Store non-package data:
1131 ///////////////////////////////////////////////////////////////////
1132 if ( ! policy_r.dryRun() )
1134 filesystem::assert_dir( home() );
1135 // requested locales
1136 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1139 SoftLocksFile::Data newdata;
1140 pool_r.getActiveSoftLocks( newdata );
1141 _softLocksFile.setData( newdata );
1144 if ( ZConfig::instance().apply_locks_file() )
1146 HardLocksFile::Data newdata;
1147 pool_r.getHardLockQueries( newdata );
1148 _hardLocksFile.setData( newdata );
1153 DBG << "dryRun: Not stroring non-package data." << endl;
1156 ///////////////////////////////////////////////////////////////////
1157 // Compute transaction:
1158 ///////////////////////////////////////////////////////////////////
1159 ZYppCommitResult result( root() );
1160 result.rTransaction() = pool_r.resolver().getTransaction();
1161 result.rTransaction().order();
1162 // steps: this is our todo-list
1163 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1164 if ( policy_r.restrictToMedia() )
1166 // Collect until the 1st package from an unwanted media occurs.
1167 // Further collection could violate install order.
1168 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1169 for_( it, result.transaction().begin(), result.transaction().end() )
1171 if ( makeResObject( *it )->mediaNr() > 1 )
1173 steps.push_back( *it );
1178 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1180 MIL << "Todo: " << result << endl;
1182 ///////////////////////////////////////////////////////////////////
1183 // First collect and display all messages
1184 // associated with patches to be installed.
1185 ///////////////////////////////////////////////////////////////////
1186 if ( ! policy_r.dryRun() )
1188 for_( it, steps.begin(), steps.end() )
1190 if ( ! it->satSolvable().isKind<Patch>() )
1194 if ( ! pi.status().isToBeInstalled() )
1197 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1198 if ( ! patch ||patch->message().empty() )
1201 MIL << "Show message for " << patch << endl;
1202 callback::SendReport<target::PatchMessageReport> report;
1203 if ( ! report->show( patch ) )
1205 WAR << "commit aborted by the user" << endl;
1206 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1212 DBG << "dryRun: Not checking patch messages." << endl;
1215 ///////////////////////////////////////////////////////////////////
1216 // Remove/install packages.
1217 ///////////////////////////////////////////////////////////////////
1218 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1219 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1221 // Prepare the package cache. Pass all items requiring download.
1222 repo::RepoMediaAccess access;
1223 RepoProvidePackage repoProvidePackage( access, pool_r );
1224 CommitPackageCache packageCache( root() / "tmp", repoProvidePackage );
1225 packageCache.setCommitList( steps.begin(), steps.end() );
1228 if ( policy_r.downloadMode() != DownloadAsNeeded )
1230 // Preload the cache. Until now this means pre-loading all packages.
1231 // Once DownloadInHeaps is fully implemented, this will change and
1232 // we may actually have more than one heap.
1233 for_( it, steps.begin(), steps.end() )
1235 switch ( it->stepType() )
1237 case sat::Transaction::TRANSACTION_INSTALL:
1238 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1239 // proceed: only install actionas may require download.
1243 // next: no download for or non-packages and delete actions.
1249 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1251 ManagedFile localfile;
1254 // TODO: unify packageCache.get for Package and SrcPackage
1255 if ( pi->isKind<Package>() )
1257 localfile = packageCache.get( pi );
1259 else if ( pi->isKind<SrcPackage>() )
1261 repo::RepoMediaAccess access;
1262 repo::SrcPackageProvider prov( access );
1263 localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1267 INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1270 localfile.resetDispose(); // keep the package file in the cache
1272 catch ( const AbortRequestException & exp )
1274 it->stepStage( sat::Transaction::STEP_ERROR );
1276 WAR << "commit cache preload aborted by the user" << endl;
1277 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1280 catch ( const SkipRequestException & exp )
1283 it->stepStage( sat::Transaction::STEP_ERROR );
1285 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1288 catch ( const Exception & exp )
1290 // bnc #395704: missing catch causes abort.
1291 // TODO see if packageCache fails to handle errors correctly.
1293 it->stepStage( sat::Transaction::STEP_ERROR );
1295 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1304 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1306 else if ( ! policy_r.dryRun() )
1308 commit( policy_r, packageCache, result );
1312 DBG << "dryRun: Not installing/deleting anything." << endl;
1317 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1320 ///////////////////////////////////////////////////////////////////
1321 // Try to rebuild solv file while rpm database is still in cache
1322 ///////////////////////////////////////////////////////////////////
1323 if ( ! policy_r.dryRun() )
1328 // for DEPRECATED old ZyppCommitResult results:
1329 ///////////////////////////////////////////////////////////////////
1330 // build return statistics
1331 ///////////////////////////////////////////////////////////////////
1332 result._errors.clear();
1333 result._remaining.clear();
1334 result._srcremaining.clear();
1335 unsigned toInstall = 0;
1336 for_( step, steps.begin(), steps.end() )
1338 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1340 // For non-packages only products might have beed installed.
1341 // All the rest is ignored.
1342 if ( step->satSolvable().isSystem() || ! step->satSolvable().isKind<Product>() )
1345 else if ( step->stepType() == sat::Transaction::TRANSACTION_ERASE )
1351 switch ( step->stepStage() )
1353 case sat::Transaction::STEP_TODO:
1354 if ( step->satSolvable().isKind<Package>() )
1355 result._remaining.push_back( PoolItem( *step ) );
1356 else if ( step->satSolvable().isKind<SrcPackage>() )
1357 result._srcremaining.push_back( PoolItem( *step ) );
1359 case sat::Transaction::STEP_DONE:
1362 case sat::Transaction::STEP_ERROR:
1363 result._errors.push_back( PoolItem( *step ) );
1367 result._result = (toInstall - result._remaining.size());
1368 ///////////////////////////////////////////////////////////////////
1370 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1374 ///////////////////////////////////////////////////////////////////
1378 ///////////////////////////////////////////////////////////////////
1379 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1380 CommitPackageCache & packageCache_r,
1381 ZYppCommitResult & result_r )
1383 // steps: this is our todo-list
1384 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1385 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1388 std::vector<sat::Solvable> successfullyInstalledPackages;
1389 TargetImpl::PoolItemList remaining;
1391 for_( step, steps.begin(), steps.end() )
1393 PoolItem citem( *step );
1394 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1396 if ( citem->isKind<Package>() )
1398 // for packages this means being obsoleted (by rpm)
1399 // thius no additional action is needed.
1400 step->stepStage( sat::Transaction::STEP_DONE );
1405 if ( citem->isKind<Package>() )
1407 Package::constPtr p = citem->asKind<Package>();
1408 if ( citem.status().isToBeInstalled() )
1410 ManagedFile localfile;
1413 localfile = packageCache_r.get( citem );
1415 catch ( const AbortRequestException &e )
1417 WAR << "commit aborted by the user" << endl;
1419 step->stepStage( sat::Transaction::STEP_ERROR );
1422 catch ( const SkipRequestException &e )
1425 WAR << "Skipping package " << p << " in commit" << endl;
1426 step->stepStage( sat::Transaction::STEP_ERROR );
1429 catch ( const Exception &e )
1431 // bnc #395704: missing catch causes abort.
1432 // TODO see if packageCache fails to handle errors correctly.
1434 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1435 step->stepStage( sat::Transaction::STEP_ERROR );
1439 #warning Exception handling
1440 // create a installation progress report proxy
1441 RpmInstallPackageReceiver progress( citem.resolvable() );
1442 progress.connect(); // disconnected on destruction.
1444 bool success = false;
1445 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1446 // Why force and nodeps?
1448 // Because zypp builds the transaction and the resolver asserts that
1449 // everything is fine.
1450 // We use rpm just to unpack and register the package in the database.
1451 // We do this step by step, so rpm is not aware of the bigger context.
1452 // So we turn off rpms internal checks, because we do it inside zypp.
1453 flags |= rpm::RPMINST_NODEPS;
1454 flags |= rpm::RPMINST_FORCE;
1456 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1457 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1458 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1459 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1463 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1464 rpm().installPackage( localfile, flags );
1465 HistoryLog().install(citem);
1467 if ( progress.aborted() )
1469 WAR << "commit aborted by the user" << endl;
1470 localfile.resetDispose(); // keep the package file in the cache
1472 step->stepStage( sat::Transaction::STEP_ERROR );
1478 step->stepStage( sat::Transaction::STEP_DONE );
1481 catch ( Exception & excpt_r )
1483 ZYPP_CAUGHT(excpt_r);
1484 localfile.resetDispose(); // keep the package file in the cache
1486 if ( policy_r.dryRun() )
1488 WAR << "dry run failed" << endl;
1489 step->stepStage( sat::Transaction::STEP_ERROR );
1493 if ( progress.aborted() )
1495 WAR << "commit aborted by the user" << endl;
1500 WAR << "Install failed" << endl;
1502 step->stepStage( sat::Transaction::STEP_ERROR );
1506 if ( success && !policy_r.dryRun() )
1508 citem.status().resetTransact( ResStatus::USER );
1509 successfullyInstalledPackages.push_back( citem.satSolvable() );
1510 step->stepStage( sat::Transaction::STEP_DONE );
1515 RpmRemovePackageReceiver progress( citem.resolvable() );
1516 progress.connect(); // disconnected on destruction.
1518 bool success = false;
1519 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1520 flags |= rpm::RPMINST_NODEPS;
1521 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1524 rpm().removePackage( p, flags );
1525 HistoryLog().remove(citem);
1527 if ( progress.aborted() )
1529 WAR << "commit aborted by the user" << endl;
1531 step->stepStage( sat::Transaction::STEP_ERROR );
1537 step->stepStage( sat::Transaction::STEP_DONE );
1540 catch (Exception & excpt_r)
1542 ZYPP_CAUGHT( excpt_r );
1543 if ( progress.aborted() )
1545 WAR << "commit aborted by the user" << endl;
1547 step->stepStage( sat::Transaction::STEP_ERROR );
1551 WAR << "removal of " << p << " failed";
1552 step->stepStage( sat::Transaction::STEP_ERROR );
1554 if ( success && !policy_r.dryRun() )
1556 citem.status().resetTransact( ResStatus::USER );
1557 step->stepStage( sat::Transaction::STEP_DONE );
1561 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1563 // Status is changed as the buddy package buddy
1564 // gets installed/deleted. Handle non-buddies only.
1565 if ( ! citem.buddy() )
1567 if ( citem->isKind<Product>() )
1569 Product::constPtr p = citem->asKind<Product>();
1570 if ( citem.status().isToBeInstalled() )
1572 ERR << "Can't install orphan product without release-package! " << citem << endl;
1576 // Deleting the corresponding product entry is all we con do.
1577 // So the product will no longer be visible as installed.
1578 std::string referenceFilename( p->referenceFilename() );
1579 if ( referenceFilename.empty() )
1581 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1585 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1586 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1588 ERR << "Delete orphan product failed: " << referenceFile << endl;
1593 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1595 // SrcPackage is install-only
1596 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1597 installSrcPackage( p );
1600 citem.status().resetTransact( ResStatus::USER );
1601 step->stepStage( sat::Transaction::STEP_DONE );
1604 } // other resolvables
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 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1655 if ( baseproduct.isFile() )
1659 return parser::ProductFileReader::scanFile( baseproduct.path() );
1661 catch ( const Exception & excpt )
1663 ZYPP_CAUGHT( excpt );
1666 return parser::ProductFileData();
1669 inline Pathname staticGuessRoot( const Pathname & root_r )
1671 if ( root_r.empty() )
1673 // empty root: use existing Target or assume "/"
1674 Pathname ret ( ZConfig::instance().systemRoot() );
1676 return Pathname("/");
1682 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1684 std::ifstream idfile( file_r.c_str() );
1685 for( iostr::EachLine in( idfile ); in; in.next() )
1687 std::string line( str::trim( *in ) );
1688 if ( ! line.empty() )
1691 return std::string();
1694 ///////////////////////////////////////////////////////////////////
1696 Product::constPtr TargetImpl::baseProduct() const
1698 ResPool pool(ResPool::instance());
1699 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1701 Product::constPtr p = (*it)->asKind<Product>();
1702 if ( p->isTargetDistribution() )
1708 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1710 const Pathname needroot( staticGuessRoot(root_r) );
1711 const Target_constPtr target( getZYpp()->getTarget() );
1712 if ( target && target->root() == needroot )
1713 return target->requestedLocales();
1714 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1717 std::string TargetImpl::targetDistribution() const
1718 { return baseproductdata( _root ).registerTarget(); }
1720 std::string TargetImpl::targetDistribution( const Pathname & root_r )
1721 { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1723 std::string TargetImpl::targetDistributionRelease() const
1724 { return baseproductdata( _root ).registerRelease(); }
1726 std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1727 { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1729 Target::DistributionLabel TargetImpl::distributionLabel() const
1731 Target::DistributionLabel ret;
1732 parser::ProductFileData pdata( baseproductdata( _root ) );
1733 ret.shortName = pdata.shortName();
1734 ret.summary = pdata.summary();
1738 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1740 Target::DistributionLabel ret;
1741 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1742 ret.shortName = pdata.shortName();
1743 ret.summary = pdata.summary();
1747 std::string TargetImpl::distributionVersion() const
1749 if ( _distributionVersion.empty() )
1751 _distributionVersion = TargetImpl::distributionVersion(root());
1752 if ( !_distributionVersion.empty() )
1753 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1755 return _distributionVersion;
1758 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1760 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1761 if ( distributionVersion.empty() )
1763 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1764 // On RHEL, Fedora and others the "product version" is determined by the first package
1765 // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1766 // with the $distroverpkg variable.
1767 scoped_ptr<rpm::RpmDb> tmprpmdb;
1768 if ( ZConfig::instance().systemRoot() == Pathname() )
1772 tmprpmdb.reset( new rpm::RpmDb );
1773 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1780 rpm::librpmDb::db_const_iterator it;
1781 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1782 distributionVersion = it->tag_version();
1784 return distributionVersion;
1788 std::string TargetImpl::distributionFlavor() const
1790 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1793 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1795 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1798 ///////////////////////////////////////////////////////////////////
1800 std::string TargetImpl::anonymousUniqueId() const
1802 return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1805 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1807 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1810 ///////////////////////////////////////////////////////////////////
1812 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1814 // provide on local disk
1815 ManagedFile localfile = provideSrcPackage(srcPackage_r);
1817 rpm().installPackage ( localfile );
1820 ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1822 // provide on local disk
1823 repo::RepoMediaAccess access_r;
1824 repo::SrcPackageProvider prov( access_r );
1825 return prov.provideSrcPackage( srcPackage_r );
1827 ////////////////////////////////////////////////////////////////
1828 } // namespace target
1829 ///////////////////////////////////////////////////////////////////
1830 /////////////////////////////////////////////////////////////////
1832 ///////////////////////////////////////////////////////////////////