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 PluginScript plugin( pi_r.path() );
150 plugin.send( PluginFrame( "PLUGINBEGIN" ) );
151 PluginFrame ret( plugin.receive() );
152 if ( ret.isAckCommand() )
154 _scripts.push_back( plugin );
158 WAR << "Failed to load plugin: Bad plugin response." << endl;
161 catch( const zypp::Exception & )
163 WAR << "Failed to load plugin." << endl;
168 std::list<PluginScript> _scripts;
171 void testCommitPlugins( const Pathname & path_r ) // for testing only
173 USR << "+++++" << endl;
177 USR << "=====" << endl;
179 USR << "-----" << endl;
182 ///////////////////////////////////////////////////////////////////
184 /** \internal Manage writing a new testcase when doing an upgrade. */
185 void writeUpgradeTestcase()
187 unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
188 MIL << "Testcases to keep: " << toKeep << endl;
191 Target_Ptr target( getZYpp()->getTarget() );
194 WAR << "No Target no Testcase!" << endl;
198 std::string stem( "updateTestcase" );
199 Pathname dir( target->assertRootPrefix("/var/log/") );
200 Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
203 std::list<std::string> content;
204 filesystem::readdir( content, dir, /*dots*/false );
205 std::set<std::string> cases;
206 for_( c, content.begin(), content.end() )
208 if ( str::startsWith( *c, stem ) )
211 if ( cases.size() >= toKeep )
213 unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
214 for_( c, cases.begin(), cases.end() )
216 filesystem::recursive_rmdir( dir/(*c) );
223 MIL << "Write new testcase " << next << endl;
224 getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
227 ///////////////////////////////////////////////////////////////////
229 { /////////////////////////////////////////////////////////////////
231 /** Execute script and report against report_r.
232 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
233 * execution was successfull (<tt>first = true</tt>), or the desired
234 * \c PatchScriptReport::Action in case execution failed
235 * (<tt>first = false</tt>).
237 * \note The packager is responsible for setting the correct permissions
238 * of the script. If the script is not executable it is reported as an
239 * error. We must not modify the permessions.
241 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
242 const Pathname & script_r,
243 callback::SendReport<PatchScriptReport> & report_r )
245 MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
247 HistoryLog historylog;
248 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
249 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
251 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
253 historylog.comment(output);
254 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
256 WAR << "User request to abort script " << script_r << endl;
258 // the rest is handled by exit code evaluation
259 // in case the script has meanwhile finished.
263 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
265 if ( prog.close() != 0 )
267 ret.second = report_r->problem( prog.execError() );
268 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
269 std::ostringstream sstr;
270 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
271 historylog.comment(sstr.str(), /*timestamp*/true);
280 /** Execute script and report against report_r.
281 * Return \c false if user requested \c ABORT.
283 bool executeScript( const Pathname & root_r,
284 const Pathname & script_r,
285 callback::SendReport<PatchScriptReport> & report_r )
287 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
290 action = doExecuteScript( root_r, script_r, report_r );
292 return true; // success
294 switch ( action.second )
296 case PatchScriptReport::ABORT:
297 WAR << "User request to abort at script " << script_r << endl;
298 return false; // requested abort.
301 case PatchScriptReport::IGNORE:
302 WAR << "User request to skip script " << script_r << endl;
303 return true; // requested skip.
306 case PatchScriptReport::RETRY:
309 } while ( action.second == PatchScriptReport::RETRY );
311 // THIS is not intended to be reached:
312 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
313 return false; // abort.
316 /** Look for update scripts named 'name-version-release-*' and
317 * execute them. Return \c false if \c ABORT was requested.
319 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
321 bool RunUpdateScripts( const Pathname & root_r,
322 const Pathname & scriptsPath_r,
323 const std::vector<sat::Solvable> & checkPackages_r,
326 if ( checkPackages_r.empty() )
327 return true; // no installed packages to check
329 MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
330 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
331 if ( ! PathInfo( scriptsDir ).isDir() )
332 return true; // no script dir
334 std::list<std::string> scripts;
335 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
336 if ( scripts.empty() )
337 return true; // no scripts in script dir
339 // Now collect and execute all matching scripts.
340 // On ABORT: at least log all outstanding scripts.
341 // - "name-version-release"
342 // - "name-version-release-*"
344 std::map<std::string, Pathname> unify; // scripts <md5,path>
345 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
347 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
348 for_( sit, scripts.begin(), scripts.end() )
350 if ( ! str::hasPrefix( *sit, prefix ) )
353 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
354 continue; // if not exact match it had to continue with '-'
356 PathInfo script( scriptsDir / *sit );
357 if ( ! script.isFile() )
360 // Assert it's set executable
361 filesystem::addmod( script.path(), 0500 );
363 Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
365 // Unify scripts by md5sum
366 std::string md5sum( filesystem::md5sum( script.path() ) );
367 if ( unify[md5sum].empty() )
369 unify[md5sum] = localPath;
373 // translators: We may find the same script content in files with different names.
374 // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
375 // message for a log file. Preferably start translation with "%s"
376 std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[md5sum].c_str() ) );
377 MIL << "Skip update script: " << msg << endl;
378 HistoryLog().comment( msg, /*timestamp*/true );
382 if ( abort || aborting_r )
384 WAR << "Aborting: Skip update script " << *sit << endl;
385 HistoryLog().comment(
386 localPath.asString() + _(" execution skipped while aborting"),
391 MIL << "Found update script " << *sit << endl;
392 callback::SendReport<PatchScriptReport> report;
393 report->start( make<Package>( *it ), script.path() );
395 if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
396 abort = true; // requested abort.
403 ///////////////////////////////////////////////////////////////////
405 ///////////////////////////////////////////////////////////////////
407 inline void copyTo( std::ostream & out_r, const Pathname & file_r )
409 std::ifstream infile( file_r.c_str() );
410 for( iostr::EachLine in( infile ); in; in.next() )
412 out_r << *in << endl;
416 inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
418 std::string ret( cmd_r );
419 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
420 SUBST_IF( "%p", notification_r.solvable().asString() );
421 SUBST_IF( "%P", notification_r.file().asString() );
426 void sendNotification( const Pathname & root_r,
427 const UpdateNotifications & notifications_r )
429 if ( notifications_r.empty() )
432 std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
433 MIL << "Notification command is '" << cmdspec << "'" << endl;
434 if ( cmdspec.empty() )
437 std::string::size_type pos( cmdspec.find( '|' ) );
438 if ( pos == std::string::npos )
440 ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
441 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
445 std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
446 std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
448 enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
449 Format format = UNKNOWN;
450 if ( formatStr == "none" )
452 else if ( formatStr == "single" )
454 else if ( formatStr == "digest" )
456 else if ( formatStr == "bulk" )
460 ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
461 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
465 // Take care: commands are ececuted chroot(root_r). The message file
466 // pathnames in notifications_r are local to root_r. For physical access
467 // to the file they need to be prefixed.
469 if ( format == NONE || format == SINGLE )
471 for_( it, notifications_r.begin(), notifications_r.end() )
473 std::vector<std::string> command;
474 if ( format == SINGLE )
475 command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
476 str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
478 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
479 if ( true ) // Wait for feedback
481 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
485 int ret = prog.close();
488 ERR << "Notification command returned with error (" << ret << ")." << endl;
489 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
495 else if ( format == DIGEST || format == BULK )
497 filesystem::TmpFile tmpfile;
498 ofstream out( tmpfile.path().c_str() );
499 for_( it, notifications_r.begin(), notifications_r.end() )
501 if ( format == DIGEST )
503 out << it->file() << endl;
505 else if ( format == BULK )
507 copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
511 std::vector<std::string> command;
512 command.push_back( "<"+tmpfile.path().asString() ); // redirect input
513 str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
515 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
516 if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
518 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
522 int ret = prog.close();
525 ERR << "Notification command returned with error (" << ret << ")." << endl;
526 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
533 INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
534 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
540 /** Look for update messages named 'name-version-release-*' and
541 * send notification according to \ref ZConfig::updateMessagesNotify.
543 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
545 void RunUpdateMessages( const Pathname & root_r,
546 const Pathname & messagesPath_r,
547 const std::vector<sat::Solvable> & checkPackages_r,
548 ZYppCommitResult & result_r )
550 if ( checkPackages_r.empty() )
551 return; // no installed packages to check
553 MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
554 Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
555 if ( ! PathInfo( messagesDir ).isDir() )
556 return; // no messages dir
558 std::list<std::string> messages;
559 filesystem::readdir( messages, messagesDir, /*dots*/false );
560 if ( messages.empty() )
561 return; // no messages in message dir
563 // Now collect all matching messages in result and send them
564 // - "name-version-release"
565 // - "name-version-release-*"
566 HistoryLog historylog;
567 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
569 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
570 for_( sit, messages.begin(), messages.end() )
572 if ( ! str::hasPrefix( *sit, prefix ) )
575 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
576 continue; // if not exact match it had to continue with '-'
578 PathInfo message( messagesDir / *sit );
579 if ( ! message.isFile() || message.size() == 0 )
582 MIL << "Found update message " << *sit << endl;
583 Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
584 result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
585 historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
588 sendNotification( root_r, result_r.updateMessages() );
591 /////////////////////////////////////////////////////////////////
593 ///////////////////////////////////////////////////////////////////
595 void XRunUpdateMessages( const Pathname & root_r,
596 const Pathname & messagesPath_r,
597 const std::vector<sat::Solvable> & checkPackages_r,
598 ZYppCommitResult & result_r )
599 { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
601 /** Helper for PackageProvider queries during commit. */
602 struct QueryInstalledEditionHelper
604 bool operator()( const std::string & name_r,
605 const Edition & ed_r,
606 const Arch & arch_r ) const
608 rpm::librpmDb::db_const_iterator it;
609 for ( it.findByName( name_r ); *it; ++it )
611 if ( arch_r == it->tag_arch()
612 && ( ed_r == Edition::noedition || ed_r == it->tag_edition() ) )
622 * \short Let the Source provide the package.
623 * \p pool_r \ref ResPool used to get candidates
624 * \p pi item to be commited
626 struct RepoProvidePackage
629 repo::RepoMediaAccess &_access;
631 RepoProvidePackage( repo::RepoMediaAccess &access, ResPool pool_r )
632 : _pool(pool_r), _access(access)
635 ManagedFile operator()( const PoolItem & pi )
637 // Redirect PackageProvider queries for installed editions
638 // (in case of patch/delta rpm processing) to rpmDb.
639 repo::PackageProviderPolicy packageProviderPolicy;
640 packageProviderPolicy.queryInstalledCB( QueryInstalledEditionHelper() );
642 Package::constPtr p = asKind<Package>(pi.resolvable());
644 // Build a repository list for repos
645 // contributing to the pool
646 std::list<Repository> repos( _pool.knownRepositoriesBegin(), _pool.knownRepositoriesEnd() );
647 repo::DeltaCandidates deltas(repos, p->name());
648 repo::PackageProvider pkgProvider( _access, p, deltas, packageProviderPolicy );
650 ManagedFile ret( pkgProvider.providePackage() );
654 ///////////////////////////////////////////////////////////////////
656 IMPL_PTR_TYPE(TargetImpl);
658 TargetImpl_Ptr TargetImpl::_nullimpl;
660 /** Null implementation */
661 TargetImpl_Ptr TargetImpl::nullimpl()
664 _nullimpl = new TargetImpl;
668 ///////////////////////////////////////////////////////////////////
670 // METHOD NAME : TargetImpl::TargetImpl
671 // METHOD TYPE : Ctor
673 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
675 , _requestedLocalesFile( home() / "RequestedLocales" )
676 , _softLocksFile( home() / "SoftLocks" )
677 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
679 _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
681 HistoryLog::setRoot(_root);
685 MIL << "Initialized target on " << _root << endl;
689 * generates a random id using uuidgen
691 static std::string generateRandomId()
693 std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
694 return iostr::getline( uuidprovider );
698 * updates the content of \p filename
699 * if \p condition is true, setting the content
700 * the the value returned by \p value
702 void updateFileContent( const Pathname &filename,
703 boost::function<bool ()> condition,
704 boost::function<string ()> value )
706 string val = value();
707 // if the value is empty, then just dont
708 // do anything, regardless of the condition
714 MIL << "updating '" << filename << "' content." << endl;
716 // if the file does not exist we need to generate the uuid file
718 std::ofstream filestr;
719 // make sure the path exists
720 filesystem::assert_dir( filename.dirname() );
721 filestr.open( filename.c_str() );
723 if ( filestr.good() )
730 // FIXME, should we ignore the error?
731 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
736 /** helper functor */
737 static bool fileMissing( const Pathname &pathname )
739 return ! PathInfo(pathname).isExist();
742 void TargetImpl::createAnonymousId() const
745 // create the anonymous unique id
746 // this value is used for statistics
747 Pathname idpath( home() / "AnonymousUniqueId");
751 updateFileContent( idpath,
752 boost::bind(fileMissing, idpath),
755 catch ( const Exception &e )
757 WAR << "Can't create anonymous id file" << endl;
762 void TargetImpl::createLastDistributionFlavorCache() const
764 // create the anonymous unique id
765 // this value is used for statistics
766 Pathname flavorpath( home() / "LastDistributionFlavor");
768 // is there a product
769 Product::constPtr p = baseProduct();
772 WAR << "No base product, I won't create flavor cache" << endl;
776 string flavor = p->flavor();
781 updateFileContent( flavorpath,
782 // only if flavor is not empty
783 functor::Constant<bool>( ! flavor.empty() ),
784 functor::Constant<string>(flavor) );
786 catch ( const Exception &e )
788 WAR << "Can't create flavor cache" << endl;
793 ///////////////////////////////////////////////////////////////////
795 // METHOD NAME : TargetImpl::~TargetImpl
796 // METHOD TYPE : Dtor
798 TargetImpl::~TargetImpl()
800 _rpm.closeDatabase();
801 MIL << "Targets closed" << endl;
804 ///////////////////////////////////////////////////////////////////
806 // solv file handling
808 ///////////////////////////////////////////////////////////////////
810 Pathname TargetImpl::defaultSolvfilesPath() const
812 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
815 void TargetImpl::clearCache()
817 Pathname base = solvfilesPath();
818 filesystem::recursive_rmdir( base );
821 void TargetImpl::buildCache()
823 Pathname base = solvfilesPath();
824 Pathname rpmsolv = base/"solv";
825 Pathname rpmsolvcookie = base/"cookie";
827 bool build_rpm_solv = true;
828 // lets see if the rpm solv cache exists
830 RepoStatus rpmstatus( RepoStatus( _root/"/var/lib/rpm/Name" )
831 && (_root/"/etc/products.d") );
833 bool solvexisted = PathInfo(rpmsolv).isExist();
836 // see the status of the cache
837 PathInfo cookie( rpmsolvcookie );
838 MIL << "Read cookie: " << cookie << endl;
839 if ( cookie.isExist() )
841 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
842 // now compare it with the rpm database
843 if ( status.checksum() == rpmstatus.checksum() )
844 build_rpm_solv = false;
845 MIL << "Read cookie: " << rpmsolvcookie << " says: "
846 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
850 if ( build_rpm_solv )
852 // if the solvfile dir does not exist yet, we better create it
853 filesystem::assert_dir( base );
855 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
857 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
860 // Can't create temporary solv file, usually due to insufficient permission
861 // (user query while @System solv needs refresh). If so, try switching
862 // to a location within zypps temp. space (will be cleaned at application end).
864 bool switchingToTmpSolvfile = false;
865 Exception ex("Failed to cache rpm database.");
866 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
868 if ( ! solvfilesPathIsTemp() )
870 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
871 rpmsolv = base/"solv";
872 rpmsolvcookie = base/"cookie";
874 filesystem::assert_dir( base );
875 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
879 WAR << "Using a temporary solv file at " << base << endl;
880 switchingToTmpSolvfile = true;
881 _tmpSolvfilesPath = base;
885 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
889 if ( ! switchingToTmpSolvfile )
895 // Take care we unlink the solvfile on exception
896 ManagedFile guard( base, filesystem::recursive_rmdir );
898 std::ostringstream cmd;
900 if ( ! _root.empty() )
901 cmd << " -r '" << _root << "'";
903 cmd << " -p '" << Pathname::assertprefix( _root, "/etc/products.d" ) << "'";
905 if ( ! oldSolvFile.empty() )
906 cmd << " '" << oldSolvFile << "'";
908 cmd << " > '" << tmpsolv.path() << "'";
910 MIL << "Executing: " << cmd << endl;
911 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
914 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
915 WAR << " " << output;
916 cmd << " " << output;
919 int ret = prog.close();
922 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
923 ex.remember( cmd.str() );
927 ret = filesystem::rename( tmpsolv, rpmsolv );
929 ZYPP_THROW(Exception("Failed to move cache to final destination"));
930 // if this fails, don't bother throwing exceptions
931 filesystem::chmod( rpmsolv, 0644 );
933 rpmstatus.saveToCookieFile(rpmsolvcookie);
936 guard.resetDispose();
938 // Finally send notification to plugins
939 // NOTE: quick hack looking for spacewalk plugin only
941 Pathname script( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"system/spacewalk" ) );
942 if ( PathInfo( script ).isX() )
944 PluginScript spacewalk( script );
947 PluginFrame notify( "PACKAGESETCHANGED" );
948 spacewalk.send( notify );
950 PluginFrame ret( spacewalk.receive() );
952 if ( ret.command() == "ERROR" )
953 ret.writeTo( WAR ) << endl;
955 catch ( const Exception & excpt )
957 WAR << excpt.asUserHistory() << endl;
963 void TargetImpl::unload()
965 Repository system( sat::Pool::instance().findSystemRepo() );
967 system.eraseFromPool();
971 void TargetImpl::load()
975 // now add the repos to the pool
976 sat::Pool satpool( sat::Pool::instance() );
977 Pathname rpmsolv( solvfilesPath() / "solv" );
978 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
980 // Providing an empty system repo, unload any old content
981 Repository system( sat::Pool::instance().findSystemRepo() );
982 if ( system && ! system.solvablesEmpty() )
984 system.eraseFromPool(); // invalidates system
988 system = satpool.systemRepo();
993 system.addSolv( rpmsolv );
995 catch ( const Exception & exp )
998 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1002 system.addSolv( rpmsolv );
1005 // (Re)Load the requested locales et al.
1006 // If the requested locales are empty, we leave the pool untouched
1007 // to avoid undoing changes the application applied. We expect this
1008 // to happen on a bare metal installation only. An already existing
1009 // target should be loaded before its settings are changed.
1011 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1012 if ( ! requestedLocales.empty() )
1014 satpool.setRequestedLocales( requestedLocales );
1018 SoftLocksFile::Data softLocks( _softLocksFile.data() );
1019 if ( ! softLocks.empty() )
1021 // Don't soft lock any installed item.
1022 for_( it, system.solvablesBegin(), system.solvablesEnd() )
1024 softLocks.erase( it->ident() );
1026 ResPool::instance().setAutoSoftLocks( softLocks );
1029 if ( ZConfig::instance().apply_locks_file() )
1031 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1032 if ( ! hardLocks.empty() )
1034 ResPool::instance().setHardLockQueries( hardLocks );
1038 // now that the target is loaded, we can cache the flavor
1039 createLastDistributionFlavorCache();
1041 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1044 ///////////////////////////////////////////////////////////////////
1048 ///////////////////////////////////////////////////////////////////
1049 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1051 // ----------------------------------------------------------------- //
1052 ZYppCommitPolicy policy_r( policy_rX );
1054 // Fake outstanding YCP fix: Honour restriction to media 1
1055 // at installation, but install all remaining packages if post-boot.
1056 if ( policy_r.restrictToMedia() > 1 )
1057 policy_r.allMedia();
1059 if ( policy_r.downloadMode() == DownloadDefault ) {
1060 if ( root() == "/" )
1061 policy_r.downloadMode(DownloadInHeaps);
1063 policy_r.downloadMode(DownloadAsNeeded);
1065 // DownloadOnly implies dry-run.
1066 else if ( policy_r.downloadMode() == DownloadOnly )
1067 policy_r.dryRun( true );
1068 // ----------------------------------------------------------------- //
1070 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1072 ///////////////////////////////////////////////////////////////////
1073 // Prepare execution of commit plugins:
1074 ///////////////////////////////////////////////////////////////////
1075 CommitPlugins commitPlugins;
1076 if ( root() == "/" && ! policy_r.dryRun() )
1078 Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
1079 commitPlugins.load( plugindir );
1082 ///////////////////////////////////////////////////////////////////
1083 // Write out a testcase if we're in dist upgrade mode.
1084 ///////////////////////////////////////////////////////////////////
1085 if ( getZYpp()->resolver()->upgradeMode() )
1087 if ( ! policy_r.dryRun() )
1089 writeUpgradeTestcase();
1093 DBG << "dryRun: Not writing upgrade testcase." << endl;
1097 ///////////////////////////////////////////////////////////////////
1098 // Store non-package data:
1099 ///////////////////////////////////////////////////////////////////
1100 if ( ! policy_r.dryRun() )
1102 filesystem::assert_dir( home() );
1103 // requested locales
1104 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1107 SoftLocksFile::Data newdata;
1108 pool_r.getActiveSoftLocks( newdata );
1109 _softLocksFile.setData( newdata );
1112 if ( ZConfig::instance().apply_locks_file() )
1114 HardLocksFile::Data newdata;
1115 pool_r.getHardLockQueries( newdata );
1116 _hardLocksFile.setData( newdata );
1121 DBG << "dryRun: Not stroring non-package data." << endl;
1124 ///////////////////////////////////////////////////////////////////
1125 // Compute transaction:
1126 ///////////////////////////////////////////////////////////////////
1127 ZYppCommitResult result( root() );
1128 result.rTransaction() = pool_r.resolver().getTransaction();
1129 result.rTransaction().order();
1130 // steps: this is our todo-list
1131 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1132 if ( policy_r.restrictToMedia() )
1134 // Collect until the 1st package from an unwanted media occurs.
1135 // Further collection could violate install order.
1136 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1137 for_( it, result.transaction().begin(), result.transaction().end() )
1139 if ( makeResObject( *it )->mediaNr() > 1 )
1141 steps.push_back( *it );
1146 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1148 MIL << "Todo: " << result << endl;
1150 ///////////////////////////////////////////////////////////////////
1151 // First collect and display all messages
1152 // associated with patches to be installed.
1153 ///////////////////////////////////////////////////////////////////
1154 if ( ! policy_r.dryRun() )
1156 for_( it, steps.begin(), steps.end() )
1158 if ( ! it->satSolvable().isKind<Patch>() )
1162 if ( ! pi.status().isToBeInstalled() )
1165 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1166 if ( ! patch ||patch->message().empty() )
1169 MIL << "Show message for " << patch << endl;
1170 callback::SendReport<target::PatchMessageReport> report;
1171 if ( ! report->show( patch ) )
1173 WAR << "commit aborted by the user" << endl;
1174 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1180 DBG << "dryRun: Not checking patch messages." << endl;
1183 ///////////////////////////////////////////////////////////////////
1184 // Remove/install packages.
1185 ///////////////////////////////////////////////////////////////////
1186 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1187 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1189 // Prepare the package cache. Pass all items requiring download.
1190 repo::RepoMediaAccess access;
1191 RepoProvidePackage repoProvidePackage( access, pool_r );
1192 CommitPackageCache packageCache( root() / "tmp", repoProvidePackage );
1193 packageCache.setCommitList( steps.begin(), steps.end() );
1196 if ( policy_r.downloadMode() != DownloadAsNeeded )
1198 // Preload the cache. Until now this means pre-loading all packages.
1199 // Once DownloadInHeaps is fully implemented, this will change and
1200 // we may actually have more than one heap.
1201 for_( it, steps.begin(), steps.end() )
1203 switch ( it->stepType() )
1205 case sat::Transaction::TRANSACTION_INSTALL:
1206 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1207 // proceed: only install actionas may require download.
1211 // next: no download for or non-packages and delete actions.
1217 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1219 ManagedFile localfile;
1222 // TODO: unify packageCache.get for Package and SrcPackage
1223 if ( pi->isKind<Package>() )
1225 localfile = packageCache.get( pi );
1227 else if ( pi->isKind<SrcPackage>() )
1229 repo::RepoMediaAccess access;
1230 repo::SrcPackageProvider prov( access );
1231 localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1235 INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1238 localfile.resetDispose(); // keep the package file in the cache
1240 catch ( const AbortRequestException & exp )
1242 it->stepStage( sat::Transaction::STEP_ERROR );
1244 WAR << "commit cache preload aborted by the user" << endl;
1245 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1248 catch ( const SkipRequestException & exp )
1251 it->stepStage( sat::Transaction::STEP_ERROR );
1253 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1256 catch ( const Exception & exp )
1258 // bnc #395704: missing catch causes abort.
1259 // TODO see if packageCache fails to handle errors correctly.
1261 it->stepStage( sat::Transaction::STEP_ERROR );
1263 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1272 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1274 else if ( ! policy_r.dryRun() )
1276 commit( policy_r, packageCache, result );
1280 DBG << "dryRun: Not installing/deleting anything." << endl;
1285 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1288 ///////////////////////////////////////////////////////////////////
1289 // Try to rebuild solv file while rpm database is still in cache
1290 ///////////////////////////////////////////////////////////////////
1291 if ( ! policy_r.dryRun() )
1296 // for DEPRECATED old ZyppCommitResult results:
1297 ///////////////////////////////////////////////////////////////////
1298 // build return statistics
1299 ///////////////////////////////////////////////////////////////////
1300 result._errors.clear();
1301 result._remaining.clear();
1302 result._srcremaining.clear();
1303 unsigned toInstall = 0;
1304 for_( step, steps.begin(), steps.end() )
1306 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1308 // For non-packages only products might have beed installed.
1309 // All the rest is ignored.
1310 if ( step->satSolvable().isSystem() || ! step->satSolvable().isKind<Product>() )
1313 else if ( step->stepType() == sat::Transaction::TRANSACTION_ERASE )
1319 switch ( step->stepStage() )
1321 case sat::Transaction::STEP_TODO:
1322 if ( step->satSolvable().isKind<Package>() )
1323 result._remaining.push_back( PoolItem( *step ) );
1324 else if ( step->satSolvable().isKind<SrcPackage>() )
1325 result._srcremaining.push_back( PoolItem( *step ) );
1327 case sat::Transaction::STEP_DONE:
1330 case sat::Transaction::STEP_ERROR:
1331 result._errors.push_back( PoolItem( *step ) );
1335 result._result = (toInstall - result._remaining.size());
1336 ///////////////////////////////////////////////////////////////////
1338 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1342 ///////////////////////////////////////////////////////////////////
1346 ///////////////////////////////////////////////////////////////////
1347 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1348 CommitPackageCache & packageCache_r,
1349 ZYppCommitResult & result_r )
1351 // steps: this is our todo-list
1352 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1353 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1356 std::vector<sat::Solvable> successfullyInstalledPackages;
1357 TargetImpl::PoolItemList remaining;
1359 for_( step, steps.begin(), steps.end() )
1361 PoolItem citem( *step );
1362 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1364 if ( citem->isKind<Package>() )
1366 // for packages this means being obsoleted (by rpm)
1367 // thius no additional action is needed.
1368 step->stepStage( sat::Transaction::STEP_DONE );
1373 if ( citem->isKind<Package>() )
1375 Package::constPtr p = citem->asKind<Package>();
1376 if ( citem.status().isToBeInstalled() )
1378 ManagedFile localfile;
1381 localfile = packageCache_r.get( citem );
1383 catch ( const AbortRequestException &e )
1385 WAR << "commit aborted by the user" << endl;
1387 step->stepStage( sat::Transaction::STEP_ERROR );
1390 catch ( const SkipRequestException &e )
1393 WAR << "Skipping package " << p << " in commit" << endl;
1394 step->stepStage( sat::Transaction::STEP_ERROR );
1397 catch ( const Exception &e )
1399 // bnc #395704: missing catch causes abort.
1400 // TODO see if packageCache fails to handle errors correctly.
1402 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1403 step->stepStage( sat::Transaction::STEP_ERROR );
1407 #warning Exception handling
1408 // create a installation progress report proxy
1409 RpmInstallPackageReceiver progress( citem.resolvable() );
1410 progress.connect(); // disconnected on destruction.
1412 bool success = false;
1413 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1414 // Why force and nodeps?
1416 // Because zypp builds the transaction and the resolver asserts that
1417 // everything is fine.
1418 // We use rpm just to unpack and register the package in the database.
1419 // We do this step by step, so rpm is not aware of the bigger context.
1420 // So we turn off rpms internal checks, because we do it inside zypp.
1421 flags |= rpm::RPMINST_NODEPS;
1422 flags |= rpm::RPMINST_FORCE;
1424 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1425 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1426 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1427 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1431 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1432 rpm().installPackage( localfile, flags );
1433 HistoryLog().install(citem);
1435 if ( progress.aborted() )
1437 WAR << "commit aborted by the user" << endl;
1438 localfile.resetDispose(); // keep the package file in the cache
1440 step->stepStage( sat::Transaction::STEP_ERROR );
1446 step->stepStage( sat::Transaction::STEP_DONE );
1449 catch ( Exception & excpt_r )
1451 ZYPP_CAUGHT(excpt_r);
1452 localfile.resetDispose(); // keep the package file in the cache
1454 if ( policy_r.dryRun() )
1456 WAR << "dry run failed" << endl;
1457 step->stepStage( sat::Transaction::STEP_ERROR );
1461 if ( progress.aborted() )
1463 WAR << "commit aborted by the user" << endl;
1468 WAR << "Install failed" << endl;
1470 step->stepStage( sat::Transaction::STEP_ERROR );
1474 if ( success && !policy_r.dryRun() )
1476 citem.status().resetTransact( ResStatus::USER );
1477 successfullyInstalledPackages.push_back( citem.satSolvable() );
1478 step->stepStage( sat::Transaction::STEP_DONE );
1483 RpmRemovePackageReceiver progress( citem.resolvable() );
1484 progress.connect(); // disconnected on destruction.
1486 bool success = false;
1487 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1488 flags |= rpm::RPMINST_NODEPS;
1489 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1492 rpm().removePackage( p, flags );
1493 HistoryLog().remove(citem);
1495 if ( progress.aborted() )
1497 WAR << "commit aborted by the user" << endl;
1499 step->stepStage( sat::Transaction::STEP_ERROR );
1505 step->stepStage( sat::Transaction::STEP_DONE );
1508 catch (Exception & excpt_r)
1510 ZYPP_CAUGHT( excpt_r );
1511 if ( progress.aborted() )
1513 WAR << "commit aborted by the user" << endl;
1515 step->stepStage( sat::Transaction::STEP_ERROR );
1519 WAR << "removal of " << p << " failed";
1520 step->stepStage( sat::Transaction::STEP_ERROR );
1522 if ( success && !policy_r.dryRun() )
1524 citem.status().resetTransact( ResStatus::USER );
1525 step->stepStage( sat::Transaction::STEP_DONE );
1529 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1531 // Status is changed as the buddy package buddy
1532 // gets installed/deleted. Handle non-buddies only.
1533 if ( ! citem.buddy() )
1535 if ( citem->isKind<Product>() )
1537 Product::constPtr p = citem->asKind<Product>();
1538 if ( citem.status().isToBeInstalled() )
1540 ERR << "Can't install orphan product without release-package! " << citem << endl;
1544 // Deleting the corresponding product entry is all we con do.
1545 // So the product will no longer be visible as installed.
1546 std::string referenceFilename( p->referenceFilename() );
1547 if ( referenceFilename.empty() )
1549 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1553 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1554 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1556 ERR << "Delete orphan product failed: " << referenceFile << endl;
1561 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1563 // SrcPackage is install-only
1564 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1565 installSrcPackage( p );
1568 citem.status().resetTransact( ResStatus::USER );
1569 step->stepStage( sat::Transaction::STEP_DONE );
1572 } // other resolvables
1576 // Check presence of update scripts/messages. If aborting,
1577 // at least log omitted scripts.
1578 if ( ! successfullyInstalledPackages.empty() )
1580 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1581 successfullyInstalledPackages, abort ) )
1583 WAR << "Commit aborted by the user" << endl;
1586 // send messages after scripts in case some script generates output,
1587 // that should be kept in t %ghost message file.
1588 RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1589 successfullyInstalledPackages,
1595 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1599 ///////////////////////////////////////////////////////////////////
1601 rpm::RpmDb & TargetImpl::rpm()
1606 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1608 return _rpm.hasFile(path_str, name_str);
1612 Date TargetImpl::timestamp() const
1614 return _rpm.timestamp();
1617 ///////////////////////////////////////////////////////////////////
1620 parser::ProductFileData baseproductdata( const Pathname & root_r )
1622 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1623 if ( baseproduct.isFile() )
1627 return parser::ProductFileReader::scanFile( baseproduct.path() );
1629 catch ( const Exception & excpt )
1631 ZYPP_CAUGHT( excpt );
1634 return parser::ProductFileData();
1637 inline Pathname staticGuessRoot( const Pathname & root_r )
1639 if ( root_r.empty() )
1641 // empty root: use existing Target or assume "/"
1642 Pathname ret ( ZConfig::instance().systemRoot() );
1644 return Pathname("/");
1650 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1652 std::ifstream idfile( file_r.c_str() );
1653 for( iostr::EachLine in( idfile ); in; in.next() )
1655 std::string line( str::trim( *in ) );
1656 if ( ! line.empty() )
1659 return std::string();
1662 ///////////////////////////////////////////////////////////////////
1664 Product::constPtr TargetImpl::baseProduct() const
1666 ResPool pool(ResPool::instance());
1667 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1669 Product::constPtr p = (*it)->asKind<Product>();
1670 if ( p->isTargetDistribution() )
1676 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1678 const Pathname needroot( staticGuessRoot(root_r) );
1679 const Target_constPtr target( getZYpp()->getTarget() );
1680 if ( target && target->root() == needroot )
1681 return target->requestedLocales();
1682 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1685 std::string TargetImpl::targetDistribution() const
1686 { return baseproductdata( _root ).registerTarget(); }
1688 std::string TargetImpl::targetDistribution( const Pathname & root_r )
1689 { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1691 std::string TargetImpl::targetDistributionRelease() const
1692 { return baseproductdata( _root ).registerRelease(); }
1694 std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1695 { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1697 Target::DistributionLabel TargetImpl::distributionLabel() const
1699 Target::DistributionLabel ret;
1700 parser::ProductFileData pdata( baseproductdata( _root ) );
1701 ret.shortName = pdata.shortName();
1702 ret.summary = pdata.summary();
1706 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1708 Target::DistributionLabel ret;
1709 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1710 ret.shortName = pdata.shortName();
1711 ret.summary = pdata.summary();
1715 std::string TargetImpl::distributionVersion() const
1717 if ( _distributionVersion.empty() )
1719 _distributionVersion = TargetImpl::distributionVersion(root());
1720 if ( !_distributionVersion.empty() )
1721 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1723 return _distributionVersion;
1726 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1728 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1729 if ( distributionVersion.empty() )
1731 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1732 // On RHEL, Fedora and others the "product version" is determined by the first package
1733 // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1734 // with the $distroverpkg variable.
1735 scoped_ptr<rpm::RpmDb> tmprpmdb;
1736 if ( ZConfig::instance().systemRoot() == Pathname() )
1740 tmprpmdb.reset( new rpm::RpmDb );
1741 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1748 rpm::librpmDb::db_const_iterator it;
1749 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1750 distributionVersion = it->tag_version();
1752 return distributionVersion;
1756 std::string TargetImpl::distributionFlavor() const
1758 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1761 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1763 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1766 ///////////////////////////////////////////////////////////////////
1768 std::string TargetImpl::anonymousUniqueId() const
1770 return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1773 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1775 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1778 ///////////////////////////////////////////////////////////////////
1780 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1782 // provide on local disk
1783 repo::RepoMediaAccess access_r;
1784 repo::SrcPackageProvider prov( access_r );
1785 ManagedFile localfile = prov.provideSrcPackage( srcPackage_r );
1787 rpm().installPackage ( localfile );
1790 /////////////////////////////////////////////////////////////////
1791 } // namespace target
1792 ///////////////////////////////////////////////////////////////////
1793 /////////////////////////////////////////////////////////////////
1795 ///////////////////////////////////////////////////////////////////