1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/target/TargetImpl.cc
19 #include <sys/types.h>
22 #include "zypp/base/LogTools.h"
23 #include "zypp/base/Exception.h"
24 #include "zypp/base/Iterator.h"
25 #include "zypp/base/Gettext.h"
26 #include "zypp/base/IOStream.h"
27 #include "zypp/base/Functional.h"
28 #include "zypp/base/UserRequestException.h"
29 #include "zypp/base/Json.h"
31 #include "zypp/ZConfig.h"
32 #include "zypp/ZYppFactory.h"
34 #include "zypp/PoolItem.h"
35 #include "zypp/ResObjects.h"
37 #include "zypp/TmpPath.h"
38 #include "zypp/RepoStatus.h"
39 #include "zypp/ExternalProgram.h"
40 #include "zypp/Repository.h"
42 #include "zypp/ResFilters.h"
43 #include "zypp/HistoryLog.h"
44 #include "zypp/target/TargetImpl.h"
45 #include "zypp/target/TargetCallbackReceiver.h"
46 #include "zypp/target/rpm/librpmDb.h"
47 #include "zypp/target/CommitPackageCache.h"
48 #include "zypp/target/RpmPostTransCollector.h"
50 #include "zypp/parser/ProductFileReader.h"
52 #include "zypp/solver/detail/Testcase.h"
54 #include "zypp/repo/SrcPackageProvider.h"
56 #include "zypp/sat/Pool.h"
57 #include "zypp/sat/Transaction.h"
59 #include "zypp/PluginExecutor.h"
63 ///////////////////////////////////////////////////////////////////
65 { /////////////////////////////////////////////////////////////////
66 ///////////////////////////////////////////////////////////////////
69 // Lazy via template specialisation / should switch to overloading
72 inline std::string toJSON( const ZYppCommitResult::TransactionStepList & steps_r )
74 using sat::Transaction;
77 for ( const Transaction::Step & step : steps_r )
78 // ignore implicit deletes due to obsoletes and non-package actions
79 if ( step.stepType() != Transaction::TRANSACTION_IGNORE )
85 /** See \ref commitbegin on page \ref plugin-commit for the specs. */
87 inline std::string toJSON( const sat::Transaction::Step & step_r )
89 static const std::string strType( "type" );
90 static const std::string strStage( "stage" );
91 static const std::string strSolvable( "solvable" );
93 static const std::string strTypeDel( "-" );
94 static const std::string strTypeIns( "+" );
95 static const std::string strTypeMul( "M" );
97 static const std::string strStageDone( "ok" );
98 static const std::string strStageFailed( "err" );
100 static const std::string strSolvableN( "n" );
101 static const std::string strSolvableE( "e" );
102 static const std::string strSolvableV( "v" );
103 static const std::string strSolvableR( "r" );
104 static const std::string strSolvableA( "a" );
106 using sat::Transaction;
109 switch ( step_r.stepType() )
111 case Transaction::TRANSACTION_IGNORE: /*empty*/ break;
112 case Transaction::TRANSACTION_ERASE: ret.add( strType, strTypeDel ); break;
113 case Transaction::TRANSACTION_INSTALL: ret.add( strType, strTypeIns ); break;
114 case Transaction::TRANSACTION_MULTIINSTALL: ret.add( strType, strTypeMul ); break;
117 switch ( step_r.stepStage() )
119 case Transaction::STEP_TODO: /*empty*/ break;
120 case Transaction::STEP_DONE: ret.add( strStage, strStageDone ); break;
121 case Transaction::STEP_ERROR: ret.add( strStage, strStageFailed ); break;
128 if ( sat::Solvable solv = step_r.satSolvable() )
130 ident = solv.ident();
136 // deleted package; post mortem data stored in Transaction::Step
137 ident = step_r.ident();
138 ed = step_r.edition();
139 arch = step_r.arch();
143 { strSolvableN, ident.asString() },
144 { strSolvableV, ed.version() },
145 { strSolvableR, ed.release() },
146 { strSolvableA, arch.asString() }
148 if ( Edition::epoch_t epoch = ed.epoch() )
149 s.add( strSolvableE, epoch );
151 ret.add( strSolvable, s );
157 ///////////////////////////////////////////////////////////////////
159 ///////////////////////////////////////////////////////////////////
162 ///////////////////////////////////////////////////////////////////
165 SolvIdentFile::Data getUserInstalledFromHistory( const Pathname & historyFile_r )
167 SolvIdentFile::Data onSystemByUserList;
168 // go and parse it: 'who' must constain an '@', then it was installed by user request.
169 // 2009-09-29 07:25:19|install|lirc-remotes|0.8.5-3.2|x86_64|root@opensuse|InstallationImage|a204211eb0...
170 std::ifstream infile( historyFile_r.c_str() );
171 for( iostr::EachLine in( infile ); in; in.next() )
173 const char * ch( (*in).c_str() );
175 if ( *ch < '1' || '9' < *ch )
177 const char * sep1 = ::strchr( ch, '|' ); // | after date
181 // if logs an install or delete
182 bool installs = true;
183 if ( ::strncmp( sep1, "install|", 8 ) )
185 if ( ::strncmp( sep1, "remove |", 8 ) )
186 continue; // no install and no remove
188 installs = false; // remove
190 sep1 += 8; // | after what
191 // get the package name
192 const char * sep2 = ::strchr( sep1, '|' ); // | after name
193 if ( !sep2 || sep1 == sep2 )
195 (*in)[sep2-ch] = '\0';
196 IdString pkg( sep1 );
197 // we're done, if a delete
200 onSystemByUserList.erase( pkg );
203 // now guess whether user installed or not (3rd next field contains 'user@host')
204 if ( (sep1 = ::strchr( sep2+1, '|' )) // | after version
205 && (sep1 = ::strchr( sep1+1, '|' )) // | after arch
206 && (sep2 = ::strchr( sep1+1, '|' )) ) // | after who
208 (*in)[sep2-ch] = '\0';
209 if ( ::strchr( sep1+1, '@' ) )
212 onSystemByUserList.insert( pkg );
217 MIL << "onSystemByUserList found: " << onSystemByUserList.size() << endl;
218 return onSystemByUserList;
221 ///////////////////////////////////////////////////////////////////
223 ///////////////////////////////////////////////////////////////////
226 inline PluginFrame transactionPluginFrame( const std::string & command_r, ZYppCommitResult::TransactionStepList & steps_r )
228 return PluginFrame( command_r, json::Object {
229 { "TransactionStepList", steps_r }
233 ///////////////////////////////////////////////////////////////////
235 /** \internal Manage writing a new testcase when doing an upgrade. */
236 void writeUpgradeTestcase()
238 unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
239 MIL << "Testcases to keep: " << toKeep << endl;
242 Target_Ptr target( getZYpp()->getTarget() );
245 WAR << "No Target no Testcase!" << endl;
249 std::string stem( "updateTestcase" );
250 Pathname dir( target->assertRootPrefix("/var/log/") );
251 Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
254 std::list<std::string> content;
255 filesystem::readdir( content, dir, /*dots*/false );
256 std::set<std::string> cases;
257 for_( c, content.begin(), content.end() )
259 if ( str::startsWith( *c, stem ) )
262 if ( cases.size() >= toKeep )
264 unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
265 for_( c, cases.begin(), cases.end() )
267 filesystem::recursive_rmdir( dir/(*c) );
274 MIL << "Write new testcase " << next << endl;
275 getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
278 ///////////////////////////////////////////////////////////////////
280 { /////////////////////////////////////////////////////////////////
282 /** Execute script and report against report_r.
283 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
284 * execution was successfull (<tt>first = true</tt>), or the desired
285 * \c PatchScriptReport::Action in case execution failed
286 * (<tt>first = false</tt>).
288 * \note The packager is responsible for setting the correct permissions
289 * of the script. If the script is not executable it is reported as an
290 * error. We must not modify the permessions.
292 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
293 const Pathname & script_r,
294 callback::SendReport<PatchScriptReport> & report_r )
296 MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
298 HistoryLog historylog;
299 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
300 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
302 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
304 historylog.comment(output);
305 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
307 WAR << "User request to abort script " << script_r << endl;
309 // the rest is handled by exit code evaluation
310 // in case the script has meanwhile finished.
314 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
316 if ( prog.close() != 0 )
318 ret.second = report_r->problem( prog.execError() );
319 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
320 std::ostringstream sstr;
321 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
322 historylog.comment(sstr.str(), /*timestamp*/true);
331 /** Execute script and report against report_r.
332 * Return \c false if user requested \c ABORT.
334 bool executeScript( const Pathname & root_r,
335 const Pathname & script_r,
336 callback::SendReport<PatchScriptReport> & report_r )
338 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
341 action = doExecuteScript( root_r, script_r, report_r );
343 return true; // success
345 switch ( action.second )
347 case PatchScriptReport::ABORT:
348 WAR << "User request to abort at script " << script_r << endl;
349 return false; // requested abort.
352 case PatchScriptReport::IGNORE:
353 WAR << "User request to skip script " << script_r << endl;
354 return true; // requested skip.
357 case PatchScriptReport::RETRY:
360 } while ( action.second == PatchScriptReport::RETRY );
362 // THIS is not intended to be reached:
363 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
364 return false; // abort.
367 /** Look for update scripts named 'name-version-release-*' and
368 * execute them. Return \c false if \c ABORT was requested.
370 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
372 bool RunUpdateScripts( const Pathname & root_r,
373 const Pathname & scriptsPath_r,
374 const std::vector<sat::Solvable> & checkPackages_r,
377 if ( checkPackages_r.empty() )
378 return true; // no installed packages to check
380 MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
381 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
382 if ( ! PathInfo( scriptsDir ).isDir() )
383 return true; // no script dir
385 std::list<std::string> scripts;
386 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
387 if ( scripts.empty() )
388 return true; // no scripts in script dir
390 // Now collect and execute all matching scripts.
391 // On ABORT: at least log all outstanding scripts.
392 // - "name-version-release"
393 // - "name-version-release-*"
395 std::map<std::string, Pathname> unify; // scripts <md5,path>
396 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
398 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
399 for_( sit, scripts.begin(), scripts.end() )
401 if ( ! str::hasPrefix( *sit, prefix ) )
404 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
405 continue; // if not exact match it had to continue with '-'
407 PathInfo script( scriptsDir / *sit );
408 Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
409 std::string unifytag; // must not stay empty
411 if ( script.isFile() )
413 // Assert it's set executable, unify by md5sum.
414 filesystem::addmod( script.path(), 0500 );
415 unifytag = filesystem::md5sum( script.path() );
417 else if ( ! script.isExist() )
419 // Might be a dangling symlink, might be ok if we are in
420 // instsys (absolute symlink within the system below /mnt).
421 // readlink will tell....
422 unifytag = filesystem::readlink( script.path() ).asString();
425 if ( unifytag.empty() )
429 if ( unify[unifytag].empty() )
431 unify[unifytag] = localPath;
435 // translators: We may find the same script content in files with different names.
436 // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
437 // message for a log file. Preferably start translation with "%s"
438 std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
439 MIL << "Skip update script: " << msg << endl;
440 HistoryLog().comment( msg, /*timestamp*/true );
444 if ( abort || aborting_r )
446 WAR << "Aborting: Skip update script " << *sit << endl;
447 HistoryLog().comment(
448 localPath.asString() + _(" execution skipped while aborting"),
453 MIL << "Found update script " << *sit << endl;
454 callback::SendReport<PatchScriptReport> report;
455 report->start( make<Package>( *it ), script.path() );
457 if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
458 abort = true; // requested abort.
465 ///////////////////////////////////////////////////////////////////
467 ///////////////////////////////////////////////////////////////////
469 inline void copyTo( std::ostream & out_r, const Pathname & file_r )
471 std::ifstream infile( file_r.c_str() );
472 for( iostr::EachLine in( infile ); in; in.next() )
474 out_r << *in << endl;
478 inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
480 std::string ret( cmd_r );
481 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
482 SUBST_IF( "%p", notification_r.solvable().asString() );
483 SUBST_IF( "%P", notification_r.file().asString() );
488 void sendNotification( const Pathname & root_r,
489 const UpdateNotifications & notifications_r )
491 if ( notifications_r.empty() )
494 std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
495 MIL << "Notification command is '" << cmdspec << "'" << endl;
496 if ( cmdspec.empty() )
499 std::string::size_type pos( cmdspec.find( '|' ) );
500 if ( pos == std::string::npos )
502 ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
503 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
507 std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
508 std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
510 enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
511 Format format = UNKNOWN;
512 if ( formatStr == "none" )
514 else if ( formatStr == "single" )
516 else if ( formatStr == "digest" )
518 else if ( formatStr == "bulk" )
522 ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
523 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
527 // Take care: commands are ececuted chroot(root_r). The message file
528 // pathnames in notifications_r are local to root_r. For physical access
529 // to the file they need to be prefixed.
531 if ( format == NONE || format == SINGLE )
533 for_( it, notifications_r.begin(), notifications_r.end() )
535 std::vector<std::string> command;
536 if ( format == SINGLE )
537 command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
538 str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
540 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
541 if ( true ) // Wait for feedback
543 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
547 int ret = prog.close();
550 ERR << "Notification command returned with error (" << ret << ")." << endl;
551 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
557 else if ( format == DIGEST || format == BULK )
559 filesystem::TmpFile tmpfile;
560 ofstream out( tmpfile.path().c_str() );
561 for_( it, notifications_r.begin(), notifications_r.end() )
563 if ( format == DIGEST )
565 out << it->file() << endl;
567 else if ( format == BULK )
569 copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
573 std::vector<std::string> command;
574 command.push_back( "<"+tmpfile.path().asString() ); // redirect input
575 str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
577 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
578 if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
580 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
584 int ret = prog.close();
587 ERR << "Notification command returned with error (" << ret << ")." << endl;
588 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
595 INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
596 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
602 /** Look for update messages named 'name-version-release-*' and
603 * send notification according to \ref ZConfig::updateMessagesNotify.
605 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
607 void RunUpdateMessages( const Pathname & root_r,
608 const Pathname & messagesPath_r,
609 const std::vector<sat::Solvable> & checkPackages_r,
610 ZYppCommitResult & result_r )
612 if ( checkPackages_r.empty() )
613 return; // no installed packages to check
615 MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
616 Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
617 if ( ! PathInfo( messagesDir ).isDir() )
618 return; // no messages dir
620 std::list<std::string> messages;
621 filesystem::readdir( messages, messagesDir, /*dots*/false );
622 if ( messages.empty() )
623 return; // no messages in message dir
625 // Now collect all matching messages in result and send them
626 // - "name-version-release"
627 // - "name-version-release-*"
628 HistoryLog historylog;
629 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
631 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
632 for_( sit, messages.begin(), messages.end() )
634 if ( ! str::hasPrefix( *sit, prefix ) )
637 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
638 continue; // if not exact match it had to continue with '-'
640 PathInfo message( messagesDir / *sit );
641 if ( ! message.isFile() || message.size() == 0 )
644 MIL << "Found update message " << *sit << endl;
645 Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
646 result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
647 historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
650 sendNotification( root_r, result_r.updateMessages() );
653 /////////////////////////////////////////////////////////////////
655 ///////////////////////////////////////////////////////////////////
657 void XRunUpdateMessages( const Pathname & root_r,
658 const Pathname & messagesPath_r,
659 const std::vector<sat::Solvable> & checkPackages_r,
660 ZYppCommitResult & result_r )
661 { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
663 ///////////////////////////////////////////////////////////////////
665 IMPL_PTR_TYPE(TargetImpl);
667 TargetImpl_Ptr TargetImpl::_nullimpl;
669 /** Null implementation */
670 TargetImpl_Ptr TargetImpl::nullimpl()
673 _nullimpl = new TargetImpl;
677 ///////////////////////////////////////////////////////////////////
679 // METHOD NAME : TargetImpl::TargetImpl
680 // METHOD TYPE : Ctor
682 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
684 , _requestedLocalesFile( home() / "RequestedLocales" )
685 , _autoInstalledFile( home() / "AutoInstalled" )
686 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
688 _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
690 HistoryLog::setRoot(_root);
694 MIL << "Initialized target on " << _root << endl;
698 * generates a random id using uuidgen
700 static std::string generateRandomId()
702 std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
703 return iostr::getline( uuidprovider );
707 * updates the content of \p filename
708 * if \p condition is true, setting the content
709 * the the value returned by \p value
711 void updateFileContent( const Pathname &filename,
712 boost::function<bool ()> condition,
713 boost::function<string ()> value )
715 string val = value();
716 // if the value is empty, then just dont
717 // do anything, regardless of the condition
723 MIL << "updating '" << filename << "' content." << endl;
725 // if the file does not exist we need to generate the uuid file
727 std::ofstream filestr;
728 // make sure the path exists
729 filesystem::assert_dir( filename.dirname() );
730 filestr.open( filename.c_str() );
732 if ( filestr.good() )
739 // FIXME, should we ignore the error?
740 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
745 /** helper functor */
746 static bool fileMissing( const Pathname &pathname )
748 return ! PathInfo(pathname).isExist();
751 void TargetImpl::createAnonymousId() const
754 // create the anonymous unique id
755 // this value is used for statistics
756 Pathname idpath( home() / "AnonymousUniqueId");
760 updateFileContent( idpath,
761 boost::bind(fileMissing, idpath),
764 catch ( const Exception &e )
766 WAR << "Can't create anonymous id file" << endl;
771 void TargetImpl::createLastDistributionFlavorCache() const
773 // create the anonymous unique id
774 // this value is used for statistics
775 Pathname flavorpath( home() / "LastDistributionFlavor");
777 // is there a product
778 Product::constPtr p = baseProduct();
781 WAR << "No base product, I won't create flavor cache" << endl;
785 string flavor = p->flavor();
790 updateFileContent( flavorpath,
791 // only if flavor is not empty
792 functor::Constant<bool>( ! flavor.empty() ),
793 functor::Constant<string>(flavor) );
795 catch ( const Exception &e )
797 WAR << "Can't create flavor cache" << endl;
802 ///////////////////////////////////////////////////////////////////
804 // METHOD NAME : TargetImpl::~TargetImpl
805 // METHOD TYPE : Dtor
807 TargetImpl::~TargetImpl()
809 _rpm.closeDatabase();
810 MIL << "Targets closed" << endl;
813 ///////////////////////////////////////////////////////////////////
815 // solv file handling
817 ///////////////////////////////////////////////////////////////////
819 Pathname TargetImpl::defaultSolvfilesPath() const
821 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
824 void TargetImpl::clearCache()
826 Pathname base = solvfilesPath();
827 filesystem::recursive_rmdir( base );
830 bool TargetImpl::buildCache()
832 Pathname base = solvfilesPath();
833 Pathname rpmsolv = base/"solv";
834 Pathname rpmsolvcookie = base/"cookie";
836 bool build_rpm_solv = true;
837 // lets see if the rpm solv cache exists
839 RepoStatus rpmstatus( RepoStatus(_root/"var/lib/rpm/Name") && RepoStatus(_root/"etc/products.d") );
841 bool solvexisted = PathInfo(rpmsolv).isExist();
844 // see the status of the cache
845 PathInfo cookie( rpmsolvcookie );
846 MIL << "Read cookie: " << cookie << endl;
847 if ( cookie.isExist() )
849 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
850 // now compare it with the rpm database
851 if ( status == rpmstatus )
852 build_rpm_solv = false;
853 MIL << "Read cookie: " << rpmsolvcookie << " says: "
854 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
858 if ( build_rpm_solv )
860 // if the solvfile dir does not exist yet, we better create it
861 filesystem::assert_dir( base );
863 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
865 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
868 // Can't create temporary solv file, usually due to insufficient permission
869 // (user query while @System solv needs refresh). If so, try switching
870 // to a location within zypps temp. space (will be cleaned at application end).
872 bool switchingToTmpSolvfile = false;
873 Exception ex("Failed to cache rpm database.");
874 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
876 if ( ! solvfilesPathIsTemp() )
878 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
879 rpmsolv = base/"solv";
880 rpmsolvcookie = base/"cookie";
882 filesystem::assert_dir( base );
883 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
887 WAR << "Using a temporary solv file at " << base << endl;
888 switchingToTmpSolvfile = true;
889 _tmpSolvfilesPath = base;
893 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
897 if ( ! switchingToTmpSolvfile )
903 // Take care we unlink the solvfile on exception
904 ManagedFile guard( base, filesystem::recursive_rmdir );
906 std::ostringstream cmd;
908 if ( ! _root.empty() )
909 cmd << " -r '" << _root << "'";
910 cmd << " -X"; // autogenerate pattern/product/... from -package
911 cmd << " -A"; // autogenerate application pseudo packages
912 cmd << " -p '" << Pathname::assertprefix( _root, "/etc/products.d" ) << "'";
914 if ( ! oldSolvFile.empty() )
915 cmd << " '" << oldSolvFile << "'";
917 cmd << " > '" << tmpsolv.path() << "'";
919 MIL << "Executing: " << cmd << endl;
920 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
923 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
924 WAR << " " << output;
925 cmd << " " << output;
928 int ret = prog.close();
931 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
932 ex.remember( cmd.str() );
936 ret = filesystem::rename( tmpsolv, rpmsolv );
938 ZYPP_THROW(Exception("Failed to move cache to final destination"));
939 // if this fails, don't bother throwing exceptions
940 filesystem::chmod( rpmsolv, 0644 );
942 rpmstatus.saveToCookieFile(rpmsolvcookie);
945 guard.resetDispose();
947 // system-hook: Finally send notification to plugins
950 PluginExecutor plugins;
951 plugins.load( ZConfig::instance().pluginsPath()/"system" );
953 plugins.send( PluginFrame( "PACKAGESETCHANGED" ) );
956 return build_rpm_solv;
959 void TargetImpl::reload()
964 void TargetImpl::unload()
966 Repository system( sat::Pool::instance().findSystemRepo() );
968 system.eraseFromPool();
971 void TargetImpl::load( bool force )
973 bool newCache = buildCache();
974 MIL << "New cache built: " << (newCache?"true":"false") <<
975 ", force loading: " << (force?"true":"false") << endl;
977 // now add the repos to the pool
978 sat::Pool satpool( sat::Pool::instance() );
979 Pathname rpmsolv( solvfilesPath() / "solv" );
980 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
982 // Providing an empty system repo, unload any old content
983 Repository system( sat::Pool::instance().findSystemRepo() );
985 if ( system && ! system.solvablesEmpty() )
987 if ( newCache || force )
989 system.eraseFromPool(); // invalidates system
993 return; // nothing to do
999 system = satpool.systemRepo();
1004 MIL << "adding " << rpmsolv << " to system" << endl;
1005 system.addSolv( rpmsolv );
1007 catch ( const Exception & exp )
1010 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1014 system.addSolv( rpmsolv );
1016 sat::Pool::instance().rootDir( _root );
1018 // (Re)Load the requested locales et al.
1019 // If the requested locales are empty, we leave the pool untouched
1020 // to avoid undoing changes the application applied. We expect this
1021 // to happen on a bare metal installation only. An already existing
1022 // target should be loaded before its settings are changed.
1024 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1025 if ( ! requestedLocales.empty() )
1027 satpool.setRequestedLocales( requestedLocales );
1031 if ( ! PathInfo( _autoInstalledFile.file() ).isExist() )
1033 // Initialize from history, if it does not exist
1034 Pathname historyFile( Pathname::assertprefix( _root, ZConfig::instance().historyLogFile() ) );
1035 if ( PathInfo( historyFile ).isExist() )
1037 SolvIdentFile::Data onSystemByUser( getUserInstalledFromHistory( historyFile ) );
1038 SolvIdentFile::Data onSystemByAuto;
1039 for_( it, system.solvablesBegin(), system.solvablesEnd() )
1041 IdString ident( (*it).ident() );
1042 if ( onSystemByUser.find( ident ) == onSystemByUser.end() )
1043 onSystemByAuto.insert( ident );
1045 _autoInstalledFile.setData( onSystemByAuto );
1047 // on the fly removed any obsolete SoftLocks file
1048 filesystem::unlink( home() / "SoftLocks" );
1050 // read from AutoInstalled file
1052 for ( const auto & idstr : _autoInstalledFile.data() )
1053 q.push( idstr.id() );
1054 satpool.setAutoInstalled( q );
1056 if ( ZConfig::instance().apply_locks_file() )
1058 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1059 if ( ! hardLocks.empty() )
1061 ResPool::instance().setHardLockQueries( hardLocks );
1065 // now that the target is loaded, we can cache the flavor
1066 createLastDistributionFlavorCache();
1068 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1071 ///////////////////////////////////////////////////////////////////
1075 ///////////////////////////////////////////////////////////////////
1076 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1078 // ----------------------------------------------------------------- //
1079 ZYppCommitPolicy policy_r( policy_rX );
1081 // Fake outstanding YCP fix: Honour restriction to media 1
1082 // at installation, but install all remaining packages if post-boot.
1083 if ( policy_r.restrictToMedia() > 1 )
1084 policy_r.allMedia();
1086 if ( policy_r.downloadMode() == DownloadDefault ) {
1087 if ( root() == "/" )
1088 policy_r.downloadMode(DownloadInHeaps);
1090 policy_r.downloadMode(DownloadAsNeeded);
1092 // DownloadOnly implies dry-run.
1093 else if ( policy_r.downloadMode() == DownloadOnly )
1094 policy_r.dryRun( true );
1095 // ----------------------------------------------------------------- //
1097 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1099 ///////////////////////////////////////////////////////////////////
1100 // Compute transaction:
1101 ///////////////////////////////////////////////////////////////////
1102 ZYppCommitResult result( root() );
1103 result.rTransaction() = pool_r.resolver().getTransaction();
1104 result.rTransaction().order();
1105 // steps: this is our todo-list
1106 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1107 if ( policy_r.restrictToMedia() )
1109 // Collect until the 1st package from an unwanted media occurs.
1110 // Further collection could violate install order.
1111 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1112 for_( it, result.transaction().begin(), result.transaction().end() )
1114 if ( makeResObject( *it )->mediaNr() > 1 )
1116 steps.push_back( *it );
1121 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1123 MIL << "Todo: " << result << endl;
1125 ///////////////////////////////////////////////////////////////////
1126 // Prepare execution of commit plugins:
1127 ///////////////////////////////////////////////////////////////////
1128 PluginExecutor commitPlugins;
1129 if ( root() == "/" && ! policy_r.dryRun() )
1131 commitPlugins.load( ZConfig::instance().pluginsPath()/"commit" );
1133 if ( commitPlugins )
1134 commitPlugins.send( transactionPluginFrame( "COMMITBEGIN", steps ) );
1136 ///////////////////////////////////////////////////////////////////
1137 // Write out a testcase if we're in dist upgrade mode.
1138 ///////////////////////////////////////////////////////////////////
1139 if ( pool_r.resolver().upgradeMode() || pool_r.resolver().upgradingRepos() )
1141 if ( ! policy_r.dryRun() )
1143 writeUpgradeTestcase();
1147 DBG << "dryRun: Not writing upgrade testcase." << endl;
1151 ///////////////////////////////////////////////////////////////////
1152 // Store non-package data:
1153 ///////////////////////////////////////////////////////////////////
1154 if ( ! policy_r.dryRun() )
1156 filesystem::assert_dir( home() );
1157 // requested locales
1158 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1161 SolvIdentFile::Data newdata;
1162 for ( sat::Queue::value_type id : result.rTransaction().autoInstalled() )
1163 newdata.insert( IdString(id) );
1164 _autoInstalledFile.setData( newdata );
1167 if ( ZConfig::instance().apply_locks_file() )
1169 HardLocksFile::Data newdata;
1170 pool_r.getHardLockQueries( newdata );
1171 _hardLocksFile.setData( newdata );
1176 DBG << "dryRun: Not stroring non-package data." << endl;
1179 ///////////////////////////////////////////////////////////////////
1180 // First collect and display all messages
1181 // associated with patches to be installed.
1182 ///////////////////////////////////////////////////////////////////
1183 if ( ! policy_r.dryRun() )
1185 for_( it, steps.begin(), steps.end() )
1187 if ( ! it->satSolvable().isKind<Patch>() )
1191 if ( ! pi.status().isToBeInstalled() )
1194 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1195 if ( ! patch ||patch->message().empty() )
1198 MIL << "Show message for " << patch << endl;
1199 callback::SendReport<target::PatchMessageReport> report;
1200 if ( ! report->show( patch ) )
1202 WAR << "commit aborted by the user" << endl;
1203 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1209 DBG << "dryRun: Not checking patch messages." << endl;
1212 ///////////////////////////////////////////////////////////////////
1213 // Remove/install packages.
1214 ///////////////////////////////////////////////////////////////////
1215 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1216 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1218 // Prepare the package cache. Pass all items requiring download.
1219 CommitPackageCache packageCache( root() );
1220 packageCache.setCommitList( steps.begin(), steps.end() );
1223 if ( policy_r.downloadMode() != DownloadAsNeeded )
1225 // Preload the cache. Until now this means pre-loading all packages.
1226 // Once DownloadInHeaps is fully implemented, this will change and
1227 // we may actually have more than one heap.
1228 for_( it, steps.begin(), steps.end() )
1230 switch ( it->stepType() )
1232 case sat::Transaction::TRANSACTION_INSTALL:
1233 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1234 // proceed: only install actionas may require download.
1238 // next: no download for or non-packages and delete actions.
1244 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1246 ManagedFile localfile;
1249 // TODO: unify packageCache.get for Package and SrcPackage
1250 if ( pi->isKind<Package>() )
1252 localfile = packageCache.get( pi );
1254 else if ( pi->isKind<SrcPackage>() )
1256 repo::RepoMediaAccess access;
1257 repo::SrcPackageProvider prov( access );
1258 localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1262 INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1265 localfile.resetDispose(); // keep the package file in the cache
1267 catch ( const AbortRequestException & exp )
1269 it->stepStage( sat::Transaction::STEP_ERROR );
1271 WAR << "commit cache preload aborted by the user" << endl;
1272 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1275 catch ( const SkipRequestException & exp )
1278 it->stepStage( sat::Transaction::STEP_ERROR );
1280 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1283 catch ( const Exception & exp )
1285 // bnc #395704: missing catch causes abort.
1286 // TODO see if packageCache fails to handle errors correctly.
1288 it->stepStage( sat::Transaction::STEP_ERROR );
1290 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1295 packageCache.preloaded( true ); // try to avoid duplicate infoInCache CBs in commit
1300 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1304 if ( ! policy_r.dryRun() )
1306 // if cache is preloaded, check for file conflicts
1307 commitFindFileConflicts( policy_r, result );
1308 commit( policy_r, packageCache, result );
1312 DBG << "dryRun/downloadOnly: Not installing/deleting anything." << endl;
1318 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1321 ///////////////////////////////////////////////////////////////////
1322 // Send result to commit plugins:
1323 ///////////////////////////////////////////////////////////////////
1324 if ( commitPlugins )
1325 commitPlugins.send( transactionPluginFrame( "COMMITEND", steps ) );
1327 ///////////////////////////////////////////////////////////////////
1328 // Try to rebuild solv file while rpm database is still in cache
1329 ///////////////////////////////////////////////////////////////////
1330 if ( ! policy_r.dryRun() )
1335 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1339 ///////////////////////////////////////////////////////////////////
1343 ///////////////////////////////////////////////////////////////////
1346 struct NotifyAttemptToModify
1348 NotifyAttemptToModify( ZYppCommitResult & result_r ) : _result( result_r ) {}
1351 { if ( _guard ) { _result.attemptToModify( true ); _guard = false; } }
1354 ZYppCommitResult & _result;
1358 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1359 CommitPackageCache & packageCache_r,
1360 ZYppCommitResult & result_r )
1362 // steps: this is our todo-list
1363 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1364 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1366 // Send notification once upon 1st call to rpm
1367 NotifyAttemptToModify attemptToModify( result_r );
1371 RpmPostTransCollector postTransCollector( _root );
1372 std::vector<sat::Solvable> successfullyInstalledPackages;
1373 TargetImpl::PoolItemList remaining;
1375 for_( step, steps.begin(), steps.end() )
1377 PoolItem citem( *step );
1378 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1380 if ( citem->isKind<Package>() )
1382 // for packages this means being obsoleted (by rpm)
1383 // thius no additional action is needed.
1384 step->stepStage( sat::Transaction::STEP_DONE );
1389 if ( citem->isKind<Package>() )
1391 Package::constPtr p = citem->asKind<Package>();
1392 if ( citem.status().isToBeInstalled() )
1394 ManagedFile localfile;
1397 localfile = packageCache_r.get( citem );
1399 catch ( const AbortRequestException &e )
1401 WAR << "commit aborted by the user" << endl;
1403 step->stepStage( sat::Transaction::STEP_ERROR );
1406 catch ( const SkipRequestException &e )
1409 WAR << "Skipping package " << p << " in commit" << endl;
1410 step->stepStage( sat::Transaction::STEP_ERROR );
1413 catch ( const Exception &e )
1415 // bnc #395704: missing catch causes abort.
1416 // TODO see if packageCache fails to handle errors correctly.
1418 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1419 step->stepStage( sat::Transaction::STEP_ERROR );
1423 #warning Exception handling
1424 // create a installation progress report proxy
1425 RpmInstallPackageReceiver progress( citem.resolvable() );
1426 progress.connect(); // disconnected on destruction.
1428 bool success = false;
1429 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1430 // Why force and nodeps?
1432 // Because zypp builds the transaction and the resolver asserts that
1433 // everything is fine.
1434 // We use rpm just to unpack and register the package in the database.
1435 // We do this step by step, so rpm is not aware of the bigger context.
1436 // So we turn off rpms internal checks, because we do it inside zypp.
1437 flags |= rpm::RPMINST_NODEPS;
1438 flags |= rpm::RPMINST_FORCE;
1440 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1441 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1442 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1443 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1448 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1449 if ( postTransCollector.collectScriptFromPackage( localfile ) )
1450 flags |= rpm::RPMINST_NOPOSTTRANS;
1451 rpm().installPackage( localfile, flags );
1452 HistoryLog().install(citem);
1454 if ( progress.aborted() )
1456 WAR << "commit aborted by the user" << endl;
1457 localfile.resetDispose(); // keep the package file in the cache
1459 step->stepStage( sat::Transaction::STEP_ERROR );
1465 step->stepStage( sat::Transaction::STEP_DONE );
1468 catch ( Exception & excpt_r )
1470 ZYPP_CAUGHT(excpt_r);
1471 localfile.resetDispose(); // keep the package file in the cache
1473 if ( policy_r.dryRun() )
1475 WAR << "dry run failed" << endl;
1476 step->stepStage( sat::Transaction::STEP_ERROR );
1480 if ( progress.aborted() )
1482 WAR << "commit aborted by the user" << endl;
1487 WAR << "Install failed" << endl;
1489 step->stepStage( sat::Transaction::STEP_ERROR );
1493 if ( success && !policy_r.dryRun() )
1495 citem.status().resetTransact( ResStatus::USER );
1496 successfullyInstalledPackages.push_back( citem.satSolvable() );
1497 step->stepStage( sat::Transaction::STEP_DONE );
1502 RpmRemovePackageReceiver progress( citem.resolvable() );
1503 progress.connect(); // disconnected on destruction.
1505 bool success = false;
1506 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1507 flags |= rpm::RPMINST_NODEPS;
1508 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1513 rpm().removePackage( p, flags );
1514 HistoryLog().remove(citem);
1516 if ( progress.aborted() )
1518 WAR << "commit aborted by the user" << endl;
1520 step->stepStage( sat::Transaction::STEP_ERROR );
1526 step->stepStage( sat::Transaction::STEP_DONE );
1529 catch (Exception & excpt_r)
1531 ZYPP_CAUGHT( excpt_r );
1532 if ( progress.aborted() )
1534 WAR << "commit aborted by the user" << endl;
1536 step->stepStage( sat::Transaction::STEP_ERROR );
1540 WAR << "removal of " << p << " failed";
1541 step->stepStage( sat::Transaction::STEP_ERROR );
1543 if ( success && !policy_r.dryRun() )
1545 citem.status().resetTransact( ResStatus::USER );
1546 step->stepStage( sat::Transaction::STEP_DONE );
1550 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1552 // Status is changed as the buddy package buddy
1553 // gets installed/deleted. Handle non-buddies only.
1554 if ( ! citem.buddy() )
1556 if ( citem->isKind<Product>() )
1558 Product::constPtr p = citem->asKind<Product>();
1559 if ( citem.status().isToBeInstalled() )
1561 ERR << "Can't install orphan product without release-package! " << citem << endl;
1565 // Deleting the corresponding product entry is all we con do.
1566 // So the product will no longer be visible as installed.
1567 std::string referenceFilename( p->referenceFilename() );
1568 if ( referenceFilename.empty() )
1570 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1574 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1575 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1577 ERR << "Delete orphan product failed: " << referenceFile << endl;
1582 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1584 // SrcPackage is install-only
1585 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1586 installSrcPackage( p );
1589 citem.status().resetTransact( ResStatus::USER );
1590 step->stepStage( sat::Transaction::STEP_DONE );
1593 } // other resolvables
1597 // process all remembered posttrans scripts.
1599 postTransCollector.executeScripts();
1601 postTransCollector.discardScripts();
1603 // Check presence of update scripts/messages. If aborting,
1604 // at least log omitted scripts.
1605 if ( ! successfullyInstalledPackages.empty() )
1607 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1608 successfullyInstalledPackages, abort ) )
1610 WAR << "Commit aborted by the user" << endl;
1613 // send messages after scripts in case some script generates output,
1614 // that should be kept in t %ghost message file.
1615 RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1616 successfullyInstalledPackages,
1622 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1626 ///////////////////////////////////////////////////////////////////
1628 rpm::RpmDb & TargetImpl::rpm()
1633 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1635 return _rpm.hasFile(path_str, name_str);
1639 Date TargetImpl::timestamp() const
1641 return _rpm.timestamp();
1644 ///////////////////////////////////////////////////////////////////
1647 parser::ProductFileData baseproductdata( const Pathname & root_r )
1649 parser::ProductFileData ret;
1650 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1652 if ( baseproduct.isFile() )
1656 ret = parser::ProductFileReader::scanFile( baseproduct.path() );
1658 catch ( const Exception & excpt )
1660 ZYPP_CAUGHT( excpt );
1663 else if ( PathInfo( Pathname::assertprefix( root_r, "/etc/products.d" ) ).isDir() )
1665 ERR << "baseproduct symlink is dangling or missing: " << baseproduct << endl;
1670 inline Pathname staticGuessRoot( const Pathname & root_r )
1672 if ( root_r.empty() )
1674 // empty root: use existing Target or assume "/"
1675 Pathname ret ( ZConfig::instance().systemRoot() );
1677 return Pathname("/");
1683 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1685 std::ifstream idfile( file_r.c_str() );
1686 for( iostr::EachLine in( idfile ); in; in.next() )
1688 std::string line( str::trim( *in ) );
1689 if ( ! line.empty() )
1692 return std::string();
1695 ///////////////////////////////////////////////////////////////////
1697 Product::constPtr TargetImpl::baseProduct() const
1699 ResPool pool(ResPool::instance());
1700 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1702 Product::constPtr p = (*it)->asKind<Product>();
1703 if ( p->isTargetDistribution() )
1709 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1711 const Pathname needroot( staticGuessRoot(root_r) );
1712 const Target_constPtr target( getZYpp()->getTarget() );
1713 if ( target && target->root() == needroot )
1714 return target->requestedLocales();
1715 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1718 std::string TargetImpl::targetDistribution() const
1719 { return baseproductdata( _root ).registerTarget(); }
1721 std::string TargetImpl::targetDistribution( const Pathname & root_r )
1722 { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1724 std::string TargetImpl::targetDistributionRelease() const
1725 { return baseproductdata( _root ).registerRelease(); }
1727 std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1728 { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1730 std::string TargetImpl::targetDistributionFlavor() const
1731 { return baseproductdata( _root ).registerFlavor(); }
1733 std::string TargetImpl::targetDistributionFlavor( const Pathname & root_r )
1734 { return baseproductdata( staticGuessRoot(root_r) ).registerFlavor();}
1736 Target::DistributionLabel TargetImpl::distributionLabel() const
1738 Target::DistributionLabel ret;
1739 parser::ProductFileData pdata( baseproductdata( _root ) );
1740 ret.shortName = pdata.shortName();
1741 ret.summary = pdata.summary();
1745 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1747 Target::DistributionLabel ret;
1748 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1749 ret.shortName = pdata.shortName();
1750 ret.summary = pdata.summary();
1754 std::string TargetImpl::distributionVersion() const
1756 if ( _distributionVersion.empty() )
1758 _distributionVersion = TargetImpl::distributionVersion(root());
1759 if ( !_distributionVersion.empty() )
1760 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1762 return _distributionVersion;
1765 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1767 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1768 if ( distributionVersion.empty() )
1770 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1771 // On RHEL, Fedora and others the "product version" is determined by the first package
1772 // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1773 // with the $distroverpkg variable.
1774 scoped_ptr<rpm::RpmDb> tmprpmdb;
1775 if ( ZConfig::instance().systemRoot() == Pathname() )
1779 tmprpmdb.reset( new rpm::RpmDb );
1780 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1787 rpm::librpmDb::db_const_iterator it;
1788 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1789 distributionVersion = it->tag_version();
1791 return distributionVersion;
1795 std::string TargetImpl::distributionFlavor() const
1797 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1800 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1802 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1805 ///////////////////////////////////////////////////////////////////
1807 std::string TargetImpl::anonymousUniqueId() const
1809 return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1812 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1814 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1817 ///////////////////////////////////////////////////////////////////
1819 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1821 // provide on local disk
1822 ManagedFile localfile = provideSrcPackage(srcPackage_r);
1824 rpm().installPackage ( localfile );
1827 ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1829 // provide on local disk
1830 repo::RepoMediaAccess access_r;
1831 repo::SrcPackageProvider prov( access_r );
1832 return prov.provideSrcPackage( srcPackage_r );
1834 ////////////////////////////////////////////////////////////////
1835 } // namespace target
1836 ///////////////////////////////////////////////////////////////////
1837 /////////////////////////////////////////////////////////////////
1839 ///////////////////////////////////////////////////////////////////