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"
51 #include "zypp/repo/SrcPackageProvider.h"
53 #include "zypp/sat/Pool.h"
54 #include "zypp/sat/Transaction.h"
56 #include "zypp/PluginScript.h"
60 ///////////////////////////////////////////////////////////////////
62 { /////////////////////////////////////////////////////////////////
63 ///////////////////////////////////////////////////////////////////
66 // Lazy via template specialisation / should switch to overloading
69 inline std::string toJSON( const ZYppCommitResult::TransactionStepList & steps_r )
71 using sat::Transaction;
74 for ( const Transaction::Step & step : steps_r )
75 // ignore implicit deletes due to obsoletes and non-package actions
76 if ( step.stepType() != Transaction::TRANSACTION_IGNORE )
82 /** See \ref commitbegin on page \ref plugin-commit for the specs. */
84 inline std::string toJSON( const sat::Transaction::Step & step_r )
86 static const std::string strType( "type" );
87 static const std::string strStage( "stage" );
88 static const std::string strSolvable( "solvable" );
90 static const std::string strTypeDel( "-" );
91 static const std::string strTypeIns( "+" );
92 static const std::string strTypeMul( "M" );
94 static const std::string strStageDone( "ok" );
95 static const std::string strStageFailed( "err" );
97 static const std::string strSolvableN( "n" );
98 static const std::string strSolvableE( "e" );
99 static const std::string strSolvableV( "v" );
100 static const std::string strSolvableR( "r" );
101 static const std::string strSolvableA( "a" );
103 using sat::Transaction;
106 switch ( step_r.stepType() )
108 case Transaction::TRANSACTION_IGNORE: /*empty*/ break;
109 case Transaction::TRANSACTION_ERASE: ret.add( strType, strTypeDel ); break;
110 case Transaction::TRANSACTION_INSTALL: ret.add( strType, strTypeIns ); break;
111 case Transaction::TRANSACTION_MULTIINSTALL: ret.add( strType, strTypeMul ); break;
114 switch ( step_r.stepStage() )
116 case Transaction::STEP_TODO: /*empty*/ break;
117 case Transaction::STEP_DONE: ret.add( strStage, strStageDone ); break;
118 case Transaction::STEP_ERROR: ret.add( strStage, strStageFailed ); break;
125 if ( sat::Solvable solv = step_r.satSolvable() )
127 ident = solv.ident();
133 // deleted package; post mortem data stored in Transaction::Step
134 ident = step_r.ident();
135 ed = step_r.edition();
136 arch = step_r.arch();
140 { strSolvableN, ident.asString() },
141 { strSolvableV, ed.version() },
142 { strSolvableR, ed.release() },
143 { strSolvableA, arch.asString() }
145 if ( Edition::epoch_t epoch = ed.epoch() )
146 s.add( strSolvableE, epoch );
148 ret.add( strSolvable, s );
154 ///////////////////////////////////////////////////////////////////
156 ///////////////////////////////////////////////////////////////////
159 ///////////////////////////////////////////////////////////////////
162 SolvIdentFile::Data getUserInstalledFromHistory( const Pathname & historyFile_r )
164 SolvIdentFile::Data onSystemByUserList;
165 // go and parse it: 'who' must constain an '@', then it was installed by user request.
166 // 2009-09-29 07:25:19|install|lirc-remotes|0.8.5-3.2|x86_64|root@opensuse|InstallationImage|a204211eb0...
167 std::ifstream infile( historyFile_r.c_str() );
168 for( iostr::EachLine in( infile ); in; in.next() )
170 const char * ch( (*in).c_str() );
172 if ( *ch < '1' || '9' < *ch )
174 const char * sep1 = ::strchr( ch, '|' ); // | after date
178 // if logs an install or delete
179 bool installs = true;
180 if ( ::strncmp( sep1, "install|", 8 ) )
182 if ( ::strncmp( sep1, "remove |", 8 ) )
183 continue; // no install and no remove
185 installs = false; // remove
187 sep1 += 8; // | after what
188 // get the package name
189 const char * sep2 = ::strchr( sep1, '|' ); // | after name
190 if ( !sep2 || sep1 == sep2 )
192 (*in)[sep2-ch] = '\0';
193 IdString pkg( sep1 );
194 // we're done, if a delete
197 onSystemByUserList.erase( pkg );
200 // now guess whether user installed or not (3rd next field contains 'user@host')
201 if ( (sep1 = ::strchr( sep2+1, '|' )) // | after version
202 && (sep1 = ::strchr( sep1+1, '|' )) // | after arch
203 && (sep2 = ::strchr( sep1+1, '|' )) ) // | after who
205 (*in)[sep2-ch] = '\0';
206 if ( ::strchr( sep1+1, '@' ) )
209 onSystemByUserList.insert( pkg );
214 MIL << "onSystemByUserList found: " << onSystemByUserList.size() << endl;
215 return onSystemByUserList;
218 ///////////////////////////////////////////////////////////////////
220 /** Helper for commit plugin execution.
223 class CommitPlugins : private base::NonCopyable
226 /** Default ctor: Empty plugin list */
230 /** Dtor: Send PLUGINEND message and close plugins. */
233 if ( ! _scripts.empty() )
234 send( PluginFrame( "PLUGINEND" ) );
235 // ~PluginScript will disconnect all remaining plugins!
238 /** Whether no plugins are waiting */
240 { return _scripts.empty(); }
243 /** Send \ref PluginFrame to all open plugins.
244 * Failed plugins are removed from the execution list.
246 void send( const PluginFrame & frame_r )
248 DBG << "+++++++++++++++ send " << frame_r << endl;
249 for ( auto it = _scripts.begin(); it != _scripts.end(); )
251 doSend( *it, frame_r );
255 it = _scripts.erase( it );
257 DBG << "--------------- send " << frame_r << endl;
260 /** Find and launch plugins sending PLUGINSTART message.
262 * If \a path_r is a directory all executable files whithin are
263 * expected to be plugins. Otherwise \a path_r must point to an
266 void load( const Pathname & path_r )
268 PathInfo pi( path_r );
269 DBG << "+++++++++++++++ load " << pi << endl;
272 std::list<Pathname> entries;
273 if ( filesystem::readdir( entries, pi.path(), false ) != 0 )
275 WAR << "Plugin dir is not readable: " << pi << endl;
278 for_( it, entries.begin(), entries.end() )
281 if ( pii.isFile() && pii.userMayRX() )
285 else if ( pi.isFile() )
287 if ( pi.userMayRX() )
290 WAR << "Plugin file is not executable: " << pi << endl;
294 WAR << "Plugin path is neither dir nor file: " << pi << endl;
296 DBG << "--------------- load " << pi << endl;
300 /** Send \ref PluginFrame and expect valid answer (ACK|_ENOMETHOD).
301 * Upon invalid answer or error, close the plugin. and remove it from the
303 * \returns the received \ref PluginFrame (empty Frame upon Exception)
305 PluginFrame doSend( PluginScript & script_r, const PluginFrame & frame_r )
310 script_r.send( frame_r );
311 ret = script_r.receive();
313 catch( const zypp::Exception & e )
316 if ( ! ( ret.isAckCommand() || ret.isEnomethodCommand() ) )
318 WAR << "Bad plugin response from " << script_r << endl;
319 WAR << dump(ret) << endl;
326 /** Launch a plugin sending PLUGINSTART message. */
327 void doLoad( const PathInfo & pi_r )
329 MIL << "Load plugin: " << pi_r << endl;
331 PluginScript plugin( pi_r.path() );
334 PluginFrame frame( "PLUGINBEGIN" );
335 if ( ZConfig::instance().hasUserData() )
336 frame.setHeader( "userdata", ZConfig::instance().userData() );
338 doSend( plugin, frame ); // closes on error
339 if ( plugin.isOpen() )
340 _scripts.push_back( plugin );
342 catch( const zypp::Exception & e )
344 WAR << "Failed to load plugin " << pi_r << endl;
349 std::list<PluginScript> _scripts;
352 void testCommitPlugins( const Pathname & path_r ) // for testing only
354 USR << "+++++" << endl;
358 USR << "=====" << endl;
360 USR << "-----" << endl;
363 ///////////////////////////////////////////////////////////////////
366 inline PluginFrame transactionPluginFrame( const std::string & command_r, ZYppCommitResult::TransactionStepList & steps_r )
368 return PluginFrame( command_r, json::Object {
369 { "TransactionStepList", steps_r }
373 ///////////////////////////////////////////////////////////////////
375 /** \internal Manage writing a new testcase when doing an upgrade. */
376 void writeUpgradeTestcase()
378 unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
379 MIL << "Testcases to keep: " << toKeep << endl;
382 Target_Ptr target( getZYpp()->getTarget() );
385 WAR << "No Target no Testcase!" << endl;
389 std::string stem( "updateTestcase" );
390 Pathname dir( target->assertRootPrefix("/var/log/") );
391 Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
394 std::list<std::string> content;
395 filesystem::readdir( content, dir, /*dots*/false );
396 std::set<std::string> cases;
397 for_( c, content.begin(), content.end() )
399 if ( str::startsWith( *c, stem ) )
402 if ( cases.size() >= toKeep )
404 unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
405 for_( c, cases.begin(), cases.end() )
407 filesystem::recursive_rmdir( dir/(*c) );
414 MIL << "Write new testcase " << next << endl;
415 getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
418 ///////////////////////////////////////////////////////////////////
420 { /////////////////////////////////////////////////////////////////
422 /** Execute script and report against report_r.
423 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
424 * execution was successfull (<tt>first = true</tt>), or the desired
425 * \c PatchScriptReport::Action in case execution failed
426 * (<tt>first = false</tt>).
428 * \note The packager is responsible for setting the correct permissions
429 * of the script. If the script is not executable it is reported as an
430 * error. We must not modify the permessions.
432 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
433 const Pathname & script_r,
434 callback::SendReport<PatchScriptReport> & report_r )
436 MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
438 HistoryLog historylog;
439 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
440 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
442 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
444 historylog.comment(output);
445 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
447 WAR << "User request to abort script " << script_r << endl;
449 // the rest is handled by exit code evaluation
450 // in case the script has meanwhile finished.
454 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
456 if ( prog.close() != 0 )
458 ret.second = report_r->problem( prog.execError() );
459 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
460 std::ostringstream sstr;
461 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
462 historylog.comment(sstr.str(), /*timestamp*/true);
471 /** Execute script and report against report_r.
472 * Return \c false if user requested \c ABORT.
474 bool executeScript( const Pathname & root_r,
475 const Pathname & script_r,
476 callback::SendReport<PatchScriptReport> & report_r )
478 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
481 action = doExecuteScript( root_r, script_r, report_r );
483 return true; // success
485 switch ( action.second )
487 case PatchScriptReport::ABORT:
488 WAR << "User request to abort at script " << script_r << endl;
489 return false; // requested abort.
492 case PatchScriptReport::IGNORE:
493 WAR << "User request to skip script " << script_r << endl;
494 return true; // requested skip.
497 case PatchScriptReport::RETRY:
500 } while ( action.second == PatchScriptReport::RETRY );
502 // THIS is not intended to be reached:
503 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
504 return false; // abort.
507 /** Look for update scripts named 'name-version-release-*' and
508 * execute them. Return \c false if \c ABORT was requested.
510 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
512 bool RunUpdateScripts( const Pathname & root_r,
513 const Pathname & scriptsPath_r,
514 const std::vector<sat::Solvable> & checkPackages_r,
517 if ( checkPackages_r.empty() )
518 return true; // no installed packages to check
520 MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
521 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
522 if ( ! PathInfo( scriptsDir ).isDir() )
523 return true; // no script dir
525 std::list<std::string> scripts;
526 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
527 if ( scripts.empty() )
528 return true; // no scripts in script dir
530 // Now collect and execute all matching scripts.
531 // On ABORT: at least log all outstanding scripts.
532 // - "name-version-release"
533 // - "name-version-release-*"
535 std::map<std::string, Pathname> unify; // scripts <md5,path>
536 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
538 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
539 for_( sit, scripts.begin(), scripts.end() )
541 if ( ! str::hasPrefix( *sit, prefix ) )
544 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
545 continue; // if not exact match it had to continue with '-'
547 PathInfo script( scriptsDir / *sit );
548 Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
549 std::string unifytag; // must not stay empty
551 if ( script.isFile() )
553 // Assert it's set executable, unify by md5sum.
554 filesystem::addmod( script.path(), 0500 );
555 unifytag = filesystem::md5sum( script.path() );
557 else if ( ! script.isExist() )
559 // Might be a dangling symlink, might be ok if we are in
560 // instsys (absolute symlink within the system below /mnt).
561 // readlink will tell....
562 unifytag = filesystem::readlink( script.path() ).asString();
565 if ( unifytag.empty() )
569 if ( unify[unifytag].empty() )
571 unify[unifytag] = localPath;
575 // translators: We may find the same script content in files with different names.
576 // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
577 // message for a log file. Preferably start translation with "%s"
578 std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
579 MIL << "Skip update script: " << msg << endl;
580 HistoryLog().comment( msg, /*timestamp*/true );
584 if ( abort || aborting_r )
586 WAR << "Aborting: Skip update script " << *sit << endl;
587 HistoryLog().comment(
588 localPath.asString() + _(" execution skipped while aborting"),
593 MIL << "Found update script " << *sit << endl;
594 callback::SendReport<PatchScriptReport> report;
595 report->start( make<Package>( *it ), script.path() );
597 if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
598 abort = true; // requested abort.
605 ///////////////////////////////////////////////////////////////////
607 ///////////////////////////////////////////////////////////////////
609 inline void copyTo( std::ostream & out_r, const Pathname & file_r )
611 std::ifstream infile( file_r.c_str() );
612 for( iostr::EachLine in( infile ); in; in.next() )
614 out_r << *in << endl;
618 inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
620 std::string ret( cmd_r );
621 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
622 SUBST_IF( "%p", notification_r.solvable().asString() );
623 SUBST_IF( "%P", notification_r.file().asString() );
628 void sendNotification( const Pathname & root_r,
629 const UpdateNotifications & notifications_r )
631 if ( notifications_r.empty() )
634 std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
635 MIL << "Notification command is '" << cmdspec << "'" << endl;
636 if ( cmdspec.empty() )
639 std::string::size_type pos( cmdspec.find( '|' ) );
640 if ( pos == std::string::npos )
642 ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
643 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
647 std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
648 std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
650 enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
651 Format format = UNKNOWN;
652 if ( formatStr == "none" )
654 else if ( formatStr == "single" )
656 else if ( formatStr == "digest" )
658 else if ( formatStr == "bulk" )
662 ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
663 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
667 // Take care: commands are ececuted chroot(root_r). The message file
668 // pathnames in notifications_r are local to root_r. For physical access
669 // to the file they need to be prefixed.
671 if ( format == NONE || format == SINGLE )
673 for_( it, notifications_r.begin(), notifications_r.end() )
675 std::vector<std::string> command;
676 if ( format == SINGLE )
677 command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
678 str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
680 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
681 if ( true ) // Wait for feedback
683 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
687 int ret = prog.close();
690 ERR << "Notification command returned with error (" << ret << ")." << endl;
691 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
697 else if ( format == DIGEST || format == BULK )
699 filesystem::TmpFile tmpfile;
700 ofstream out( tmpfile.path().c_str() );
701 for_( it, notifications_r.begin(), notifications_r.end() )
703 if ( format == DIGEST )
705 out << it->file() << endl;
707 else if ( format == BULK )
709 copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
713 std::vector<std::string> command;
714 command.push_back( "<"+tmpfile.path().asString() ); // redirect input
715 str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
717 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
718 if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
720 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
724 int ret = prog.close();
727 ERR << "Notification command returned with error (" << ret << ")." << endl;
728 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
735 INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
736 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
742 /** Look for update messages named 'name-version-release-*' and
743 * send notification according to \ref ZConfig::updateMessagesNotify.
745 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
747 void RunUpdateMessages( const Pathname & root_r,
748 const Pathname & messagesPath_r,
749 const std::vector<sat::Solvable> & checkPackages_r,
750 ZYppCommitResult & result_r )
752 if ( checkPackages_r.empty() )
753 return; // no installed packages to check
755 MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
756 Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
757 if ( ! PathInfo( messagesDir ).isDir() )
758 return; // no messages dir
760 std::list<std::string> messages;
761 filesystem::readdir( messages, messagesDir, /*dots*/false );
762 if ( messages.empty() )
763 return; // no messages in message dir
765 // Now collect all matching messages in result and send them
766 // - "name-version-release"
767 // - "name-version-release-*"
768 HistoryLog historylog;
769 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
771 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
772 for_( sit, messages.begin(), messages.end() )
774 if ( ! str::hasPrefix( *sit, prefix ) )
777 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
778 continue; // if not exact match it had to continue with '-'
780 PathInfo message( messagesDir / *sit );
781 if ( ! message.isFile() || message.size() == 0 )
784 MIL << "Found update message " << *sit << endl;
785 Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
786 result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
787 historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
790 sendNotification( root_r, result_r.updateMessages() );
793 /////////////////////////////////////////////////////////////////
795 ///////////////////////////////////////////////////////////////////
797 void XRunUpdateMessages( const Pathname & root_r,
798 const Pathname & messagesPath_r,
799 const std::vector<sat::Solvable> & checkPackages_r,
800 ZYppCommitResult & result_r )
801 { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
803 ///////////////////////////////////////////////////////////////////
805 IMPL_PTR_TYPE(TargetImpl);
807 TargetImpl_Ptr TargetImpl::_nullimpl;
809 /** Null implementation */
810 TargetImpl_Ptr TargetImpl::nullimpl()
813 _nullimpl = new TargetImpl;
817 ///////////////////////////////////////////////////////////////////
819 // METHOD NAME : TargetImpl::TargetImpl
820 // METHOD TYPE : Ctor
822 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
824 , _requestedLocalesFile( home() / "RequestedLocales" )
825 , _autoInstalledFile( home() / "AutoInstalled" )
826 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
828 _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
830 HistoryLog::setRoot(_root);
834 MIL << "Initialized target on " << _root << endl;
838 * generates a random id using uuidgen
840 static std::string generateRandomId()
842 std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
843 return iostr::getline( uuidprovider );
847 * updates the content of \p filename
848 * if \p condition is true, setting the content
849 * the the value returned by \p value
851 void updateFileContent( const Pathname &filename,
852 boost::function<bool ()> condition,
853 boost::function<string ()> value )
855 string val = value();
856 // if the value is empty, then just dont
857 // do anything, regardless of the condition
863 MIL << "updating '" << filename << "' content." << endl;
865 // if the file does not exist we need to generate the uuid file
867 std::ofstream filestr;
868 // make sure the path exists
869 filesystem::assert_dir( filename.dirname() );
870 filestr.open( filename.c_str() );
872 if ( filestr.good() )
879 // FIXME, should we ignore the error?
880 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
885 /** helper functor */
886 static bool fileMissing( const Pathname &pathname )
888 return ! PathInfo(pathname).isExist();
891 void TargetImpl::createAnonymousId() const
894 // create the anonymous unique id
895 // this value is used for statistics
896 Pathname idpath( home() / "AnonymousUniqueId");
900 updateFileContent( idpath,
901 boost::bind(fileMissing, idpath),
904 catch ( const Exception &e )
906 WAR << "Can't create anonymous id file" << endl;
911 void TargetImpl::createLastDistributionFlavorCache() const
913 // create the anonymous unique id
914 // this value is used for statistics
915 Pathname flavorpath( home() / "LastDistributionFlavor");
917 // is there a product
918 Product::constPtr p = baseProduct();
921 WAR << "No base product, I won't create flavor cache" << endl;
925 string flavor = p->flavor();
930 updateFileContent( flavorpath,
931 // only if flavor is not empty
932 functor::Constant<bool>( ! flavor.empty() ),
933 functor::Constant<string>(flavor) );
935 catch ( const Exception &e )
937 WAR << "Can't create flavor cache" << endl;
942 ///////////////////////////////////////////////////////////////////
944 // METHOD NAME : TargetImpl::~TargetImpl
945 // METHOD TYPE : Dtor
947 TargetImpl::~TargetImpl()
949 _rpm.closeDatabase();
950 MIL << "Targets closed" << endl;
953 ///////////////////////////////////////////////////////////////////
955 // solv file handling
957 ///////////////////////////////////////////////////////////////////
959 Pathname TargetImpl::defaultSolvfilesPath() const
961 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
964 void TargetImpl::clearCache()
966 Pathname base = solvfilesPath();
967 filesystem::recursive_rmdir( base );
970 bool TargetImpl::buildCache()
972 Pathname base = solvfilesPath();
973 Pathname rpmsolv = base/"solv";
974 Pathname rpmsolvcookie = base/"cookie";
976 bool build_rpm_solv = true;
977 // lets see if the rpm solv cache exists
979 RepoStatus rpmstatus( RepoStatus(_root/"var/lib/rpm/Name") && RepoStatus(_root/"etc/products.d") );
981 bool solvexisted = PathInfo(rpmsolv).isExist();
984 // see the status of the cache
985 PathInfo cookie( rpmsolvcookie );
986 MIL << "Read cookie: " << cookie << endl;
987 if ( cookie.isExist() )
989 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
990 // now compare it with the rpm database
991 if ( status == rpmstatus )
992 build_rpm_solv = false;
993 MIL << "Read cookie: " << rpmsolvcookie << " says: "
994 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
998 if ( build_rpm_solv )
1000 // if the solvfile dir does not exist yet, we better create it
1001 filesystem::assert_dir( base );
1003 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
1005 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
1008 // Can't create temporary solv file, usually due to insufficient permission
1009 // (user query while @System solv needs refresh). If so, try switching
1010 // to a location within zypps temp. space (will be cleaned at application end).
1012 bool switchingToTmpSolvfile = false;
1013 Exception ex("Failed to cache rpm database.");
1014 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
1016 if ( ! solvfilesPathIsTemp() )
1018 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
1019 rpmsolv = base/"solv";
1020 rpmsolvcookie = base/"cookie";
1022 filesystem::assert_dir( base );
1023 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
1027 WAR << "Using a temporary solv file at " << base << endl;
1028 switchingToTmpSolvfile = true;
1029 _tmpSolvfilesPath = base;
1033 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
1037 if ( ! switchingToTmpSolvfile )
1043 // Take care we unlink the solvfile on exception
1044 ManagedFile guard( base, filesystem::recursive_rmdir );
1046 ExternalProgram::Arguments cmd;
1047 cmd.push_back( "rpmdb2solv" );
1048 if ( ! _root.empty() ) {
1049 cmd.push_back( "-r" );
1050 cmd.push_back( _root.asString() );
1052 cmd.push_back( "-X" ); // autogenerate pattern/product/... from -package
1053 cmd.push_back( "-A" ); // autogenerate application pseudo packages
1054 cmd.push_back( "-p" );
1055 cmd.push_back( Pathname::assertprefix( _root, "/etc/products.d" ).asString() );
1057 if ( ! oldSolvFile.empty() )
1058 cmd.push_back( oldSolvFile.asString() );
1060 cmd.push_back( "-o" );
1061 cmd.push_back( tmpsolv.path().asString() );
1063 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
1064 std::string errdetail;
1066 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1067 WAR << " " << output;
1068 if ( errdetail.empty() ) {
1069 errdetail = prog.command();
1072 errdetail += output;
1075 int ret = prog.close();
1078 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
1079 ex.remember( errdetail );
1083 ret = filesystem::rename( tmpsolv, rpmsolv );
1085 ZYPP_THROW(Exception("Failed to move cache to final destination"));
1086 // if this fails, don't bother throwing exceptions
1087 filesystem::chmod( rpmsolv, 0644 );
1089 rpmstatus.saveToCookieFile(rpmsolvcookie);
1092 guard.resetDispose();
1093 sat::updateSolvFileIndex( rpmsolv ); // content digest for zypper bash completion
1095 // Finally send notification to plugins
1096 // NOTE: quick hack looking for spacewalk plugin only
1098 Pathname script( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"system/spacewalk" ) );
1099 if ( PathInfo( script ).isX() )
1101 PluginScript spacewalk( script );
1104 PluginFrame notify( "PACKAGESETCHANGED" );
1105 spacewalk.send( notify );
1107 PluginFrame ret( spacewalk.receive() );
1109 if ( ret.command() == "ERROR" )
1110 ret.writeTo( WAR ) << endl;
1112 catch ( const Exception & excpt )
1114 WAR << excpt.asUserHistory() << endl;
1120 // On the fly add missing solv.idx files for bash completion.
1121 if ( ! PathInfo(base/"solv.idx").isExist() )
1122 sat::updateSolvFileIndex( rpmsolv );
1124 return build_rpm_solv;
1127 void TargetImpl::reload()
1132 void TargetImpl::unload()
1134 Repository system( sat::Pool::instance().findSystemRepo() );
1136 system.eraseFromPool();
1139 void TargetImpl::load( bool force )
1141 bool newCache = buildCache();
1142 MIL << "New cache built: " << (newCache?"true":"false") <<
1143 ", force loading: " << (force?"true":"false") << endl;
1145 // now add the repos to the pool
1146 sat::Pool satpool( sat::Pool::instance() );
1147 Pathname rpmsolv( solvfilesPath() / "solv" );
1148 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
1150 // Providing an empty system repo, unload any old content
1151 Repository system( sat::Pool::instance().findSystemRepo() );
1153 if ( system && ! system.solvablesEmpty() )
1155 if ( newCache || force )
1157 system.eraseFromPool(); // invalidates system
1161 return; // nothing to do
1167 system = satpool.systemRepo();
1172 MIL << "adding " << rpmsolv << " to system" << endl;
1173 system.addSolv( rpmsolv );
1175 catch ( const Exception & exp )
1178 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1182 system.addSolv( rpmsolv );
1184 satpool.rootDir( _root );
1186 // (Re)Load the requested locales et al.
1187 // If the requested locales are empty, we leave the pool untouched
1188 // to avoid undoing changes the application applied. We expect this
1189 // to happen on a bare metal installation only. An already existing
1190 // target should be loaded before its settings are changed.
1192 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1193 if ( ! requestedLocales.empty() )
1195 satpool.initRequestedLocales( requestedLocales );
1199 if ( ! PathInfo( _autoInstalledFile.file() ).isExist() )
1201 // Initialize from history, if it does not exist
1202 Pathname historyFile( Pathname::assertprefix( _root, ZConfig::instance().historyLogFile() ) );
1203 if ( PathInfo( historyFile ).isExist() )
1205 SolvIdentFile::Data onSystemByUser( getUserInstalledFromHistory( historyFile ) );
1206 SolvIdentFile::Data onSystemByAuto;
1207 for_( it, system.solvablesBegin(), system.solvablesEnd() )
1209 IdString ident( (*it).ident() );
1210 if ( onSystemByUser.find( ident ) == onSystemByUser.end() )
1211 onSystemByAuto.insert( ident );
1213 _autoInstalledFile.setData( onSystemByAuto );
1215 // on the fly removed any obsolete SoftLocks file
1216 filesystem::unlink( home() / "SoftLocks" );
1218 // read from AutoInstalled file
1220 for ( const auto & idstr : _autoInstalledFile.data() )
1221 q.push( idstr.id() );
1222 satpool.setAutoInstalled( q );
1224 if ( ZConfig::instance().apply_locks_file() )
1226 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1227 if ( ! hardLocks.empty() )
1229 ResPool::instance().setHardLockQueries( hardLocks );
1233 // now that the target is loaded, we can cache the flavor
1234 createLastDistributionFlavorCache();
1236 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1239 ///////////////////////////////////////////////////////////////////
1243 ///////////////////////////////////////////////////////////////////
1244 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1246 // ----------------------------------------------------------------- //
1247 ZYppCommitPolicy policy_r( policy_rX );
1249 // Fake outstanding YCP fix: Honour restriction to media 1
1250 // at installation, but install all remaining packages if post-boot.
1251 if ( policy_r.restrictToMedia() > 1 )
1252 policy_r.allMedia();
1254 if ( policy_r.downloadMode() == DownloadDefault ) {
1255 if ( root() == "/" )
1256 policy_r.downloadMode(DownloadInHeaps);
1258 policy_r.downloadMode(DownloadAsNeeded);
1260 // DownloadOnly implies dry-run.
1261 else if ( policy_r.downloadMode() == DownloadOnly )
1262 policy_r.dryRun( true );
1263 // ----------------------------------------------------------------- //
1265 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1267 ///////////////////////////////////////////////////////////////////
1268 // Compute transaction:
1269 ///////////////////////////////////////////////////////////////////
1270 ZYppCommitResult result( root() );
1271 result.rTransaction() = pool_r.resolver().getTransaction();
1272 result.rTransaction().order();
1273 // steps: this is our todo-list
1274 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1275 if ( policy_r.restrictToMedia() )
1277 // Collect until the 1st package from an unwanted media occurs.
1278 // Further collection could violate install order.
1279 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1280 for_( it, result.transaction().begin(), result.transaction().end() )
1282 if ( makeResObject( *it )->mediaNr() > 1 )
1284 steps.push_back( *it );
1289 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1291 MIL << "Todo: " << result << endl;
1293 ///////////////////////////////////////////////////////////////////
1294 // Prepare execution of commit plugins:
1295 ///////////////////////////////////////////////////////////////////
1296 CommitPlugins commitPlugins;
1297 if ( root() == "/" && ! policy_r.dryRun() )
1299 Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
1300 commitPlugins.load( plugindir );
1302 if ( ! commitPlugins.empty() )
1303 commitPlugins.send( transactionPluginFrame( "COMMITBEGIN", steps ) );
1305 ///////////////////////////////////////////////////////////////////
1306 // Write out a testcase if we're in dist upgrade mode.
1307 ///////////////////////////////////////////////////////////////////
1308 if ( getZYpp()->resolver()->upgradeMode() )
1310 if ( ! policy_r.dryRun() )
1312 writeUpgradeTestcase();
1316 DBG << "dryRun: Not writing upgrade testcase." << endl;
1320 ///////////////////////////////////////////////////////////////////
1321 // Store non-package data:
1322 ///////////////////////////////////////////////////////////////////
1323 if ( ! policy_r.dryRun() )
1325 filesystem::assert_dir( home() );
1326 // requested locales
1327 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1330 SolvIdentFile::Data newdata;
1331 for ( sat::Queue::value_type id : result.rTransaction().autoInstalled() )
1332 newdata.insert( IdString(id) );
1333 _autoInstalledFile.setData( newdata );
1336 if ( ZConfig::instance().apply_locks_file() )
1338 HardLocksFile::Data newdata;
1339 pool_r.getHardLockQueries( newdata );
1340 _hardLocksFile.setData( newdata );
1345 DBG << "dryRun: Not stroring non-package data." << endl;
1348 ///////////////////////////////////////////////////////////////////
1349 // First collect and display all messages
1350 // associated with patches to be installed.
1351 ///////////////////////////////////////////////////////////////////
1352 if ( ! policy_r.dryRun() )
1354 for_( it, steps.begin(), steps.end() )
1356 if ( ! it->satSolvable().isKind<Patch>() )
1360 if ( ! pi.status().isToBeInstalled() )
1363 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1364 if ( ! patch ||patch->message().empty() )
1367 MIL << "Show message for " << patch << endl;
1368 callback::SendReport<target::PatchMessageReport> report;
1369 if ( ! report->show( patch ) )
1371 WAR << "commit aborted by the user" << endl;
1372 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1378 DBG << "dryRun: Not checking patch messages." << endl;
1381 ///////////////////////////////////////////////////////////////////
1382 // Remove/install packages.
1383 ///////////////////////////////////////////////////////////////////
1384 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1385 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1387 // Prepare the package cache. Pass all items requiring download.
1388 CommitPackageCache packageCache( root() );
1389 packageCache.setCommitList( steps.begin(), steps.end() );
1392 if ( policy_r.downloadMode() != DownloadAsNeeded )
1394 // Preload the cache. Until now this means pre-loading all packages.
1395 // Once DownloadInHeaps is fully implemented, this will change and
1396 // we may actually have more than one heap.
1397 for_( it, steps.begin(), steps.end() )
1399 switch ( it->stepType() )
1401 case sat::Transaction::TRANSACTION_INSTALL:
1402 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1403 // proceed: only install actionas may require download.
1407 // next: no download for or non-packages and delete actions.
1413 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1415 ManagedFile localfile;
1418 // TODO: unify packageCache.get for Package and SrcPackage
1419 if ( pi->isKind<Package>() )
1421 localfile = packageCache.get( pi );
1423 else if ( pi->isKind<SrcPackage>() )
1425 repo::RepoMediaAccess access;
1426 repo::SrcPackageProvider prov( access );
1427 localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1431 INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1434 localfile.resetDispose(); // keep the package file in the cache
1436 catch ( const AbortRequestException & exp )
1438 it->stepStage( sat::Transaction::STEP_ERROR );
1440 WAR << "commit cache preload aborted by the user" << endl;
1441 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1444 catch ( const SkipRequestException & exp )
1447 it->stepStage( sat::Transaction::STEP_ERROR );
1449 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1452 catch ( const Exception & exp )
1454 // bnc #395704: missing catch causes abort.
1455 // TODO see if packageCache fails to handle errors correctly.
1457 it->stepStage( sat::Transaction::STEP_ERROR );
1459 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1464 packageCache.preloaded( true ); // try to avoid duplicate infoInCache CBs in commit
1469 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1473 if ( ! policy_r.dryRun() )
1475 // if cache is preloaded, check for file conflicts
1476 commitFindFileConflicts( policy_r, result );
1477 commit( policy_r, packageCache, result );
1481 DBG << "dryRun/downloadOnly: Not installing/deleting anything." << endl;
1487 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1490 ///////////////////////////////////////////////////////////////////
1491 // Send result to commit plugins:
1492 ///////////////////////////////////////////////////////////////////
1493 if ( ! commitPlugins.empty() )
1494 commitPlugins.send( transactionPluginFrame( "COMMITEND", steps ) );
1496 ///////////////////////////////////////////////////////////////////
1497 // Try to rebuild solv file while rpm database is still in cache
1498 ///////////////////////////////////////////////////////////////////
1499 if ( ! policy_r.dryRun() )
1504 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1508 ///////////////////////////////////////////////////////////////////
1512 ///////////////////////////////////////////////////////////////////
1513 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1514 CommitPackageCache & packageCache_r,
1515 ZYppCommitResult & result_r )
1517 // steps: this is our todo-list
1518 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1519 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1521 HistoryLog().stampCommand();
1524 RpmPostTransCollector postTransCollector( _root );
1525 std::vector<sat::Solvable> successfullyInstalledPackages;
1526 TargetImpl::PoolItemList remaining;
1528 for_( step, steps.begin(), steps.end() )
1530 PoolItem citem( *step );
1531 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1533 if ( citem->isKind<Package>() )
1535 // for packages this means being obsoleted (by rpm)
1536 // thius no additional action is needed.
1537 step->stepStage( sat::Transaction::STEP_DONE );
1542 if ( citem->isKind<Package>() )
1544 Package::constPtr p = citem->asKind<Package>();
1545 if ( citem.status().isToBeInstalled() )
1547 ManagedFile localfile;
1550 localfile = packageCache_r.get( citem );
1552 catch ( const AbortRequestException &e )
1554 WAR << "commit aborted by the user" << endl;
1556 step->stepStage( sat::Transaction::STEP_ERROR );
1559 catch ( const SkipRequestException &e )
1562 WAR << "Skipping package " << p << " in commit" << endl;
1563 step->stepStage( sat::Transaction::STEP_ERROR );
1566 catch ( const Exception &e )
1568 // bnc #395704: missing catch causes abort.
1569 // TODO see if packageCache fails to handle errors correctly.
1571 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1572 step->stepStage( sat::Transaction::STEP_ERROR );
1576 #warning Exception handling
1577 // create a installation progress report proxy
1578 RpmInstallPackageReceiver progress( citem.resolvable() );
1579 progress.connect(); // disconnected on destruction.
1581 bool success = false;
1582 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1583 // Why force and nodeps?
1585 // Because zypp builds the transaction and the resolver asserts that
1586 // everything is fine.
1587 // We use rpm just to unpack and register the package in the database.
1588 // We do this step by step, so rpm is not aware of the bigger context.
1589 // So we turn off rpms internal checks, because we do it inside zypp.
1590 flags |= rpm::RPMINST_NODEPS;
1591 flags |= rpm::RPMINST_FORCE;
1593 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1594 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1595 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1596 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1600 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1601 if ( postTransCollector.collectScriptFromPackage( localfile ) )
1602 flags |= rpm::RPMINST_NOPOSTTRANS;
1603 rpm().installPackage( localfile, flags );
1604 HistoryLog().install(citem);
1606 if ( progress.aborted() )
1608 WAR << "commit aborted by the user" << endl;
1609 localfile.resetDispose(); // keep the package file in the cache
1611 step->stepStage( sat::Transaction::STEP_ERROR );
1617 step->stepStage( sat::Transaction::STEP_DONE );
1620 catch ( Exception & excpt_r )
1622 ZYPP_CAUGHT(excpt_r);
1623 localfile.resetDispose(); // keep the package file in the cache
1625 if ( policy_r.dryRun() )
1627 WAR << "dry run failed" << endl;
1628 step->stepStage( sat::Transaction::STEP_ERROR );
1632 if ( progress.aborted() )
1634 WAR << "commit aborted by the user" << endl;
1639 WAR << "Install failed" << endl;
1641 step->stepStage( sat::Transaction::STEP_ERROR );
1645 if ( success && !policy_r.dryRun() )
1647 citem.status().resetTransact( ResStatus::USER );
1648 successfullyInstalledPackages.push_back( citem.satSolvable() );
1649 step->stepStage( sat::Transaction::STEP_DONE );
1654 RpmRemovePackageReceiver progress( citem.resolvable() );
1655 progress.connect(); // disconnected on destruction.
1657 bool success = false;
1658 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1659 flags |= rpm::RPMINST_NODEPS;
1660 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1663 rpm().removePackage( p, flags );
1664 HistoryLog().remove(citem);
1666 if ( progress.aborted() )
1668 WAR << "commit aborted by the user" << endl;
1670 step->stepStage( sat::Transaction::STEP_ERROR );
1676 step->stepStage( sat::Transaction::STEP_DONE );
1679 catch (Exception & excpt_r)
1681 ZYPP_CAUGHT( excpt_r );
1682 if ( progress.aborted() )
1684 WAR << "commit aborted by the user" << endl;
1686 step->stepStage( sat::Transaction::STEP_ERROR );
1690 WAR << "removal of " << p << " failed";
1691 step->stepStage( sat::Transaction::STEP_ERROR );
1693 if ( success && !policy_r.dryRun() )
1695 citem.status().resetTransact( ResStatus::USER );
1696 step->stepStage( sat::Transaction::STEP_DONE );
1700 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1702 // Status is changed as the buddy package buddy
1703 // gets installed/deleted. Handle non-buddies only.
1704 if ( ! citem.buddy() )
1706 if ( citem->isKind<Product>() )
1708 Product::constPtr p = citem->asKind<Product>();
1709 if ( citem.status().isToBeInstalled() )
1711 ERR << "Can't install orphan product without release-package! " << citem << endl;
1715 // Deleting the corresponding product entry is all we con do.
1716 // So the product will no longer be visible as installed.
1717 std::string referenceFilename( p->referenceFilename() );
1718 if ( referenceFilename.empty() )
1720 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1724 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1725 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1727 ERR << "Delete orphan product failed: " << referenceFile << endl;
1732 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1734 // SrcPackage is install-only
1735 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1736 installSrcPackage( p );
1739 citem.status().resetTransact( ResStatus::USER );
1740 step->stepStage( sat::Transaction::STEP_DONE );
1743 } // other resolvables
1747 // process all remembered posttrans scripts.
1749 postTransCollector.executeScripts();
1751 postTransCollector.discardScripts();
1753 // Check presence of update scripts/messages. If aborting,
1754 // at least log omitted scripts.
1755 if ( ! successfullyInstalledPackages.empty() )
1757 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1758 successfullyInstalledPackages, abort ) )
1760 WAR << "Commit aborted by the user" << endl;
1763 // send messages after scripts in case some script generates output,
1764 // that should be kept in t %ghost message file.
1765 RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1766 successfullyInstalledPackages,
1772 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1776 ///////////////////////////////////////////////////////////////////
1778 rpm::RpmDb & TargetImpl::rpm()
1783 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1785 return _rpm.hasFile(path_str, name_str);
1789 Date TargetImpl::timestamp() const
1791 return _rpm.timestamp();
1794 ///////////////////////////////////////////////////////////////////
1797 parser::ProductFileData baseproductdata( const Pathname & root_r )
1799 parser::ProductFileData ret;
1800 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1802 if ( baseproduct.isFile() )
1806 ret = parser::ProductFileReader::scanFile( baseproduct.path() );
1808 catch ( const Exception & excpt )
1810 ZYPP_CAUGHT( excpt );
1813 else if ( PathInfo( Pathname::assertprefix( root_r, "/etc/products.d" ) ).isDir() )
1815 ERR << "baseproduct symlink is dangling or missing: " << baseproduct << endl;
1820 inline Pathname staticGuessRoot( const Pathname & root_r )
1822 if ( root_r.empty() )
1824 // empty root: use existing Target or assume "/"
1825 Pathname ret ( ZConfig::instance().systemRoot() );
1827 return Pathname("/");
1833 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1835 std::ifstream idfile( file_r.c_str() );
1836 for( iostr::EachLine in( idfile ); in; in.next() )
1838 std::string line( str::trim( *in ) );
1839 if ( ! line.empty() )
1842 return std::string();
1845 ///////////////////////////////////////////////////////////////////
1847 Product::constPtr TargetImpl::baseProduct() const
1849 ResPool pool(ResPool::instance());
1850 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1852 Product::constPtr p = (*it)->asKind<Product>();
1853 if ( p->isTargetDistribution() )
1859 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1861 const Pathname needroot( staticGuessRoot(root_r) );
1862 const Target_constPtr target( getZYpp()->getTarget() );
1863 if ( target && target->root() == needroot )
1864 return target->requestedLocales();
1865 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1868 std::string TargetImpl::targetDistribution() const
1869 { return baseproductdata( _root ).registerTarget(); }
1871 std::string TargetImpl::targetDistribution( const Pathname & root_r )
1872 { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1874 std::string TargetImpl::targetDistributionRelease() const
1875 { return baseproductdata( _root ).registerRelease(); }
1877 std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1878 { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1880 std::string TargetImpl::targetDistributionFlavor() const
1881 { return baseproductdata( _root ).registerFlavor(); }
1883 std::string TargetImpl::targetDistributionFlavor( const Pathname & root_r )
1884 { return baseproductdata( staticGuessRoot(root_r) ).registerFlavor();}
1886 Target::DistributionLabel TargetImpl::distributionLabel() const
1888 Target::DistributionLabel ret;
1889 parser::ProductFileData pdata( baseproductdata( _root ) );
1890 ret.shortName = pdata.shortName();
1891 ret.summary = pdata.summary();
1895 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1897 Target::DistributionLabel ret;
1898 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1899 ret.shortName = pdata.shortName();
1900 ret.summary = pdata.summary();
1904 std::string TargetImpl::distributionVersion() const
1906 if ( _distributionVersion.empty() )
1908 _distributionVersion = TargetImpl::distributionVersion(root());
1909 if ( !_distributionVersion.empty() )
1910 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1912 return _distributionVersion;
1915 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1917 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1918 if ( distributionVersion.empty() )
1920 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1921 // On RHEL, Fedora and others the "product version" is determined by the first package
1922 // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1923 // with the $distroverpkg variable.
1924 scoped_ptr<rpm::RpmDb> tmprpmdb;
1925 if ( ZConfig::instance().systemRoot() == Pathname() )
1929 tmprpmdb.reset( new rpm::RpmDb );
1930 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1937 rpm::librpmDb::db_const_iterator it;
1938 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1939 distributionVersion = it->tag_version();
1941 return distributionVersion;
1945 std::string TargetImpl::distributionFlavor() const
1947 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1950 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1952 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1955 ///////////////////////////////////////////////////////////////////
1957 std::string TargetImpl::anonymousUniqueId() const
1959 return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1962 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1964 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1967 ///////////////////////////////////////////////////////////////////
1969 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1971 // provide on local disk
1972 ManagedFile localfile = provideSrcPackage(srcPackage_r);
1974 rpm().installPackage ( localfile );
1977 ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1979 // provide on local disk
1980 repo::RepoMediaAccess access_r;
1981 repo::SrcPackageProvider prov( access_r );
1982 return prov.provideSrcPackage( srcPackage_r );
1984 ////////////////////////////////////////////////////////////////
1985 } // namespace target
1986 ///////////////////////////////////////////////////////////////////
1987 /////////////////////////////////////////////////////////////////
1989 ///////////////////////////////////////////////////////////////////