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/DeltaCandidates.h"
55 #include "zypp/repo/PackageProvider.h"
56 #include "zypp/repo/SrcPackageProvider.h"
58 #include "zypp/sat/Pool.h"
59 #include "zypp/sat/Transaction.h"
61 #include "zypp/PluginScript.h"
65 ///////////////////////////////////////////////////////////////////
67 { /////////////////////////////////////////////////////////////////
68 ///////////////////////////////////////////////////////////////////
71 // Lazy via template specialisation / should switch to overloading
74 inline std::string toJSON( const ZYppCommitResult::TransactionStepList & steps_r )
76 using sat::Transaction;
79 for ( const Transaction::Step & step : steps_r )
80 // ignore implicit deletes due to obsoletes and non-package actions
81 if ( step.stepType() != Transaction::TRANSACTION_IGNORE )
87 /** See \ref commitbegin on page \ref plugin-commit for the specs. */
89 inline std::string toJSON( const sat::Transaction::Step & step_r )
91 static const std::string strType( "type" );
92 static const std::string strStage( "stage" );
93 static const std::string strSolvable( "solvable" );
95 static const std::string strTypeDel( "-" );
96 static const std::string strTypeIns( "+" );
97 static const std::string strTypeMul( "M" );
99 static const std::string strStageDone( "ok" );
100 static const std::string strStageFailed( "err" );
102 static const std::string strSolvableN( "n" );
103 static const std::string strSolvableE( "e" );
104 static const std::string strSolvableV( "v" );
105 static const std::string strSolvableR( "r" );
106 static const std::string strSolvableA( "a" );
108 using sat::Transaction;
111 switch ( step_r.stepType() )
113 case Transaction::TRANSACTION_IGNORE: /*empty*/ break;
114 case Transaction::TRANSACTION_ERASE: ret.add( strType, strTypeDel ); break;
115 case Transaction::TRANSACTION_INSTALL: ret.add( strType, strTypeIns ); break;
116 case Transaction::TRANSACTION_MULTIINSTALL: ret.add( strType, strTypeMul ); break;
119 switch ( step_r.stepStage() )
121 case Transaction::STEP_TODO: /*empty*/ break;
122 case Transaction::STEP_DONE: ret.add( strStage, strStageDone ); break;
123 case Transaction::STEP_ERROR: ret.add( strStage, strStageFailed ); break;
130 if ( sat::Solvable solv = step_r.satSolvable() )
132 ident = solv.ident();
138 // deleted package; post mortem data stored in Transaction::Step
139 ident = step_r.ident();
140 ed = step_r.edition();
141 arch = step_r.arch();
145 { strSolvableN, ident.asString() },
146 { strSolvableV, ed.version() },
147 { strSolvableR, ed.release() },
148 { strSolvableA, arch.asString() }
150 if ( Edition::epoch_t epoch = ed.epoch() )
151 s.add( strSolvableE, epoch );
153 ret.add( strSolvable, s );
159 ///////////////////////////////////////////////////////////////////
160 ///////////////////////////////////////////////////////////////////
162 { /////////////////////////////////////////////////////////////////
164 /** Helper for commit plugin execution.
167 class CommitPlugins : private base::NonCopyable
170 /** Default ctor: Empty plugin list */
174 /** Dtor: Send PLUGINEND message and close plugins. */
177 if ( ! _scripts.empty() )
178 send( PluginFrame( "PLUGINEND" ) );
179 // ~PluginScript will disconnect all remaining plugins!
182 /** Whether no plugins are waiting */
184 { return _scripts.empty(); }
187 /** Send \ref PluginFrame to all open plugins.
188 * Failed plugins are removed from the execution list.
190 void send( const PluginFrame & frame_r )
192 DBG << "+++++++++++++++ send " << frame_r << endl;
193 for ( auto it = _scripts.begin(); it != _scripts.end(); )
195 doSend( *it, frame_r );
199 it = _scripts.erase( it );
201 DBG << "--------------- send " << frame_r << endl;
204 /** Find and launch plugins sending PLUGINSTART message.
206 * If \a path_r is a directory all executable files whithin are
207 * expected to be plugins. Otherwise \a path_r must point to an
210 void load( const Pathname & path_r )
212 PathInfo pi( path_r );
213 DBG << "+++++++++++++++ load " << pi << endl;
216 std::list<Pathname> entries;
217 if ( filesystem::readdir( entries, pi.path(), false ) != 0 )
219 WAR << "Plugin dir is not readable: " << pi << endl;
222 for_( it, entries.begin(), entries.end() )
225 if ( pii.isFile() && pii.userMayRX() )
229 else if ( pi.isFile() )
231 if ( pi.userMayRX() )
234 WAR << "Plugin file is not executable: " << pi << endl;
238 WAR << "Plugin path is neither dir nor file: " << pi << endl;
240 DBG << "--------------- load " << pi << endl;
244 /** Send \ref PluginFrame and expect valid answer (ACK|_ENOMETHOD).
245 * Upon invalid answer or error, close the plugin. and remove it from the
247 * \returns the received \ref PluginFrame (empty Frame upon Exception)
249 PluginFrame doSend( PluginScript & script_r, const PluginFrame & frame_r )
254 script_r.send( frame_r );
255 ret = script_r.receive();
257 catch( const zypp::Exception & e )
260 if ( ! ( ret.isAckCommand() || ret.isEnomethodCommand() ) )
262 WAR << "Bad plugin response from " << script_r << endl;
263 WAR << dump(ret) << endl;
270 /** Launch a plugin sending PLUGINSTART message. */
271 void doLoad( const PathInfo & pi_r )
273 MIL << "Load plugin: " << pi_r << endl;
275 PluginScript plugin( pi_r.path() );
278 PluginFrame frame( "PLUGINBEGIN" );
279 if ( ZConfig::instance().hasUserData() )
280 frame.setHeader( "userdata", ZConfig::instance().userData() );
282 doSend( plugin, frame ); // closes on error
283 if ( plugin.isOpen() )
284 _scripts.push_back( plugin );
286 catch( const zypp::Exception & e )
288 WAR << "Failed to load plugin " << pi_r << endl;
293 std::list<PluginScript> _scripts;
296 void testCommitPlugins( const Pathname & path_r ) // for testing only
298 USR << "+++++" << endl;
302 USR << "=====" << endl;
304 USR << "-----" << endl;
307 ///////////////////////////////////////////////////////////////////
310 inline PluginFrame transactionPluginFrame( const std::string & command_r, ZYppCommitResult::TransactionStepList & steps_r )
312 return PluginFrame( command_r, json::Object {
313 { "TransactionStepList", steps_r }
317 ///////////////////////////////////////////////////////////////////
319 /** \internal Manage writing a new testcase when doing an upgrade. */
320 void writeUpgradeTestcase()
322 unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
323 MIL << "Testcases to keep: " << toKeep << endl;
326 Target_Ptr target( getZYpp()->getTarget() );
329 WAR << "No Target no Testcase!" << endl;
333 std::string stem( "updateTestcase" );
334 Pathname dir( target->assertRootPrefix("/var/log/") );
335 Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
338 std::list<std::string> content;
339 filesystem::readdir( content, dir, /*dots*/false );
340 std::set<std::string> cases;
341 for_( c, content.begin(), content.end() )
343 if ( str::startsWith( *c, stem ) )
346 if ( cases.size() >= toKeep )
348 unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
349 for_( c, cases.begin(), cases.end() )
351 filesystem::recursive_rmdir( dir/(*c) );
358 MIL << "Write new testcase " << next << endl;
359 getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
362 ///////////////////////////////////////////////////////////////////
364 { /////////////////////////////////////////////////////////////////
366 /** Execute script and report against report_r.
367 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
368 * execution was successfull (<tt>first = true</tt>), or the desired
369 * \c PatchScriptReport::Action in case execution failed
370 * (<tt>first = false</tt>).
372 * \note The packager is responsible for setting the correct permissions
373 * of the script. If the script is not executable it is reported as an
374 * error. We must not modify the permessions.
376 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
377 const Pathname & script_r,
378 callback::SendReport<PatchScriptReport> & report_r )
380 MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
382 HistoryLog historylog;
383 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
384 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
386 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
388 historylog.comment(output);
389 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
391 WAR << "User request to abort script " << script_r << endl;
393 // the rest is handled by exit code evaluation
394 // in case the script has meanwhile finished.
398 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
400 if ( prog.close() != 0 )
402 ret.second = report_r->problem( prog.execError() );
403 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
404 std::ostringstream sstr;
405 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
406 historylog.comment(sstr.str(), /*timestamp*/true);
415 /** Execute script and report against report_r.
416 * Return \c false if user requested \c ABORT.
418 bool executeScript( const Pathname & root_r,
419 const Pathname & script_r,
420 callback::SendReport<PatchScriptReport> & report_r )
422 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
425 action = doExecuteScript( root_r, script_r, report_r );
427 return true; // success
429 switch ( action.second )
431 case PatchScriptReport::ABORT:
432 WAR << "User request to abort at script " << script_r << endl;
433 return false; // requested abort.
436 case PatchScriptReport::IGNORE:
437 WAR << "User request to skip script " << script_r << endl;
438 return true; // requested skip.
441 case PatchScriptReport::RETRY:
444 } while ( action.second == PatchScriptReport::RETRY );
446 // THIS is not intended to be reached:
447 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
448 return false; // abort.
451 /** Look for update scripts named 'name-version-release-*' and
452 * execute them. Return \c false if \c ABORT was requested.
454 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
456 bool RunUpdateScripts( const Pathname & root_r,
457 const Pathname & scriptsPath_r,
458 const std::vector<sat::Solvable> & checkPackages_r,
461 if ( checkPackages_r.empty() )
462 return true; // no installed packages to check
464 MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
465 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
466 if ( ! PathInfo( scriptsDir ).isDir() )
467 return true; // no script dir
469 std::list<std::string> scripts;
470 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
471 if ( scripts.empty() )
472 return true; // no scripts in script dir
474 // Now collect and execute all matching scripts.
475 // On ABORT: at least log all outstanding scripts.
476 // - "name-version-release"
477 // - "name-version-release-*"
479 std::map<std::string, Pathname> unify; // scripts <md5,path>
480 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
482 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
483 for_( sit, scripts.begin(), scripts.end() )
485 if ( ! str::hasPrefix( *sit, prefix ) )
488 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
489 continue; // if not exact match it had to continue with '-'
491 PathInfo script( scriptsDir / *sit );
492 Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
493 std::string unifytag; // must not stay empty
495 if ( script.isFile() )
497 // Assert it's set executable, unify by md5sum.
498 filesystem::addmod( script.path(), 0500 );
499 unifytag = filesystem::md5sum( script.path() );
501 else if ( ! script.isExist() )
503 // Might be a dangling symlink, might be ok if we are in
504 // instsys (absolute symlink within the system below /mnt).
505 // readlink will tell....
506 unifytag = filesystem::readlink( script.path() ).asString();
509 if ( unifytag.empty() )
513 if ( unify[unifytag].empty() )
515 unify[unifytag] = localPath;
519 // translators: We may find the same script content in files with different names.
520 // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
521 // message for a log file. Preferably start translation with "%s"
522 std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
523 MIL << "Skip update script: " << msg << endl;
524 HistoryLog().comment( msg, /*timestamp*/true );
528 if ( abort || aborting_r )
530 WAR << "Aborting: Skip update script " << *sit << endl;
531 HistoryLog().comment(
532 localPath.asString() + _(" execution skipped while aborting"),
537 MIL << "Found update script " << *sit << endl;
538 callback::SendReport<PatchScriptReport> report;
539 report->start( make<Package>( *it ), script.path() );
541 if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
542 abort = true; // requested abort.
549 ///////////////////////////////////////////////////////////////////
551 ///////////////////////////////////////////////////////////////////
553 inline void copyTo( std::ostream & out_r, const Pathname & file_r )
555 std::ifstream infile( file_r.c_str() );
556 for( iostr::EachLine in( infile ); in; in.next() )
558 out_r << *in << endl;
562 inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
564 std::string ret( cmd_r );
565 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
566 SUBST_IF( "%p", notification_r.solvable().asString() );
567 SUBST_IF( "%P", notification_r.file().asString() );
572 void sendNotification( const Pathname & root_r,
573 const UpdateNotifications & notifications_r )
575 if ( notifications_r.empty() )
578 std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
579 MIL << "Notification command is '" << cmdspec << "'" << endl;
580 if ( cmdspec.empty() )
583 std::string::size_type pos( cmdspec.find( '|' ) );
584 if ( pos == std::string::npos )
586 ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
587 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
591 std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
592 std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
594 enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
595 Format format = UNKNOWN;
596 if ( formatStr == "none" )
598 else if ( formatStr == "single" )
600 else if ( formatStr == "digest" )
602 else if ( formatStr == "bulk" )
606 ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
607 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
611 // Take care: commands are ececuted chroot(root_r). The message file
612 // pathnames in notifications_r are local to root_r. For physical access
613 // to the file they need to be prefixed.
615 if ( format == NONE || format == SINGLE )
617 for_( it, notifications_r.begin(), notifications_r.end() )
619 std::vector<std::string> command;
620 if ( format == SINGLE )
621 command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
622 str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
624 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
625 if ( true ) // Wait for feedback
627 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
631 int ret = prog.close();
634 ERR << "Notification command returned with error (" << ret << ")." << endl;
635 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
641 else if ( format == DIGEST || format == BULK )
643 filesystem::TmpFile tmpfile;
644 ofstream out( tmpfile.path().c_str() );
645 for_( it, notifications_r.begin(), notifications_r.end() )
647 if ( format == DIGEST )
649 out << it->file() << endl;
651 else if ( format == BULK )
653 copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
657 std::vector<std::string> command;
658 command.push_back( "<"+tmpfile.path().asString() ); // redirect input
659 str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
661 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
662 if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
664 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
668 int ret = prog.close();
671 ERR << "Notification command returned with error (" << ret << ")." << endl;
672 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
679 INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
680 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
686 /** Look for update messages named 'name-version-release-*' and
687 * send notification according to \ref ZConfig::updateMessagesNotify.
689 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
691 void RunUpdateMessages( const Pathname & root_r,
692 const Pathname & messagesPath_r,
693 const std::vector<sat::Solvable> & checkPackages_r,
694 ZYppCommitResult & result_r )
696 if ( checkPackages_r.empty() )
697 return; // no installed packages to check
699 MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
700 Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
701 if ( ! PathInfo( messagesDir ).isDir() )
702 return; // no messages dir
704 std::list<std::string> messages;
705 filesystem::readdir( messages, messagesDir, /*dots*/false );
706 if ( messages.empty() )
707 return; // no messages in message dir
709 // Now collect all matching messages in result and send them
710 // - "name-version-release"
711 // - "name-version-release-*"
712 HistoryLog historylog;
713 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
715 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
716 for_( sit, messages.begin(), messages.end() )
718 if ( ! str::hasPrefix( *sit, prefix ) )
721 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
722 continue; // if not exact match it had to continue with '-'
724 PathInfo message( messagesDir / *sit );
725 if ( ! message.isFile() || message.size() == 0 )
728 MIL << "Found update message " << *sit << endl;
729 Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
730 result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
731 historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
734 sendNotification( root_r, result_r.updateMessages() );
737 /////////////////////////////////////////////////////////////////
739 ///////////////////////////////////////////////////////////////////
741 void XRunUpdateMessages( const Pathname & root_r,
742 const Pathname & messagesPath_r,
743 const std::vector<sat::Solvable> & checkPackages_r,
744 ZYppCommitResult & result_r )
745 { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
747 /** Helper for PackageProvider queries during commit. */
748 struct QueryInstalledEditionHelper
750 bool operator()( const std::string & name_r,
751 const Edition & ed_r,
752 const Arch & arch_r ) const
754 rpm::librpmDb::db_const_iterator it;
755 for ( it.findByName( name_r ); *it; ++it )
757 if ( arch_r == it->tag_arch()
758 && ( ed_r == Edition::noedition || ed_r == it->tag_edition() ) )
768 * \short Let the Source provide the package.
769 * \p pool_r \ref ResPool used to get candidates
770 * \p pi item to be commited
772 struct RepoProvidePackage
774 repo::RepoMediaAccess &_access;
775 std::list<Repository> _repos;
776 repo::PackageProviderPolicy _packageProviderPolicy;
778 RepoProvidePackage( repo::RepoMediaAccess &access, ResPool pool_r )
779 : _access(access), _repos( pool_r.knownRepositoriesBegin(), pool_r.knownRepositoriesEnd() )
781 _packageProviderPolicy.queryInstalledCB( QueryInstalledEditionHelper() );
784 ManagedFile operator()( const PoolItem & pi, bool fromCache_r )
786 Package::constPtr p = asKind<Package>(pi.resolvable());
789 repo::PackageProvider pkgProvider( _access, p, repo::DeltaCandidates(), _packageProviderPolicy );
790 return pkgProvider.providePackageFromCache();
794 repo::DeltaCandidates deltas( _repos, p->name() );
795 repo::PackageProvider pkgProvider( _access, p, deltas, _packageProviderPolicy );
796 return pkgProvider.providePackage();
800 ///////////////////////////////////////////////////////////////////
802 IMPL_PTR_TYPE(TargetImpl);
804 TargetImpl_Ptr TargetImpl::_nullimpl;
806 /** Null implementation */
807 TargetImpl_Ptr TargetImpl::nullimpl()
810 _nullimpl = new TargetImpl;
814 ///////////////////////////////////////////////////////////////////
816 // METHOD NAME : TargetImpl::TargetImpl
817 // METHOD TYPE : Ctor
819 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
821 , _requestedLocalesFile( home() / "RequestedLocales" )
822 , _softLocksFile( home() / "SoftLocks" )
823 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
825 _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
827 HistoryLog::setRoot(_root);
831 MIL << "Initialized target on " << _root << endl;
835 * generates a random id using uuidgen
837 static std::string generateRandomId()
839 std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
840 return iostr::getline( uuidprovider );
844 * updates the content of \p filename
845 * if \p condition is true, setting the content
846 * the the value returned by \p value
848 void updateFileContent( const Pathname &filename,
849 boost::function<bool ()> condition,
850 boost::function<string ()> value )
852 string val = value();
853 // if the value is empty, then just dont
854 // do anything, regardless of the condition
860 MIL << "updating '" << filename << "' content." << endl;
862 // if the file does not exist we need to generate the uuid file
864 std::ofstream filestr;
865 // make sure the path exists
866 filesystem::assert_dir( filename.dirname() );
867 filestr.open( filename.c_str() );
869 if ( filestr.good() )
876 // FIXME, should we ignore the error?
877 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
882 /** helper functor */
883 static bool fileMissing( const Pathname &pathname )
885 return ! PathInfo(pathname).isExist();
888 void TargetImpl::createAnonymousId() const
891 // create the anonymous unique id
892 // this value is used for statistics
893 Pathname idpath( home() / "AnonymousUniqueId");
897 updateFileContent( idpath,
898 boost::bind(fileMissing, idpath),
901 catch ( const Exception &e )
903 WAR << "Can't create anonymous id file" << endl;
908 void TargetImpl::createLastDistributionFlavorCache() const
910 // create the anonymous unique id
911 // this value is used for statistics
912 Pathname flavorpath( home() / "LastDistributionFlavor");
914 // is there a product
915 Product::constPtr p = baseProduct();
918 WAR << "No base product, I won't create flavor cache" << endl;
922 string flavor = p->flavor();
927 updateFileContent( flavorpath,
928 // only if flavor is not empty
929 functor::Constant<bool>( ! flavor.empty() ),
930 functor::Constant<string>(flavor) );
932 catch ( const Exception &e )
934 WAR << "Can't create flavor cache" << endl;
939 ///////////////////////////////////////////////////////////////////
941 // METHOD NAME : TargetImpl::~TargetImpl
942 // METHOD TYPE : Dtor
944 TargetImpl::~TargetImpl()
946 _rpm.closeDatabase();
947 MIL << "Targets closed" << endl;
950 ///////////////////////////////////////////////////////////////////
952 // solv file handling
954 ///////////////////////////////////////////////////////////////////
956 Pathname TargetImpl::defaultSolvfilesPath() const
958 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
961 void TargetImpl::clearCache()
963 Pathname base = solvfilesPath();
964 filesystem::recursive_rmdir( base );
967 bool TargetImpl::buildCache()
969 Pathname base = solvfilesPath();
970 Pathname rpmsolv = base/"solv";
971 Pathname rpmsolvcookie = base/"cookie";
973 bool build_rpm_solv = true;
974 // lets see if the rpm solv cache exists
976 RepoStatus rpmstatus( RepoStatus( _root/"/var/lib/rpm/Name" )
977 && (_root/"/etc/products.d") );
979 bool solvexisted = PathInfo(rpmsolv).isExist();
982 // see the status of the cache
983 PathInfo cookie( rpmsolvcookie );
984 MIL << "Read cookie: " << cookie << endl;
985 if ( cookie.isExist() )
987 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
988 // now compare it with the rpm database
989 if ( status.checksum() == rpmstatus.checksum() )
990 build_rpm_solv = false;
991 MIL << "Read cookie: " << rpmsolvcookie << " says: "
992 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
996 if ( build_rpm_solv )
998 // if the solvfile dir does not exist yet, we better create it
999 filesystem::assert_dir( base );
1001 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
1003 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
1006 // Can't create temporary solv file, usually due to insufficient permission
1007 // (user query while @System solv needs refresh). If so, try switching
1008 // to a location within zypps temp. space (will be cleaned at application end).
1010 bool switchingToTmpSolvfile = false;
1011 Exception ex("Failed to cache rpm database.");
1012 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
1014 if ( ! solvfilesPathIsTemp() )
1016 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
1017 rpmsolv = base/"solv";
1018 rpmsolvcookie = base/"cookie";
1020 filesystem::assert_dir( base );
1021 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
1025 WAR << "Using a temporary solv file at " << base << endl;
1026 switchingToTmpSolvfile = true;
1027 _tmpSolvfilesPath = base;
1031 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
1035 if ( ! switchingToTmpSolvfile )
1041 // Take care we unlink the solvfile on exception
1042 ManagedFile guard( base, filesystem::recursive_rmdir );
1044 std::ostringstream cmd;
1045 cmd << "rpmdb2solv";
1046 if ( ! _root.empty() )
1047 cmd << " -r '" << _root << "'";
1048 cmd << " -X"; // autogenerate pattern/product/... from -package
1049 cmd << " -A"; // autogenerate application pseudo packages
1050 cmd << " -p '" << Pathname::assertprefix( _root, "/etc/products.d" ) << "'";
1052 if ( ! oldSolvFile.empty() )
1053 cmd << " '" << oldSolvFile << "'";
1055 cmd << " > '" << tmpsolv.path() << "'";
1057 MIL << "Executing: " << cmd << endl;
1058 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
1061 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1062 WAR << " " << output;
1063 cmd << " " << output;
1066 int ret = prog.close();
1069 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
1070 ex.remember( cmd.str() );
1074 ret = filesystem::rename( tmpsolv, rpmsolv );
1076 ZYPP_THROW(Exception("Failed to move cache to final destination"));
1077 // if this fails, don't bother throwing exceptions
1078 filesystem::chmod( rpmsolv, 0644 );
1080 rpmstatus.saveToCookieFile(rpmsolvcookie);
1083 guard.resetDispose();
1085 // Finally send notification to plugins
1086 // NOTE: quick hack looking for spacewalk plugin only
1088 Pathname script( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"system/spacewalk" ) );
1089 if ( PathInfo( script ).isX() )
1091 PluginScript spacewalk( script );
1094 PluginFrame notify( "PACKAGESETCHANGED" );
1095 spacewalk.send( notify );
1097 PluginFrame ret( spacewalk.receive() );
1099 if ( ret.command() == "ERROR" )
1100 ret.writeTo( WAR ) << endl;
1102 catch ( const Exception & excpt )
1104 WAR << excpt.asUserHistory() << endl;
1108 return build_rpm_solv;
1111 void TargetImpl::reload()
1116 void TargetImpl::unload()
1118 Repository system( sat::Pool::instance().findSystemRepo() );
1120 system.eraseFromPool();
1123 void TargetImpl::load( bool force )
1125 bool newCache = buildCache();
1126 MIL << "New cache built: " << (newCache?"true":"false") <<
1127 ", force loading: " << (force?"true":"false") << endl;
1129 // now add the repos to the pool
1130 sat::Pool satpool( sat::Pool::instance() );
1131 Pathname rpmsolv( solvfilesPath() / "solv" );
1132 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
1134 // Providing an empty system repo, unload any old content
1135 Repository system( sat::Pool::instance().findSystemRepo() );
1137 if ( system && ! system.solvablesEmpty() )
1139 if ( newCache || force )
1141 system.eraseFromPool(); // invalidates system
1145 return; // nothing to do
1151 system = satpool.systemRepo();
1156 MIL << "adding " << rpmsolv << " to system" << endl;
1157 system.addSolv( rpmsolv );
1159 catch ( const Exception & exp )
1162 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1166 system.addSolv( rpmsolv );
1169 // (Re)Load the requested locales et al.
1170 // If the requested locales are empty, we leave the pool untouched
1171 // to avoid undoing changes the application applied. We expect this
1172 // to happen on a bare metal installation only. An already existing
1173 // target should be loaded before its settings are changed.
1175 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1176 if ( ! requestedLocales.empty() )
1178 satpool.setRequestedLocales( requestedLocales );
1182 SoftLocksFile::Data softLocks( _softLocksFile.data() );
1183 if ( ! softLocks.empty() )
1185 // Don't soft lock any installed item.
1186 for_( it, system.solvablesBegin(), system.solvablesEnd() )
1188 softLocks.erase( it->ident() );
1190 ResPool::instance().setAutoSoftLocks( softLocks );
1193 if ( ZConfig::instance().apply_locks_file() )
1195 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1196 if ( ! hardLocks.empty() )
1198 ResPool::instance().setHardLockQueries( hardLocks );
1202 // now that the target is loaded, we can cache the flavor
1203 createLastDistributionFlavorCache();
1205 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1208 ///////////////////////////////////////////////////////////////////
1212 ///////////////////////////////////////////////////////////////////
1213 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1215 // ----------------------------------------------------------------- //
1216 ZYppCommitPolicy policy_r( policy_rX );
1218 // Fake outstanding YCP fix: Honour restriction to media 1
1219 // at installation, but install all remaining packages if post-boot.
1220 if ( policy_r.restrictToMedia() > 1 )
1221 policy_r.allMedia();
1223 if ( policy_r.downloadMode() == DownloadDefault ) {
1224 if ( root() == "/" )
1225 policy_r.downloadMode(DownloadInHeaps);
1227 policy_r.downloadMode(DownloadAsNeeded);
1229 // DownloadOnly implies dry-run.
1230 else if ( policy_r.downloadMode() == DownloadOnly )
1231 policy_r.dryRun( true );
1232 // ----------------------------------------------------------------- //
1234 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1236 ///////////////////////////////////////////////////////////////////
1237 // Compute transaction:
1238 ///////////////////////////////////////////////////////////////////
1239 ZYppCommitResult result( root() );
1240 result.rTransaction() = pool_r.resolver().getTransaction();
1241 result.rTransaction().order();
1242 // steps: this is our todo-list
1243 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1244 if ( policy_r.restrictToMedia() )
1246 // Collect until the 1st package from an unwanted media occurs.
1247 // Further collection could violate install order.
1248 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1249 for_( it, result.transaction().begin(), result.transaction().end() )
1251 if ( makeResObject( *it )->mediaNr() > 1 )
1253 steps.push_back( *it );
1258 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1260 MIL << "Todo: " << result << endl;
1262 ///////////////////////////////////////////////////////////////////
1263 // Prepare execution of commit plugins:
1264 ///////////////////////////////////////////////////////////////////
1265 CommitPlugins commitPlugins;
1266 if ( root() == "/" && ! policy_r.dryRun() )
1268 Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
1269 commitPlugins.load( plugindir );
1271 if ( ! commitPlugins.empty() )
1272 commitPlugins.send( transactionPluginFrame( "COMMITBEGIN", steps ) );
1274 ///////////////////////////////////////////////////////////////////
1275 // Write out a testcase if we're in dist upgrade mode.
1276 ///////////////////////////////////////////////////////////////////
1277 if ( getZYpp()->resolver()->upgradeMode() )
1279 if ( ! policy_r.dryRun() )
1281 writeUpgradeTestcase();
1285 DBG << "dryRun: Not writing upgrade testcase." << endl;
1289 ///////////////////////////////////////////////////////////////////
1290 // Store non-package data:
1291 ///////////////////////////////////////////////////////////////////
1292 if ( ! policy_r.dryRun() )
1294 filesystem::assert_dir( home() );
1295 // requested locales
1296 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1299 SoftLocksFile::Data newdata;
1300 pool_r.getActiveSoftLocks( newdata );
1301 _softLocksFile.setData( newdata );
1304 if ( ZConfig::instance().apply_locks_file() )
1306 HardLocksFile::Data newdata;
1307 pool_r.getHardLockQueries( newdata );
1308 _hardLocksFile.setData( newdata );
1313 DBG << "dryRun: Not stroring non-package data." << endl;
1316 ///////////////////////////////////////////////////////////////////
1317 // First collect and display all messages
1318 // associated with patches to be installed.
1319 ///////////////////////////////////////////////////////////////////
1320 if ( ! policy_r.dryRun() )
1322 for_( it, steps.begin(), steps.end() )
1324 if ( ! it->satSolvable().isKind<Patch>() )
1328 if ( ! pi.status().isToBeInstalled() )
1331 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1332 if ( ! patch ||patch->message().empty() )
1335 MIL << "Show message for " << patch << endl;
1336 callback::SendReport<target::PatchMessageReport> report;
1337 if ( ! report->show( patch ) )
1339 WAR << "commit aborted by the user" << endl;
1340 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1346 DBG << "dryRun: Not checking patch messages." << endl;
1349 ///////////////////////////////////////////////////////////////////
1350 // Remove/install packages.
1351 ///////////////////////////////////////////////////////////////////
1352 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1353 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1355 // Prepare the package cache. Pass all items requiring download.
1356 repo::RepoMediaAccess access;
1357 RepoProvidePackage repoProvidePackage( access, pool_r );
1358 CommitPackageCache packageCache( root(), repoProvidePackage );
1359 packageCache.setCommitList( steps.begin(), steps.end() );
1362 if ( policy_r.downloadMode() != DownloadAsNeeded )
1364 // Preload the cache. Until now this means pre-loading all packages.
1365 // Once DownloadInHeaps is fully implemented, this will change and
1366 // we may actually have more than one heap.
1367 for_( it, steps.begin(), steps.end() )
1369 switch ( it->stepType() )
1371 case sat::Transaction::TRANSACTION_INSTALL:
1372 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1373 // proceed: only install actionas may require download.
1377 // next: no download for or non-packages and delete actions.
1383 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1385 ManagedFile localfile;
1388 // TODO: unify packageCache.get for Package and SrcPackage
1389 if ( pi->isKind<Package>() )
1391 localfile = packageCache.get( pi );
1393 else if ( pi->isKind<SrcPackage>() )
1395 repo::RepoMediaAccess access;
1396 repo::SrcPackageProvider prov( access );
1397 localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1401 INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1404 localfile.resetDispose(); // keep the package file in the cache
1406 catch ( const AbortRequestException & exp )
1408 it->stepStage( sat::Transaction::STEP_ERROR );
1410 WAR << "commit cache preload aborted by the user" << endl;
1411 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1414 catch ( const SkipRequestException & exp )
1417 it->stepStage( sat::Transaction::STEP_ERROR );
1419 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1422 catch ( const Exception & exp )
1424 // bnc #395704: missing catch causes abort.
1425 // TODO see if packageCache fails to handle errors correctly.
1427 it->stepStage( sat::Transaction::STEP_ERROR );
1429 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1438 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1442 if ( ! policy_r.dryRun() )
1444 // if cache is preloaded, check for file conflicts
1445 commitFindFileConflicts( policy_r, result );
1446 commit( policy_r, packageCache, result );
1450 DBG << "dryRun/downloadOnly: Not installing/deleting anything." << endl;
1456 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1459 ///////////////////////////////////////////////////////////////////
1460 // Send result to commit plugins:
1461 ///////////////////////////////////////////////////////////////////
1462 if ( ! commitPlugins.empty() )
1463 commitPlugins.send( transactionPluginFrame( "COMMITEND", steps ) );
1465 ///////////////////////////////////////////////////////////////////
1466 // Try to rebuild solv file while rpm database is still in cache
1467 ///////////////////////////////////////////////////////////////////
1468 if ( ! policy_r.dryRun() )
1473 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1477 ///////////////////////////////////////////////////////////////////
1481 ///////////////////////////////////////////////////////////////////
1482 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1483 CommitPackageCache & packageCache_r,
1484 ZYppCommitResult & result_r )
1486 // steps: this is our todo-list
1487 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1488 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1491 RpmPostTransCollector postTransCollector( _root );
1492 std::vector<sat::Solvable> successfullyInstalledPackages;
1493 TargetImpl::PoolItemList remaining;
1495 for_( step, steps.begin(), steps.end() )
1497 PoolItem citem( *step );
1498 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1500 if ( citem->isKind<Package>() )
1502 // for packages this means being obsoleted (by rpm)
1503 // thius no additional action is needed.
1504 step->stepStage( sat::Transaction::STEP_DONE );
1509 if ( citem->isKind<Package>() )
1511 Package::constPtr p = citem->asKind<Package>();
1512 if ( citem.status().isToBeInstalled() )
1514 ManagedFile localfile;
1517 localfile = packageCache_r.get( citem );
1519 catch ( const AbortRequestException &e )
1521 WAR << "commit aborted by the user" << endl;
1523 step->stepStage( sat::Transaction::STEP_ERROR );
1526 catch ( const SkipRequestException &e )
1529 WAR << "Skipping package " << p << " in commit" << endl;
1530 step->stepStage( sat::Transaction::STEP_ERROR );
1533 catch ( const Exception &e )
1535 // bnc #395704: missing catch causes abort.
1536 // TODO see if packageCache fails to handle errors correctly.
1538 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1539 step->stepStage( sat::Transaction::STEP_ERROR );
1543 #warning Exception handling
1544 // create a installation progress report proxy
1545 RpmInstallPackageReceiver progress( citem.resolvable() );
1546 progress.connect(); // disconnected on destruction.
1548 bool success = false;
1549 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1550 // Why force and nodeps?
1552 // Because zypp builds the transaction and the resolver asserts that
1553 // everything is fine.
1554 // We use rpm just to unpack and register the package in the database.
1555 // We do this step by step, so rpm is not aware of the bigger context.
1556 // So we turn off rpms internal checks, because we do it inside zypp.
1557 flags |= rpm::RPMINST_NODEPS;
1558 flags |= rpm::RPMINST_FORCE;
1560 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1561 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1562 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1563 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1567 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1568 if ( postTransCollector.collectScriptFromPackage( localfile ) )
1569 flags |= rpm::RPMINST_NOPOSTTRANS;
1570 rpm().installPackage( localfile, flags );
1571 HistoryLog().install(citem);
1573 if ( progress.aborted() )
1575 WAR << "commit aborted by the user" << endl;
1576 localfile.resetDispose(); // keep the package file in the cache
1578 step->stepStage( sat::Transaction::STEP_ERROR );
1584 step->stepStage( sat::Transaction::STEP_DONE );
1587 catch ( Exception & excpt_r )
1589 ZYPP_CAUGHT(excpt_r);
1590 localfile.resetDispose(); // keep the package file in the cache
1592 if ( policy_r.dryRun() )
1594 WAR << "dry run failed" << endl;
1595 step->stepStage( sat::Transaction::STEP_ERROR );
1599 if ( progress.aborted() )
1601 WAR << "commit aborted by the user" << endl;
1606 WAR << "Install failed" << endl;
1608 step->stepStage( sat::Transaction::STEP_ERROR );
1612 if ( success && !policy_r.dryRun() )
1614 citem.status().resetTransact( ResStatus::USER );
1615 successfullyInstalledPackages.push_back( citem.satSolvable() );
1616 step->stepStage( sat::Transaction::STEP_DONE );
1621 RpmRemovePackageReceiver progress( citem.resolvable() );
1622 progress.connect(); // disconnected on destruction.
1624 bool success = false;
1625 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1626 flags |= rpm::RPMINST_NODEPS;
1627 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1630 rpm().removePackage( p, flags );
1631 HistoryLog().remove(citem);
1633 if ( progress.aborted() )
1635 WAR << "commit aborted by the user" << endl;
1637 step->stepStage( sat::Transaction::STEP_ERROR );
1643 step->stepStage( sat::Transaction::STEP_DONE );
1646 catch (Exception & excpt_r)
1648 ZYPP_CAUGHT( excpt_r );
1649 if ( progress.aborted() )
1651 WAR << "commit aborted by the user" << endl;
1653 step->stepStage( sat::Transaction::STEP_ERROR );
1657 WAR << "removal of " << p << " failed";
1658 step->stepStage( sat::Transaction::STEP_ERROR );
1660 if ( success && !policy_r.dryRun() )
1662 citem.status().resetTransact( ResStatus::USER );
1663 step->stepStage( sat::Transaction::STEP_DONE );
1667 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1669 // Status is changed as the buddy package buddy
1670 // gets installed/deleted. Handle non-buddies only.
1671 if ( ! citem.buddy() )
1673 if ( citem->isKind<Product>() )
1675 Product::constPtr p = citem->asKind<Product>();
1676 if ( citem.status().isToBeInstalled() )
1678 ERR << "Can't install orphan product without release-package! " << citem << endl;
1682 // Deleting the corresponding product entry is all we con do.
1683 // So the product will no longer be visible as installed.
1684 std::string referenceFilename( p->referenceFilename() );
1685 if ( referenceFilename.empty() )
1687 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1691 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1692 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1694 ERR << "Delete orphan product failed: " << referenceFile << endl;
1699 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1701 // SrcPackage is install-only
1702 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1703 installSrcPackage( p );
1706 citem.status().resetTransact( ResStatus::USER );
1707 step->stepStage( sat::Transaction::STEP_DONE );
1710 } // other resolvables
1714 // process all remembered posttrans scripts.
1716 postTransCollector.executeScripts();
1718 postTransCollector.discardScripts();
1720 // Check presence of update scripts/messages. If aborting,
1721 // at least log omitted scripts.
1722 if ( ! successfullyInstalledPackages.empty() )
1724 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1725 successfullyInstalledPackages, abort ) )
1727 WAR << "Commit aborted by the user" << endl;
1730 // send messages after scripts in case some script generates output,
1731 // that should be kept in t %ghost message file.
1732 RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1733 successfullyInstalledPackages,
1739 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1743 ///////////////////////////////////////////////////////////////////
1745 rpm::RpmDb & TargetImpl::rpm()
1750 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1752 return _rpm.hasFile(path_str, name_str);
1756 Date TargetImpl::timestamp() const
1758 return _rpm.timestamp();
1761 ///////////////////////////////////////////////////////////////////
1764 parser::ProductFileData baseproductdata( const Pathname & root_r )
1766 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1767 if ( baseproduct.isFile() )
1771 return parser::ProductFileReader::scanFile( baseproduct.path() );
1773 catch ( const Exception & excpt )
1775 ZYPP_CAUGHT( excpt );
1778 return parser::ProductFileData();
1781 inline Pathname staticGuessRoot( const Pathname & root_r )
1783 if ( root_r.empty() )
1785 // empty root: use existing Target or assume "/"
1786 Pathname ret ( ZConfig::instance().systemRoot() );
1788 return Pathname("/");
1794 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1796 std::ifstream idfile( file_r.c_str() );
1797 for( iostr::EachLine in( idfile ); in; in.next() )
1799 std::string line( str::trim( *in ) );
1800 if ( ! line.empty() )
1803 return std::string();
1806 ///////////////////////////////////////////////////////////////////
1808 Product::constPtr TargetImpl::baseProduct() const
1810 ResPool pool(ResPool::instance());
1811 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1813 Product::constPtr p = (*it)->asKind<Product>();
1814 if ( p->isTargetDistribution() )
1820 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1822 const Pathname needroot( staticGuessRoot(root_r) );
1823 const Target_constPtr target( getZYpp()->getTarget() );
1824 if ( target && target->root() == needroot )
1825 return target->requestedLocales();
1826 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1829 std::string TargetImpl::targetDistribution() const
1830 { return baseproductdata( _root ).registerTarget(); }
1832 std::string TargetImpl::targetDistribution( const Pathname & root_r )
1833 { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1835 std::string TargetImpl::targetDistributionRelease() const
1836 { return baseproductdata( _root ).registerRelease(); }
1838 std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1839 { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1841 Target::DistributionLabel TargetImpl::distributionLabel() const
1843 Target::DistributionLabel ret;
1844 parser::ProductFileData pdata( baseproductdata( _root ) );
1845 ret.shortName = pdata.shortName();
1846 ret.summary = pdata.summary();
1850 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1852 Target::DistributionLabel ret;
1853 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1854 ret.shortName = pdata.shortName();
1855 ret.summary = pdata.summary();
1859 std::string TargetImpl::distributionVersion() const
1861 if ( _distributionVersion.empty() )
1863 _distributionVersion = TargetImpl::distributionVersion(root());
1864 if ( !_distributionVersion.empty() )
1865 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1867 return _distributionVersion;
1870 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1872 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1873 if ( distributionVersion.empty() )
1875 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1876 // On RHEL, Fedora and others the "product version" is determined by the first package
1877 // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1878 // with the $distroverpkg variable.
1879 scoped_ptr<rpm::RpmDb> tmprpmdb;
1880 if ( ZConfig::instance().systemRoot() == Pathname() )
1884 tmprpmdb.reset( new rpm::RpmDb );
1885 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1892 rpm::librpmDb::db_const_iterator it;
1893 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1894 distributionVersion = it->tag_version();
1896 return distributionVersion;
1900 std::string TargetImpl::distributionFlavor() const
1902 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1905 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1907 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1910 ///////////////////////////////////////////////////////////////////
1912 std::string TargetImpl::anonymousUniqueId() const
1914 return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1917 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1919 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1922 ///////////////////////////////////////////////////////////////////
1924 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1926 // provide on local disk
1927 ManagedFile localfile = provideSrcPackage(srcPackage_r);
1929 rpm().installPackage ( localfile );
1932 ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1934 // provide on local disk
1935 repo::RepoMediaAccess access_r;
1936 repo::SrcPackageProvider prov( access_r );
1937 return prov.provideSrcPackage( srcPackage_r );
1939 ////////////////////////////////////////////////////////////////
1940 } // namespace target
1941 ///////////////////////////////////////////////////////////////////
1942 /////////////////////////////////////////////////////////////////
1944 ///////////////////////////////////////////////////////////////////