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 bool 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;
961 return build_rpm_solv;
964 void TargetImpl::reload()
969 void TargetImpl::unload()
971 Repository system( sat::Pool::instance().findSystemRepo() );
973 system.eraseFromPool();
976 void TargetImpl::load( bool force )
978 bool newCache = buildCache();
979 MIL << "New cache built: " << (newCache?"true":"false") <<
980 ", force loading: " << (force?"true":"false") << endl;
982 // now add the repos to the pool
983 sat::Pool satpool( sat::Pool::instance() );
984 Pathname rpmsolv( solvfilesPath() / "solv" );
985 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
987 // Providing an empty system repo, unload any old content
988 Repository system( sat::Pool::instance().findSystemRepo() );
990 if ( system && ! system.solvablesEmpty() )
992 if ( newCache || force )
994 system.eraseFromPool(); // invalidates system
998 return; // nothing to do
1004 system = satpool.systemRepo();
1009 MIL << "adding " << rpmsolv << " to system" << endl;
1010 system.addSolv( rpmsolv );
1012 catch ( const Exception & exp )
1015 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1019 system.addSolv( rpmsolv );
1022 // (Re)Load the requested locales et al.
1023 // If the requested locales are empty, we leave the pool untouched
1024 // to avoid undoing changes the application applied. We expect this
1025 // to happen on a bare metal installation only. An already existing
1026 // target should be loaded before its settings are changed.
1028 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1029 if ( ! requestedLocales.empty() )
1031 satpool.setRequestedLocales( requestedLocales );
1035 SoftLocksFile::Data softLocks( _softLocksFile.data() );
1036 if ( ! softLocks.empty() )
1038 // Don't soft lock any installed item.
1039 for_( it, system.solvablesBegin(), system.solvablesEnd() )
1041 softLocks.erase( it->ident() );
1043 ResPool::instance().setAutoSoftLocks( softLocks );
1046 if ( ZConfig::instance().apply_locks_file() )
1048 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1049 if ( ! hardLocks.empty() )
1051 ResPool::instance().setHardLockQueries( hardLocks );
1055 // now that the target is loaded, we can cache the flavor
1056 createLastDistributionFlavorCache();
1058 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1061 ///////////////////////////////////////////////////////////////////
1065 ///////////////////////////////////////////////////////////////////
1066 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1068 // ----------------------------------------------------------------- //
1069 ZYppCommitPolicy policy_r( policy_rX );
1071 // Fake outstanding YCP fix: Honour restriction to media 1
1072 // at installation, but install all remaining packages if post-boot.
1073 if ( policy_r.restrictToMedia() > 1 )
1074 policy_r.allMedia();
1076 if ( policy_r.downloadMode() == DownloadDefault ) {
1077 if ( root() == "/" )
1078 policy_r.downloadMode(DownloadInHeaps);
1080 policy_r.downloadMode(DownloadAsNeeded);
1082 // DownloadOnly implies dry-run.
1083 else if ( policy_r.downloadMode() == DownloadOnly )
1084 policy_r.dryRun( true );
1085 // ----------------------------------------------------------------- //
1087 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1089 ///////////////////////////////////////////////////////////////////
1090 // Prepare execution of commit plugins:
1091 ///////////////////////////////////////////////////////////////////
1092 CommitPlugins commitPlugins;
1093 if ( root() == "/" && ! policy_r.dryRun() )
1095 Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
1096 commitPlugins.load( plugindir );
1099 ///////////////////////////////////////////////////////////////////
1100 // Write out a testcase if we're in dist upgrade mode.
1101 ///////////////////////////////////////////////////////////////////
1102 if ( getZYpp()->resolver()->upgradeMode() )
1104 if ( ! policy_r.dryRun() )
1106 writeUpgradeTestcase();
1110 DBG << "dryRun: Not writing upgrade testcase." << endl;
1114 ///////////////////////////////////////////////////////////////////
1115 // Store non-package data:
1116 ///////////////////////////////////////////////////////////////////
1117 if ( ! policy_r.dryRun() )
1119 filesystem::assert_dir( home() );
1120 // requested locales
1121 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1124 SoftLocksFile::Data newdata;
1125 pool_r.getActiveSoftLocks( newdata );
1126 _softLocksFile.setData( newdata );
1129 if ( ZConfig::instance().apply_locks_file() )
1131 HardLocksFile::Data newdata;
1132 pool_r.getHardLockQueries( newdata );
1133 _hardLocksFile.setData( newdata );
1138 DBG << "dryRun: Not stroring non-package data." << endl;
1141 ///////////////////////////////////////////////////////////////////
1142 // Compute transaction:
1143 ///////////////////////////////////////////////////////////////////
1144 ZYppCommitResult result( root() );
1145 result.rTransaction() = pool_r.resolver().getTransaction();
1146 result.rTransaction().order();
1147 // steps: this is our todo-list
1148 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1149 if ( policy_r.restrictToMedia() )
1151 // Collect until the 1st package from an unwanted media occurs.
1152 // Further collection could violate install order.
1153 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1154 for_( it, result.transaction().begin(), result.transaction().end() )
1156 if ( makeResObject( *it )->mediaNr() > 1 )
1158 steps.push_back( *it );
1163 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1165 MIL << "Todo: " << result << endl;
1167 ///////////////////////////////////////////////////////////////////
1168 // First collect and display all messages
1169 // associated with patches to be installed.
1170 ///////////////////////////////////////////////////////////////////
1171 if ( ! policy_r.dryRun() )
1173 for_( it, steps.begin(), steps.end() )
1175 if ( ! it->satSolvable().isKind<Patch>() )
1179 if ( ! pi.status().isToBeInstalled() )
1182 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1183 if ( ! patch ||patch->message().empty() )
1186 MIL << "Show message for " << patch << endl;
1187 callback::SendReport<target::PatchMessageReport> report;
1188 if ( ! report->show( patch ) )
1190 WAR << "commit aborted by the user" << endl;
1191 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1197 DBG << "dryRun: Not checking patch messages." << endl;
1200 ///////////////////////////////////////////////////////////////////
1201 // Remove/install packages.
1202 ///////////////////////////////////////////////////////////////////
1203 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1204 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1206 // Prepare the package cache. Pass all items requiring download.
1207 repo::RepoMediaAccess access;
1208 RepoProvidePackage repoProvidePackage( access, pool_r );
1209 CommitPackageCache packageCache( root() / "tmp", repoProvidePackage );
1210 packageCache.setCommitList( steps.begin(), steps.end() );
1213 if ( policy_r.downloadMode() != DownloadAsNeeded )
1215 // Preload the cache. Until now this means pre-loading all packages.
1216 // Once DownloadInHeaps is fully implemented, this will change and
1217 // we may actually have more than one heap.
1218 for_( it, steps.begin(), steps.end() )
1220 switch ( it->stepType() )
1222 case sat::Transaction::TRANSACTION_INSTALL:
1223 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1224 // proceed: only install actionas may require download.
1228 // next: no download for or non-packages and delete actions.
1234 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1236 ManagedFile localfile;
1239 // TODO: unify packageCache.get for Package and SrcPackage
1240 if ( pi->isKind<Package>() )
1242 localfile = packageCache.get( pi );
1244 else if ( pi->isKind<SrcPackage>() )
1246 repo::RepoMediaAccess access;
1247 repo::SrcPackageProvider prov( access );
1248 localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1252 INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1255 localfile.resetDispose(); // keep the package file in the cache
1257 catch ( const AbortRequestException & exp )
1259 it->stepStage( sat::Transaction::STEP_ERROR );
1261 WAR << "commit cache preload aborted by the user" << endl;
1262 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1265 catch ( const SkipRequestException & exp )
1268 it->stepStage( sat::Transaction::STEP_ERROR );
1270 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1273 catch ( const Exception & exp )
1275 // bnc #395704: missing catch causes abort.
1276 // TODO see if packageCache fails to handle errors correctly.
1278 it->stepStage( sat::Transaction::STEP_ERROR );
1280 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1289 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1291 else if ( ! policy_r.dryRun() )
1293 commit( policy_r, packageCache, result );
1297 DBG << "dryRun: Not installing/deleting anything." << endl;
1302 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1305 ///////////////////////////////////////////////////////////////////
1306 // Try to rebuild solv file while rpm database is still in cache
1307 ///////////////////////////////////////////////////////////////////
1308 if ( ! policy_r.dryRun() )
1313 // for DEPRECATED old ZyppCommitResult results:
1314 ///////////////////////////////////////////////////////////////////
1315 // build return statistics
1316 ///////////////////////////////////////////////////////////////////
1317 result._errors.clear();
1318 result._remaining.clear();
1319 result._srcremaining.clear();
1320 unsigned toInstall = 0;
1321 for_( step, steps.begin(), steps.end() )
1323 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1325 // For non-packages only products might have beed installed.
1326 // All the rest is ignored.
1327 if ( step->satSolvable().isSystem() || ! step->satSolvable().isKind<Product>() )
1330 else if ( step->stepType() == sat::Transaction::TRANSACTION_ERASE )
1336 switch ( step->stepStage() )
1338 case sat::Transaction::STEP_TODO:
1339 if ( step->satSolvable().isKind<Package>() )
1340 result._remaining.push_back( PoolItem( *step ) );
1341 else if ( step->satSolvable().isKind<SrcPackage>() )
1342 result._srcremaining.push_back( PoolItem( *step ) );
1344 case sat::Transaction::STEP_DONE:
1347 case sat::Transaction::STEP_ERROR:
1348 result._errors.push_back( PoolItem( *step ) );
1352 result._result = (toInstall - result._remaining.size());
1353 ///////////////////////////////////////////////////////////////////
1355 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1359 ///////////////////////////////////////////////////////////////////
1363 ///////////////////////////////////////////////////////////////////
1364 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1365 CommitPackageCache & packageCache_r,
1366 ZYppCommitResult & result_r )
1368 // steps: this is our todo-list
1369 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1370 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1373 std::vector<sat::Solvable> successfullyInstalledPackages;
1374 TargetImpl::PoolItemList remaining;
1376 for_( step, steps.begin(), steps.end() )
1378 PoolItem citem( *step );
1379 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1381 if ( citem->isKind<Package>() )
1383 // for packages this means being obsoleted (by rpm)
1384 // thius no additional action is needed.
1385 step->stepStage( sat::Transaction::STEP_DONE );
1390 if ( citem->isKind<Package>() )
1392 Package::constPtr p = citem->asKind<Package>();
1393 if ( citem.status().isToBeInstalled() )
1395 ManagedFile localfile;
1398 localfile = packageCache_r.get( citem );
1400 catch ( const AbortRequestException &e )
1402 WAR << "commit aborted by the user" << endl;
1404 step->stepStage( sat::Transaction::STEP_ERROR );
1407 catch ( const SkipRequestException &e )
1410 WAR << "Skipping package " << p << " in commit" << endl;
1411 step->stepStage( sat::Transaction::STEP_ERROR );
1414 catch ( const Exception &e )
1416 // bnc #395704: missing catch causes abort.
1417 // TODO see if packageCache fails to handle errors correctly.
1419 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1420 step->stepStage( sat::Transaction::STEP_ERROR );
1424 #warning Exception handling
1425 // create a installation progress report proxy
1426 RpmInstallPackageReceiver progress( citem.resolvable() );
1427 progress.connect(); // disconnected on destruction.
1429 bool success = false;
1430 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1431 // Why force and nodeps?
1433 // Because zypp builds the transaction and the resolver asserts that
1434 // everything is fine.
1435 // We use rpm just to unpack and register the package in the database.
1436 // We do this step by step, so rpm is not aware of the bigger context.
1437 // So we turn off rpms internal checks, because we do it inside zypp.
1438 flags |= rpm::RPMINST_NODEPS;
1439 flags |= rpm::RPMINST_FORCE;
1441 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1442 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1443 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1444 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1448 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1449 rpm().installPackage( localfile, flags );
1450 HistoryLog().install(citem);
1452 if ( progress.aborted() )
1454 WAR << "commit aborted by the user" << endl;
1455 localfile.resetDispose(); // keep the package file in the cache
1457 step->stepStage( sat::Transaction::STEP_ERROR );
1463 step->stepStage( sat::Transaction::STEP_DONE );
1466 catch ( Exception & excpt_r )
1468 ZYPP_CAUGHT(excpt_r);
1469 localfile.resetDispose(); // keep the package file in the cache
1471 if ( policy_r.dryRun() )
1473 WAR << "dry run failed" << endl;
1474 step->stepStage( sat::Transaction::STEP_ERROR );
1478 if ( progress.aborted() )
1480 WAR << "commit aborted by the user" << endl;
1485 WAR << "Install failed" << endl;
1487 step->stepStage( sat::Transaction::STEP_ERROR );
1491 if ( success && !policy_r.dryRun() )
1493 citem.status().resetTransact( ResStatus::USER );
1494 successfullyInstalledPackages.push_back( citem.satSolvable() );
1495 step->stepStage( sat::Transaction::STEP_DONE );
1500 RpmRemovePackageReceiver progress( citem.resolvable() );
1501 progress.connect(); // disconnected on destruction.
1503 bool success = false;
1504 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1505 flags |= rpm::RPMINST_NODEPS;
1506 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1509 rpm().removePackage( p, flags );
1510 HistoryLog().remove(citem);
1512 if ( progress.aborted() )
1514 WAR << "commit aborted by the user" << endl;
1516 step->stepStage( sat::Transaction::STEP_ERROR );
1522 step->stepStage( sat::Transaction::STEP_DONE );
1525 catch (Exception & excpt_r)
1527 ZYPP_CAUGHT( excpt_r );
1528 if ( progress.aborted() )
1530 WAR << "commit aborted by the user" << endl;
1532 step->stepStage( sat::Transaction::STEP_ERROR );
1536 WAR << "removal of " << p << " failed";
1537 step->stepStage( sat::Transaction::STEP_ERROR );
1539 if ( success && !policy_r.dryRun() )
1541 citem.status().resetTransact( ResStatus::USER );
1542 step->stepStage( sat::Transaction::STEP_DONE );
1546 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1548 // Status is changed as the buddy package buddy
1549 // gets installed/deleted. Handle non-buddies only.
1550 if ( ! citem.buddy() )
1552 if ( citem->isKind<Product>() )
1554 Product::constPtr p = citem->asKind<Product>();
1555 if ( citem.status().isToBeInstalled() )
1557 ERR << "Can't install orphan product without release-package! " << citem << endl;
1561 // Deleting the corresponding product entry is all we con do.
1562 // So the product will no longer be visible as installed.
1563 std::string referenceFilename( p->referenceFilename() );
1564 if ( referenceFilename.empty() )
1566 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1570 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1571 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1573 ERR << "Delete orphan product failed: " << referenceFile << endl;
1578 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1580 // SrcPackage is install-only
1581 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1582 installSrcPackage( p );
1585 citem.status().resetTransact( ResStatus::USER );
1586 step->stepStage( sat::Transaction::STEP_DONE );
1589 } // other resolvables
1593 // Check presence of update scripts/messages. If aborting,
1594 // at least log omitted scripts.
1595 if ( ! successfullyInstalledPackages.empty() )
1597 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1598 successfullyInstalledPackages, abort ) )
1600 WAR << "Commit aborted by the user" << endl;
1603 // send messages after scripts in case some script generates output,
1604 // that should be kept in t %ghost message file.
1605 RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1606 successfullyInstalledPackages,
1612 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1616 ///////////////////////////////////////////////////////////////////
1618 rpm::RpmDb & TargetImpl::rpm()
1623 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1625 return _rpm.hasFile(path_str, name_str);
1629 Date TargetImpl::timestamp() const
1631 return _rpm.timestamp();
1634 ///////////////////////////////////////////////////////////////////
1637 parser::ProductFileData baseproductdata( const Pathname & root_r )
1639 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1640 if ( baseproduct.isFile() )
1644 return parser::ProductFileReader::scanFile( baseproduct.path() );
1646 catch ( const Exception & excpt )
1648 ZYPP_CAUGHT( excpt );
1651 return parser::ProductFileData();
1654 inline Pathname staticGuessRoot( const Pathname & root_r )
1656 if ( root_r.empty() )
1658 // empty root: use existing Target or assume "/"
1659 Pathname ret ( ZConfig::instance().systemRoot() );
1661 return Pathname("/");
1667 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1669 std::ifstream idfile( file_r.c_str() );
1670 for( iostr::EachLine in( idfile ); in; in.next() )
1672 std::string line( str::trim( *in ) );
1673 if ( ! line.empty() )
1676 return std::string();
1679 ///////////////////////////////////////////////////////////////////
1681 Product::constPtr TargetImpl::baseProduct() const
1683 ResPool pool(ResPool::instance());
1684 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1686 Product::constPtr p = (*it)->asKind<Product>();
1687 if ( p->isTargetDistribution() )
1693 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1695 const Pathname needroot( staticGuessRoot(root_r) );
1696 const Target_constPtr target( getZYpp()->getTarget() );
1697 if ( target && target->root() == needroot )
1698 return target->requestedLocales();
1699 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1702 std::string TargetImpl::targetDistribution() const
1703 { return baseproductdata( _root ).registerTarget(); }
1705 std::string TargetImpl::targetDistribution( const Pathname & root_r )
1706 { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1708 std::string TargetImpl::targetDistributionRelease() const
1709 { return baseproductdata( _root ).registerRelease(); }
1711 std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1712 { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1714 Target::DistributionLabel TargetImpl::distributionLabel() const
1716 Target::DistributionLabel ret;
1717 parser::ProductFileData pdata( baseproductdata( _root ) );
1718 ret.shortName = pdata.shortName();
1719 ret.summary = pdata.summary();
1723 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1725 Target::DistributionLabel ret;
1726 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1727 ret.shortName = pdata.shortName();
1728 ret.summary = pdata.summary();
1732 std::string TargetImpl::distributionVersion() const
1734 if ( _distributionVersion.empty() )
1736 _distributionVersion = TargetImpl::distributionVersion(root());
1737 if ( !_distributionVersion.empty() )
1738 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1740 return _distributionVersion;
1743 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1745 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1746 if ( distributionVersion.empty() )
1748 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1749 // On RHEL, Fedora and others the "product version" is determined by the first package
1750 // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1751 // with the $distroverpkg variable.
1752 scoped_ptr<rpm::RpmDb> tmprpmdb;
1753 if ( ZConfig::instance().systemRoot() == Pathname() )
1757 tmprpmdb.reset( new rpm::RpmDb );
1758 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1765 rpm::librpmDb::db_const_iterator it;
1766 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1767 distributionVersion = it->tag_version();
1769 return distributionVersion;
1773 std::string TargetImpl::distributionFlavor() const
1775 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1778 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1780 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1783 ///////////////////////////////////////////////////////////////////
1785 std::string TargetImpl::anonymousUniqueId() const
1787 return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1790 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1792 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1795 ///////////////////////////////////////////////////////////////////
1797 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1799 // provide on local disk
1800 repo::RepoMediaAccess access_r;
1801 repo::SrcPackageProvider prov( access_r );
1802 ManagedFile localfile = prov.provideSrcPackage( srcPackage_r );
1804 rpm().installPackage ( localfile );
1807 /////////////////////////////////////////////////////////////////
1808 } // namespace target
1809 ///////////////////////////////////////////////////////////////////
1810 /////////////////////////////////////////////////////////////////
1812 ///////////////////////////////////////////////////////////////////