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/detail/PoolImpl.h"
55 #include "zypp/sat/Transaction.h"
57 #include "zypp/PluginScript.h"
61 ///////////////////////////////////////////////////////////////////
64 /////////////////////////////////////////////////////////////////
67 // HACK for bnc#906096: let pool re-evaluate multiversion spec
68 // if target root changes. ZConfig returns data sensitive to
69 // current target root.
70 inline void sigMultiversionSpecChanged()
72 sat::detail::PoolMember::myPool().multiversionSpecChanged();
75 /////////////////////////////////////////////////////////////////
77 ///////////////////////////////////////////////////////////////////
80 // Lazy via template specialisation / should switch to overloading
83 inline std::string toJSON( const ZYppCommitResult::TransactionStepList & steps_r )
85 using sat::Transaction;
88 for ( const Transaction::Step & step : steps_r )
89 // ignore implicit deletes due to obsoletes and non-package actions
90 if ( step.stepType() != Transaction::TRANSACTION_IGNORE )
96 /** See \ref commitbegin on page \ref plugin-commit for the specs. */
98 inline std::string toJSON( const sat::Transaction::Step & step_r )
100 static const std::string strType( "type" );
101 static const std::string strStage( "stage" );
102 static const std::string strSolvable( "solvable" );
104 static const std::string strTypeDel( "-" );
105 static const std::string strTypeIns( "+" );
106 static const std::string strTypeMul( "M" );
108 static const std::string strStageDone( "ok" );
109 static const std::string strStageFailed( "err" );
111 static const std::string strSolvableN( "n" );
112 static const std::string strSolvableE( "e" );
113 static const std::string strSolvableV( "v" );
114 static const std::string strSolvableR( "r" );
115 static const std::string strSolvableA( "a" );
117 using sat::Transaction;
120 switch ( step_r.stepType() )
122 case Transaction::TRANSACTION_IGNORE: /*empty*/ break;
123 case Transaction::TRANSACTION_ERASE: ret.add( strType, strTypeDel ); break;
124 case Transaction::TRANSACTION_INSTALL: ret.add( strType, strTypeIns ); break;
125 case Transaction::TRANSACTION_MULTIINSTALL: ret.add( strType, strTypeMul ); break;
128 switch ( step_r.stepStage() )
130 case Transaction::STEP_TODO: /*empty*/ break;
131 case Transaction::STEP_DONE: ret.add( strStage, strStageDone ); break;
132 case Transaction::STEP_ERROR: ret.add( strStage, strStageFailed ); break;
139 if ( sat::Solvable solv = step_r.satSolvable() )
141 ident = solv.ident();
147 // deleted package; post mortem data stored in Transaction::Step
148 ident = step_r.ident();
149 ed = step_r.edition();
150 arch = step_r.arch();
154 { strSolvableN, ident.asString() },
155 { strSolvableV, ed.version() },
156 { strSolvableR, ed.release() },
157 { strSolvableA, arch.asString() }
159 if ( Edition::epoch_t epoch = ed.epoch() )
160 s.add( strSolvableE, epoch );
162 ret.add( strSolvable, s );
168 ///////////////////////////////////////////////////////////////////
170 ///////////////////////////////////////////////////////////////////
173 ///////////////////////////////////////////////////////////////////
176 SolvIdentFile::Data getUserInstalledFromHistory( const Pathname & historyFile_r )
178 SolvIdentFile::Data onSystemByUserList;
179 // go and parse it: 'who' must constain an '@', then it was installed by user request.
180 // 2009-09-29 07:25:19|install|lirc-remotes|0.8.5-3.2|x86_64|root@opensuse|InstallationImage|a204211eb0...
181 std::ifstream infile( historyFile_r.c_str() );
182 for( iostr::EachLine in( infile ); in; in.next() )
184 const char * ch( (*in).c_str() );
186 if ( *ch < '1' || '9' < *ch )
188 const char * sep1 = ::strchr( ch, '|' ); // | after date
192 // if logs an install or delete
193 bool installs = true;
194 if ( ::strncmp( sep1, "install|", 8 ) )
196 if ( ::strncmp( sep1, "remove |", 8 ) )
197 continue; // no install and no remove
199 installs = false; // remove
201 sep1 += 8; // | after what
202 // get the package name
203 const char * sep2 = ::strchr( sep1, '|' ); // | after name
204 if ( !sep2 || sep1 == sep2 )
206 (*in)[sep2-ch] = '\0';
207 IdString pkg( sep1 );
208 // we're done, if a delete
211 onSystemByUserList.erase( pkg );
214 // now guess whether user installed or not (3rd next field contains 'user@host')
215 if ( (sep1 = ::strchr( sep2+1, '|' )) // | after version
216 && (sep1 = ::strchr( sep1+1, '|' )) // | after arch
217 && (sep2 = ::strchr( sep1+1, '|' )) ) // | after who
219 (*in)[sep2-ch] = '\0';
220 if ( ::strchr( sep1+1, '@' ) )
223 onSystemByUserList.insert( pkg );
228 MIL << "onSystemByUserList found: " << onSystemByUserList.size() << endl;
229 return onSystemByUserList;
232 ///////////////////////////////////////////////////////////////////
234 /** Helper for commit plugin execution.
237 class CommitPlugins : private base::NonCopyable
240 /** Default ctor: Empty plugin list */
244 /** Dtor: Send PLUGINEND message and close plugins. */
247 if ( ! _scripts.empty() )
248 send( PluginFrame( "PLUGINEND" ) );
249 // ~PluginScript will disconnect all remaining plugins!
252 /** Whether no plugins are waiting */
254 { return _scripts.empty(); }
257 /** Send \ref PluginFrame to all open plugins.
258 * Failed plugins are removed from the execution list.
260 void send( const PluginFrame & frame_r )
262 DBG << "+++++++++++++++ send " << frame_r << endl;
263 for ( auto it = _scripts.begin(); it != _scripts.end(); )
265 doSend( *it, frame_r );
269 it = _scripts.erase( it );
271 DBG << "--------------- send " << frame_r << endl;
274 /** Find and launch plugins sending PLUGINSTART message.
276 * If \a path_r is a directory all executable files whithin are
277 * expected to be plugins. Otherwise \a path_r must point to an
280 void load( const Pathname & path_r )
282 PathInfo pi( path_r );
283 DBG << "+++++++++++++++ load " << pi << endl;
286 std::list<Pathname> entries;
287 if ( filesystem::readdir( entries, pi.path(), false ) != 0 )
289 WAR << "Plugin dir is not readable: " << pi << endl;
292 for_( it, entries.begin(), entries.end() )
295 if ( pii.isFile() && pii.userMayRX() )
299 else if ( pi.isFile() )
301 if ( pi.userMayRX() )
304 WAR << "Plugin file is not executable: " << pi << endl;
308 WAR << "Plugin path is neither dir nor file: " << pi << endl;
310 DBG << "--------------- load " << pi << endl;
314 /** Send \ref PluginFrame and expect valid answer (ACK|_ENOMETHOD).
315 * Upon invalid answer or error, close the plugin. and remove it from the
317 * \returns the received \ref PluginFrame (empty Frame upon Exception)
319 PluginFrame doSend( PluginScript & script_r, const PluginFrame & frame_r )
324 script_r.send( frame_r );
325 ret = script_r.receive();
327 catch( const zypp::Exception & e )
330 if ( ! ( ret.isAckCommand() || ret.isEnomethodCommand() ) )
332 WAR << "Bad plugin response from " << script_r << endl;
333 WAR << dump(ret) << endl;
340 /** Launch a plugin sending PLUGINSTART message. */
341 void doLoad( const PathInfo & pi_r )
343 MIL << "Load plugin: " << pi_r << endl;
345 PluginScript plugin( pi_r.path() );
348 PluginFrame frame( "PLUGINBEGIN" );
349 if ( ZConfig::instance().hasUserData() )
350 frame.setHeader( "userdata", ZConfig::instance().userData() );
352 doSend( plugin, frame ); // closes on error
353 if ( plugin.isOpen() )
354 _scripts.push_back( plugin );
356 catch( const zypp::Exception & e )
358 WAR << "Failed to load plugin " << pi_r << endl;
363 std::list<PluginScript> _scripts;
366 void testCommitPlugins( const Pathname & path_r ) // for testing only
368 USR << "+++++" << endl;
372 USR << "=====" << endl;
374 USR << "-----" << endl;
377 ///////////////////////////////////////////////////////////////////
380 inline PluginFrame transactionPluginFrame( const std::string & command_r, ZYppCommitResult::TransactionStepList & steps_r )
382 return PluginFrame( command_r, json::Object {
383 { "TransactionStepList", steps_r }
387 ///////////////////////////////////////////////////////////////////
389 /** \internal Manage writing a new testcase when doing an upgrade. */
390 void writeUpgradeTestcase()
392 unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
393 MIL << "Testcases to keep: " << toKeep << endl;
396 Target_Ptr target( getZYpp()->getTarget() );
399 WAR << "No Target no Testcase!" << endl;
403 std::string stem( "updateTestcase" );
404 Pathname dir( target->assertRootPrefix("/var/log/") );
405 Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
408 std::list<std::string> content;
409 filesystem::readdir( content, dir, /*dots*/false );
410 std::set<std::string> cases;
411 for_( c, content.begin(), content.end() )
413 if ( str::startsWith( *c, stem ) )
416 if ( cases.size() >= toKeep )
418 unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
419 for_( c, cases.begin(), cases.end() )
421 filesystem::recursive_rmdir( dir/(*c) );
428 MIL << "Write new testcase " << next << endl;
429 getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
432 ///////////////////////////////////////////////////////////////////
434 { /////////////////////////////////////////////////////////////////
436 /** Execute script and report against report_r.
437 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
438 * execution was successfull (<tt>first = true</tt>), or the desired
439 * \c PatchScriptReport::Action in case execution failed
440 * (<tt>first = false</tt>).
442 * \note The packager is responsible for setting the correct permissions
443 * of the script. If the script is not executable it is reported as an
444 * error. We must not modify the permessions.
446 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
447 const Pathname & script_r,
448 callback::SendReport<PatchScriptReport> & report_r )
450 MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
452 HistoryLog historylog;
453 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
454 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
456 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
458 historylog.comment(output);
459 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
461 WAR << "User request to abort script " << script_r << endl;
463 // the rest is handled by exit code evaluation
464 // in case the script has meanwhile finished.
468 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
470 if ( prog.close() != 0 )
472 ret.second = report_r->problem( prog.execError() );
473 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
474 std::ostringstream sstr;
475 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
476 historylog.comment(sstr.str(), /*timestamp*/true);
485 /** Execute script and report against report_r.
486 * Return \c false if user requested \c ABORT.
488 bool executeScript( const Pathname & root_r,
489 const Pathname & script_r,
490 callback::SendReport<PatchScriptReport> & report_r )
492 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
495 action = doExecuteScript( root_r, script_r, report_r );
497 return true; // success
499 switch ( action.second )
501 case PatchScriptReport::ABORT:
502 WAR << "User request to abort at script " << script_r << endl;
503 return false; // requested abort.
506 case PatchScriptReport::IGNORE:
507 WAR << "User request to skip script " << script_r << endl;
508 return true; // requested skip.
511 case PatchScriptReport::RETRY:
514 } while ( action.second == PatchScriptReport::RETRY );
516 // THIS is not intended to be reached:
517 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
518 return false; // abort.
521 /** Look for update scripts named 'name-version-release-*' and
522 * execute them. Return \c false if \c ABORT was requested.
524 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
526 bool RunUpdateScripts( const Pathname & root_r,
527 const Pathname & scriptsPath_r,
528 const std::vector<sat::Solvable> & checkPackages_r,
531 if ( checkPackages_r.empty() )
532 return true; // no installed packages to check
534 MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
535 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
536 if ( ! PathInfo( scriptsDir ).isDir() )
537 return true; // no script dir
539 std::list<std::string> scripts;
540 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
541 if ( scripts.empty() )
542 return true; // no scripts in script dir
544 // Now collect and execute all matching scripts.
545 // On ABORT: at least log all outstanding scripts.
546 // - "name-version-release"
547 // - "name-version-release-*"
549 std::map<std::string, Pathname> unify; // scripts <md5,path>
550 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
552 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
553 for_( sit, scripts.begin(), scripts.end() )
555 if ( ! str::hasPrefix( *sit, prefix ) )
558 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
559 continue; // if not exact match it had to continue with '-'
561 PathInfo script( scriptsDir / *sit );
562 Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
563 std::string unifytag; // must not stay empty
565 if ( script.isFile() )
567 // Assert it's set executable, unify by md5sum.
568 filesystem::addmod( script.path(), 0500 );
569 unifytag = filesystem::md5sum( script.path() );
571 else if ( ! script.isExist() )
573 // Might be a dangling symlink, might be ok if we are in
574 // instsys (absolute symlink within the system below /mnt).
575 // readlink will tell....
576 unifytag = filesystem::readlink( script.path() ).asString();
579 if ( unifytag.empty() )
583 if ( unify[unifytag].empty() )
585 unify[unifytag] = localPath;
589 // translators: We may find the same script content in files with different names.
590 // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
591 // message for a log file. Preferably start translation with "%s"
592 std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
593 MIL << "Skip update script: " << msg << endl;
594 HistoryLog().comment( msg, /*timestamp*/true );
598 if ( abort || aborting_r )
600 WAR << "Aborting: Skip update script " << *sit << endl;
601 HistoryLog().comment(
602 localPath.asString() + _(" execution skipped while aborting"),
607 MIL << "Found update script " << *sit << endl;
608 callback::SendReport<PatchScriptReport> report;
609 report->start( make<Package>( *it ), script.path() );
611 if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
612 abort = true; // requested abort.
619 ///////////////////////////////////////////////////////////////////
621 ///////////////////////////////////////////////////////////////////
623 inline void copyTo( std::ostream & out_r, const Pathname & file_r )
625 std::ifstream infile( file_r.c_str() );
626 for( iostr::EachLine in( infile ); in; in.next() )
628 out_r << *in << endl;
632 inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
634 std::string ret( cmd_r );
635 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
636 SUBST_IF( "%p", notification_r.solvable().asString() );
637 SUBST_IF( "%P", notification_r.file().asString() );
642 void sendNotification( const Pathname & root_r,
643 const UpdateNotifications & notifications_r )
645 if ( notifications_r.empty() )
648 std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
649 MIL << "Notification command is '" << cmdspec << "'" << endl;
650 if ( cmdspec.empty() )
653 std::string::size_type pos( cmdspec.find( '|' ) );
654 if ( pos == std::string::npos )
656 ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
657 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
661 std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
662 std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
664 enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
665 Format format = UNKNOWN;
666 if ( formatStr == "none" )
668 else if ( formatStr == "single" )
670 else if ( formatStr == "digest" )
672 else if ( formatStr == "bulk" )
676 ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
677 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
681 // Take care: commands are ececuted chroot(root_r). The message file
682 // pathnames in notifications_r are local to root_r. For physical access
683 // to the file they need to be prefixed.
685 if ( format == NONE || format == SINGLE )
687 for_( it, notifications_r.begin(), notifications_r.end() )
689 std::vector<std::string> command;
690 if ( format == SINGLE )
691 command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
692 str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
694 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
695 if ( true ) // Wait for feedback
697 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
701 int ret = prog.close();
704 ERR << "Notification command returned with error (" << ret << ")." << endl;
705 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
711 else if ( format == DIGEST || format == BULK )
713 filesystem::TmpFile tmpfile;
714 ofstream out( tmpfile.path().c_str() );
715 for_( it, notifications_r.begin(), notifications_r.end() )
717 if ( format == DIGEST )
719 out << it->file() << endl;
721 else if ( format == BULK )
723 copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
727 std::vector<std::string> command;
728 command.push_back( "<"+tmpfile.path().asString() ); // redirect input
729 str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
731 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
732 if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
734 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
738 int ret = prog.close();
741 ERR << "Notification command returned with error (" << ret << ")." << endl;
742 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
749 INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
750 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
756 /** Look for update messages named 'name-version-release-*' and
757 * send notification according to \ref ZConfig::updateMessagesNotify.
759 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
761 void RunUpdateMessages( const Pathname & root_r,
762 const Pathname & messagesPath_r,
763 const std::vector<sat::Solvable> & checkPackages_r,
764 ZYppCommitResult & result_r )
766 if ( checkPackages_r.empty() )
767 return; // no installed packages to check
769 MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
770 Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
771 if ( ! PathInfo( messagesDir ).isDir() )
772 return; // no messages dir
774 std::list<std::string> messages;
775 filesystem::readdir( messages, messagesDir, /*dots*/false );
776 if ( messages.empty() )
777 return; // no messages in message dir
779 // Now collect all matching messages in result and send them
780 // - "name-version-release"
781 // - "name-version-release-*"
782 HistoryLog historylog;
783 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
785 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
786 for_( sit, messages.begin(), messages.end() )
788 if ( ! str::hasPrefix( *sit, prefix ) )
791 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
792 continue; // if not exact match it had to continue with '-'
794 PathInfo message( messagesDir / *sit );
795 if ( ! message.isFile() || message.size() == 0 )
798 MIL << "Found update message " << *sit << endl;
799 Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
800 result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
801 historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
804 sendNotification( root_r, result_r.updateMessages() );
807 /////////////////////////////////////////////////////////////////
809 ///////////////////////////////////////////////////////////////////
811 void XRunUpdateMessages( const Pathname & root_r,
812 const Pathname & messagesPath_r,
813 const std::vector<sat::Solvable> & checkPackages_r,
814 ZYppCommitResult & result_r )
815 { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
817 ///////////////////////////////////////////////////////////////////
819 IMPL_PTR_TYPE(TargetImpl);
821 ///////////////////////////////////////////////////////////////////
823 // METHOD NAME : TargetImpl::TargetImpl
824 // METHOD TYPE : Ctor
826 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
828 , _requestedLocalesFile( home() / "RequestedLocales" )
829 , _autoInstalledFile( home() / "AutoInstalled" )
830 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
832 _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
834 HistoryLog::setRoot(_root);
837 sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
838 MIL << "Initialized target on " << _root << endl;
842 * generates a random id using uuidgen
844 static std::string generateRandomId()
846 std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
847 return iostr::getline( uuidprovider );
851 * updates the content of \p filename
852 * if \p condition is true, setting the content
853 * the the value returned by \p value
855 void updateFileContent( const Pathname &filename,
856 boost::function<bool ()> condition,
857 boost::function<string ()> value )
859 string val = value();
860 // if the value is empty, then just dont
861 // do anything, regardless of the condition
867 MIL << "updating '" << filename << "' content." << endl;
869 // if the file does not exist we need to generate the uuid file
871 std::ofstream filestr;
872 // make sure the path exists
873 filesystem::assert_dir( filename.dirname() );
874 filestr.open( filename.c_str() );
876 if ( filestr.good() )
883 // FIXME, should we ignore the error?
884 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
889 /** helper functor */
890 static bool fileMissing( const Pathname &pathname )
892 return ! PathInfo(pathname).isExist();
895 void TargetImpl::createAnonymousId() const
898 // create the anonymous unique id
899 // this value is used for statistics
900 Pathname idpath( home() / "AnonymousUniqueId");
904 updateFileContent( idpath,
905 boost::bind(fileMissing, idpath),
908 catch ( const Exception &e )
910 WAR << "Can't create anonymous id file" << endl;
915 void TargetImpl::createLastDistributionFlavorCache() const
917 // create the anonymous unique id
918 // this value is used for statistics
919 Pathname flavorpath( home() / "LastDistributionFlavor");
921 // is there a product
922 Product::constPtr p = baseProduct();
925 WAR << "No base product, I won't create flavor cache" << endl;
929 string flavor = p->flavor();
934 updateFileContent( flavorpath,
935 // only if flavor is not empty
936 functor::Constant<bool>( ! flavor.empty() ),
937 functor::Constant<string>(flavor) );
939 catch ( const Exception &e )
941 WAR << "Can't create flavor cache" << endl;
946 ///////////////////////////////////////////////////////////////////
948 // METHOD NAME : TargetImpl::~TargetImpl
949 // METHOD TYPE : Dtor
951 TargetImpl::~TargetImpl()
953 _rpm.closeDatabase();
954 sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
955 MIL << "Targets closed" << endl;
958 ///////////////////////////////////////////////////////////////////
960 // solv file handling
962 ///////////////////////////////////////////////////////////////////
964 Pathname TargetImpl::defaultSolvfilesPath() const
966 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
969 void TargetImpl::clearCache()
971 Pathname base = solvfilesPath();
972 filesystem::recursive_rmdir( base );
975 bool TargetImpl::buildCache()
977 Pathname base = solvfilesPath();
978 Pathname rpmsolv = base/"solv";
979 Pathname rpmsolvcookie = base/"cookie";
981 bool build_rpm_solv = true;
982 // lets see if the rpm solv cache exists
984 RepoStatus rpmstatus( RepoStatus(_root/"var/lib/rpm/Name") && RepoStatus(_root/"etc/products.d") );
986 bool solvexisted = PathInfo(rpmsolv).isExist();
989 // see the status of the cache
990 PathInfo cookie( rpmsolvcookie );
991 MIL << "Read cookie: " << cookie << endl;
992 if ( cookie.isExist() )
994 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
995 // now compare it with the rpm database
996 if ( status == rpmstatus )
997 build_rpm_solv = false;
998 MIL << "Read cookie: " << rpmsolvcookie << " says: "
999 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
1003 if ( build_rpm_solv )
1005 // if the solvfile dir does not exist yet, we better create it
1006 filesystem::assert_dir( base );
1008 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
1010 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
1013 // Can't create temporary solv file, usually due to insufficient permission
1014 // (user query while @System solv needs refresh). If so, try switching
1015 // to a location within zypps temp. space (will be cleaned at application end).
1017 bool switchingToTmpSolvfile = false;
1018 Exception ex("Failed to cache rpm database.");
1019 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
1021 if ( ! solvfilesPathIsTemp() )
1023 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
1024 rpmsolv = base/"solv";
1025 rpmsolvcookie = base/"cookie";
1027 filesystem::assert_dir( base );
1028 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
1032 WAR << "Using a temporary solv file at " << base << endl;
1033 switchingToTmpSolvfile = true;
1034 _tmpSolvfilesPath = base;
1038 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
1042 if ( ! switchingToTmpSolvfile )
1048 // Take care we unlink the solvfile on exception
1049 ManagedFile guard( base, filesystem::recursive_rmdir );
1051 ExternalProgram::Arguments cmd;
1052 cmd.push_back( "rpmdb2solv" );
1053 if ( ! _root.empty() ) {
1054 cmd.push_back( "-r" );
1055 cmd.push_back( _root.asString() );
1057 cmd.push_back( "-X" ); // autogenerate pattern/product/... from -package
1058 cmd.push_back( "-A" ); // autogenerate application pseudo packages
1059 cmd.push_back( "-p" );
1060 cmd.push_back( Pathname::assertprefix( _root, "/etc/products.d" ).asString() );
1062 if ( ! oldSolvFile.empty() )
1063 cmd.push_back( oldSolvFile.asString() );
1065 cmd.push_back( "-o" );
1066 cmd.push_back( tmpsolv.path().asString() );
1068 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
1069 std::string errdetail;
1071 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1072 WAR << " " << output;
1073 if ( errdetail.empty() ) {
1074 errdetail = prog.command();
1077 errdetail += output;
1080 int ret = prog.close();
1083 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
1084 ex.remember( errdetail );
1088 ret = filesystem::rename( tmpsolv, rpmsolv );
1090 ZYPP_THROW(Exception("Failed to move cache to final destination"));
1091 // if this fails, don't bother throwing exceptions
1092 filesystem::chmod( rpmsolv, 0644 );
1094 rpmstatus.saveToCookieFile(rpmsolvcookie);
1097 guard.resetDispose();
1098 sat::updateSolvFileIndex( rpmsolv ); // content digest for zypper bash completion
1100 // Finally send notification to plugins
1101 // NOTE: quick hack looking for spacewalk plugin only
1103 Pathname script( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"system/spacewalk" ) );
1104 if ( PathInfo( script ).isX() )
1106 PluginScript spacewalk( script );
1109 PluginFrame notify( "PACKAGESETCHANGED" );
1110 spacewalk.send( notify );
1112 PluginFrame ret( spacewalk.receive() );
1114 if ( ret.command() == "ERROR" )
1115 ret.writeTo( WAR ) << endl;
1117 catch ( const Exception & excpt )
1119 WAR << excpt.asUserHistory() << endl;
1125 // On the fly add missing solv.idx files for bash completion.
1126 if ( ! PathInfo(base/"solv.idx").isExist() )
1127 sat::updateSolvFileIndex( rpmsolv );
1129 return build_rpm_solv;
1132 void TargetImpl::reload()
1137 void TargetImpl::unload()
1139 Repository system( sat::Pool::instance().findSystemRepo() );
1141 system.eraseFromPool();
1144 void TargetImpl::load( bool force )
1146 bool newCache = buildCache();
1147 MIL << "New cache built: " << (newCache?"true":"false") <<
1148 ", force loading: " << (force?"true":"false") << endl;
1150 // now add the repos to the pool
1151 sat::Pool satpool( sat::Pool::instance() );
1152 Pathname rpmsolv( solvfilesPath() / "solv" );
1153 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
1155 // Providing an empty system repo, unload any old content
1156 Repository system( sat::Pool::instance().findSystemRepo() );
1158 if ( system && ! system.solvablesEmpty() )
1160 if ( newCache || force )
1162 system.eraseFromPool(); // invalidates system
1166 return; // nothing to do
1172 system = satpool.systemRepo();
1177 MIL << "adding " << rpmsolv << " to system" << endl;
1178 system.addSolv( rpmsolv );
1180 catch ( const Exception & exp )
1183 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1187 system.addSolv( rpmsolv );
1189 satpool.rootDir( _root );
1191 // (Re)Load the requested locales et al.
1192 // If the requested locales are empty, we leave the pool untouched
1193 // to avoid undoing changes the application applied. We expect this
1194 // to happen on a bare metal installation only. An already existing
1195 // target should be loaded before its settings are changed.
1197 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1198 if ( ! requestedLocales.empty() )
1200 satpool.initRequestedLocales( requestedLocales );
1204 if ( ! PathInfo( _autoInstalledFile.file() ).isExist() )
1206 // Initialize from history, if it does not exist
1207 Pathname historyFile( Pathname::assertprefix( _root, ZConfig::instance().historyLogFile() ) );
1208 if ( PathInfo( historyFile ).isExist() )
1210 SolvIdentFile::Data onSystemByUser( getUserInstalledFromHistory( historyFile ) );
1211 SolvIdentFile::Data onSystemByAuto;
1212 for_( it, system.solvablesBegin(), system.solvablesEnd() )
1214 IdString ident( (*it).ident() );
1215 if ( onSystemByUser.find( ident ) == onSystemByUser.end() )
1216 onSystemByAuto.insert( ident );
1218 _autoInstalledFile.setData( onSystemByAuto );
1220 // on the fly removed any obsolete SoftLocks file
1221 filesystem::unlink( home() / "SoftLocks" );
1223 // read from AutoInstalled file
1225 for ( const auto & idstr : _autoInstalledFile.data() )
1226 q.push( idstr.id() );
1227 satpool.setAutoInstalled( q );
1229 if ( ZConfig::instance().apply_locks_file() )
1231 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1232 if ( ! hardLocks.empty() )
1234 ResPool::instance().setHardLockQueries( hardLocks );
1238 // now that the target is loaded, we can cache the flavor
1239 createLastDistributionFlavorCache();
1241 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1244 ///////////////////////////////////////////////////////////////////
1248 ///////////////////////////////////////////////////////////////////
1249 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1251 // ----------------------------------------------------------------- //
1252 ZYppCommitPolicy policy_r( policy_rX );
1254 // Fake outstanding YCP fix: Honour restriction to media 1
1255 // at installation, but install all remaining packages if post-boot.
1256 if ( policy_r.restrictToMedia() > 1 )
1257 policy_r.allMedia();
1259 if ( policy_r.downloadMode() == DownloadDefault ) {
1260 if ( root() == "/" )
1261 policy_r.downloadMode(DownloadInHeaps);
1263 policy_r.downloadMode(DownloadAsNeeded);
1265 // DownloadOnly implies dry-run.
1266 else if ( policy_r.downloadMode() == DownloadOnly )
1267 policy_r.dryRun( true );
1268 // ----------------------------------------------------------------- //
1270 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1272 ///////////////////////////////////////////////////////////////////
1273 // Compute transaction:
1274 ///////////////////////////////////////////////////////////////////
1275 ZYppCommitResult result( root() );
1276 result.rTransaction() = pool_r.resolver().getTransaction();
1277 result.rTransaction().order();
1278 // steps: this is our todo-list
1279 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1280 if ( policy_r.restrictToMedia() )
1282 // Collect until the 1st package from an unwanted media occurs.
1283 // Further collection could violate install order.
1284 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1285 for_( it, result.transaction().begin(), result.transaction().end() )
1287 if ( makeResObject( *it )->mediaNr() > 1 )
1289 steps.push_back( *it );
1294 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1296 MIL << "Todo: " << result << endl;
1298 ///////////////////////////////////////////////////////////////////
1299 // Prepare execution of commit plugins:
1300 ///////////////////////////////////////////////////////////////////
1301 CommitPlugins commitPlugins;
1302 if ( root() == "/" && ! policy_r.dryRun() )
1304 Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
1305 commitPlugins.load( plugindir );
1307 if ( ! commitPlugins.empty() )
1308 commitPlugins.send( transactionPluginFrame( "COMMITBEGIN", steps ) );
1310 ///////////////////////////////////////////////////////////////////
1311 // Write out a testcase if we're in dist upgrade mode.
1312 ///////////////////////////////////////////////////////////////////
1313 if ( getZYpp()->resolver()->upgradeMode() )
1315 if ( ! policy_r.dryRun() )
1317 writeUpgradeTestcase();
1321 DBG << "dryRun: Not writing upgrade testcase." << endl;
1325 ///////////////////////////////////////////////////////////////////
1326 // Store non-package data:
1327 ///////////////////////////////////////////////////////////////////
1328 if ( ! policy_r.dryRun() )
1330 filesystem::assert_dir( home() );
1331 // requested locales
1332 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1335 SolvIdentFile::Data newdata;
1336 for ( sat::Queue::value_type id : result.rTransaction().autoInstalled() )
1337 newdata.insert( IdString(id) );
1338 _autoInstalledFile.setData( newdata );
1341 if ( ZConfig::instance().apply_locks_file() )
1343 HardLocksFile::Data newdata;
1344 pool_r.getHardLockQueries( newdata );
1345 _hardLocksFile.setData( newdata );
1350 DBG << "dryRun: Not stroring non-package data." << endl;
1353 ///////////////////////////////////////////////////////////////////
1354 // First collect and display all messages
1355 // associated with patches to be installed.
1356 ///////////////////////////////////////////////////////////////////
1357 if ( ! policy_r.dryRun() )
1359 for_( it, steps.begin(), steps.end() )
1361 if ( ! it->satSolvable().isKind<Patch>() )
1365 if ( ! pi.status().isToBeInstalled() )
1368 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1369 if ( ! patch ||patch->message().empty() )
1372 MIL << "Show message for " << patch << endl;
1373 callback::SendReport<target::PatchMessageReport> report;
1374 if ( ! report->show( patch ) )
1376 WAR << "commit aborted by the user" << endl;
1377 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1383 DBG << "dryRun: Not checking patch messages." << endl;
1386 ///////////////////////////////////////////////////////////////////
1387 // Remove/install packages.
1388 ///////////////////////////////////////////////////////////////////
1389 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1390 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1392 // Prepare the package cache. Pass all items requiring download.
1393 CommitPackageCache packageCache( root() );
1394 packageCache.setCommitList( steps.begin(), steps.end() );
1397 if ( policy_r.downloadMode() != DownloadAsNeeded )
1399 // Preload the cache. Until now this means pre-loading all packages.
1400 // Once DownloadInHeaps is fully implemented, this will change and
1401 // we may actually have more than one heap.
1402 for_( it, steps.begin(), steps.end() )
1404 switch ( it->stepType() )
1406 case sat::Transaction::TRANSACTION_INSTALL:
1407 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1408 // proceed: only install actionas may require download.
1412 // next: no download for or non-packages and delete actions.
1418 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1420 ManagedFile localfile;
1423 // TODO: unify packageCache.get for Package and SrcPackage
1424 if ( pi->isKind<Package>() )
1426 localfile = packageCache.get( pi );
1428 else if ( pi->isKind<SrcPackage>() )
1430 repo::RepoMediaAccess access;
1431 repo::SrcPackageProvider prov( access );
1432 localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1436 INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1439 localfile.resetDispose(); // keep the package file in the cache
1441 catch ( const AbortRequestException & exp )
1443 it->stepStage( sat::Transaction::STEP_ERROR );
1445 WAR << "commit cache preload aborted by the user" << endl;
1446 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1449 catch ( const SkipRequestException & exp )
1452 it->stepStage( sat::Transaction::STEP_ERROR );
1454 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1457 catch ( const Exception & exp )
1459 // bnc #395704: missing catch causes abort.
1460 // TODO see if packageCache fails to handle errors correctly.
1462 it->stepStage( sat::Transaction::STEP_ERROR );
1464 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1469 packageCache.preloaded( true ); // try to avoid duplicate infoInCache CBs in commit
1474 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1478 if ( ! policy_r.dryRun() )
1480 // if cache is preloaded, check for file conflicts
1481 commitFindFileConflicts( policy_r, result );
1482 commit( policy_r, packageCache, result );
1486 DBG << "dryRun/downloadOnly: Not installing/deleting anything." << endl;
1492 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1495 ///////////////////////////////////////////////////////////////////
1496 // Send result to commit plugins:
1497 ///////////////////////////////////////////////////////////////////
1498 if ( ! commitPlugins.empty() )
1499 commitPlugins.send( transactionPluginFrame( "COMMITEND", steps ) );
1501 ///////////////////////////////////////////////////////////////////
1502 // Try to rebuild solv file while rpm database is still in cache
1503 ///////////////////////////////////////////////////////////////////
1504 if ( ! policy_r.dryRun() )
1509 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1513 ///////////////////////////////////////////////////////////////////
1517 ///////////////////////////////////////////////////////////////////
1520 struct NotifyAttemptToModify
1522 NotifyAttemptToModify( ZYppCommitResult & result_r ) : _result( result_r ) {}
1525 { if ( _guard ) { _result.attemptToModify( true ); _guard = false; } }
1528 ZYppCommitResult & _result;
1532 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1533 CommitPackageCache & packageCache_r,
1534 ZYppCommitResult & result_r )
1536 // steps: this is our todo-list
1537 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1538 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1540 HistoryLog().stampCommand();
1542 // Send notification once upon 1st call to rpm
1543 NotifyAttemptToModify attemptToModify( result_r );
1547 RpmPostTransCollector postTransCollector( _root );
1548 std::vector<sat::Solvable> successfullyInstalledPackages;
1549 TargetImpl::PoolItemList remaining;
1551 for_( step, steps.begin(), steps.end() )
1553 PoolItem citem( *step );
1554 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1556 if ( citem->isKind<Package>() )
1558 // for packages this means being obsoleted (by rpm)
1559 // thius no additional action is needed.
1560 step->stepStage( sat::Transaction::STEP_DONE );
1565 if ( citem->isKind<Package>() )
1567 Package::constPtr p = citem->asKind<Package>();
1568 if ( citem.status().isToBeInstalled() )
1570 ManagedFile localfile;
1573 localfile = packageCache_r.get( citem );
1575 catch ( const AbortRequestException &e )
1577 WAR << "commit aborted by the user" << endl;
1579 step->stepStage( sat::Transaction::STEP_ERROR );
1582 catch ( const SkipRequestException &e )
1585 WAR << "Skipping package " << p << " in commit" << endl;
1586 step->stepStage( sat::Transaction::STEP_ERROR );
1589 catch ( const Exception &e )
1591 // bnc #395704: missing catch causes abort.
1592 // TODO see if packageCache fails to handle errors correctly.
1594 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1595 step->stepStage( sat::Transaction::STEP_ERROR );
1599 #warning Exception handling
1600 // create a installation progress report proxy
1601 RpmInstallPackageReceiver progress( citem.resolvable() );
1602 progress.connect(); // disconnected on destruction.
1604 bool success = false;
1605 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1606 // Why force and nodeps?
1608 // Because zypp builds the transaction and the resolver asserts that
1609 // everything is fine.
1610 // We use rpm just to unpack and register the package in the database.
1611 // We do this step by step, so rpm is not aware of the bigger context.
1612 // So we turn off rpms internal checks, because we do it inside zypp.
1613 flags |= rpm::RPMINST_NODEPS;
1614 flags |= rpm::RPMINST_FORCE;
1616 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1617 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1618 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1619 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1624 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1625 if ( postTransCollector.collectScriptFromPackage( localfile ) )
1626 flags |= rpm::RPMINST_NOPOSTTRANS;
1627 rpm().installPackage( localfile, flags );
1628 HistoryLog().install(citem);
1630 if ( progress.aborted() )
1632 WAR << "commit aborted by the user" << endl;
1633 localfile.resetDispose(); // keep the package file in the cache
1635 step->stepStage( sat::Transaction::STEP_ERROR );
1641 step->stepStage( sat::Transaction::STEP_DONE );
1644 catch ( Exception & excpt_r )
1646 ZYPP_CAUGHT(excpt_r);
1647 localfile.resetDispose(); // keep the package file in the cache
1649 if ( policy_r.dryRun() )
1651 WAR << "dry run failed" << endl;
1652 step->stepStage( sat::Transaction::STEP_ERROR );
1656 if ( progress.aborted() )
1658 WAR << "commit aborted by the user" << endl;
1663 WAR << "Install failed" << endl;
1665 step->stepStage( sat::Transaction::STEP_ERROR );
1669 if ( success && !policy_r.dryRun() )
1671 citem.status().resetTransact( ResStatus::USER );
1672 successfullyInstalledPackages.push_back( citem.satSolvable() );
1673 step->stepStage( sat::Transaction::STEP_DONE );
1678 RpmRemovePackageReceiver progress( citem.resolvable() );
1679 progress.connect(); // disconnected on destruction.
1681 bool success = false;
1682 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1683 flags |= rpm::RPMINST_NODEPS;
1684 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1689 rpm().removePackage( p, flags );
1690 HistoryLog().remove(citem);
1692 if ( progress.aborted() )
1694 WAR << "commit aborted by the user" << endl;
1696 step->stepStage( sat::Transaction::STEP_ERROR );
1702 step->stepStage( sat::Transaction::STEP_DONE );
1705 catch (Exception & excpt_r)
1707 ZYPP_CAUGHT( excpt_r );
1708 if ( progress.aborted() )
1710 WAR << "commit aborted by the user" << endl;
1712 step->stepStage( sat::Transaction::STEP_ERROR );
1716 WAR << "removal of " << p << " failed";
1717 step->stepStage( sat::Transaction::STEP_ERROR );
1719 if ( success && !policy_r.dryRun() )
1721 citem.status().resetTransact( ResStatus::USER );
1722 step->stepStage( sat::Transaction::STEP_DONE );
1726 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1728 // Status is changed as the buddy package buddy
1729 // gets installed/deleted. Handle non-buddies only.
1730 if ( ! citem.buddy() )
1732 if ( citem->isKind<Product>() )
1734 Product::constPtr p = citem->asKind<Product>();
1735 if ( citem.status().isToBeInstalled() )
1737 ERR << "Can't install orphan product without release-package! " << citem << endl;
1741 // Deleting the corresponding product entry is all we con do.
1742 // So the product will no longer be visible as installed.
1743 std::string referenceFilename( p->referenceFilename() );
1744 if ( referenceFilename.empty() )
1746 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1750 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1751 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1753 ERR << "Delete orphan product failed: " << referenceFile << endl;
1758 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1760 // SrcPackage is install-only
1761 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1762 installSrcPackage( p );
1765 citem.status().resetTransact( ResStatus::USER );
1766 step->stepStage( sat::Transaction::STEP_DONE );
1769 } // other resolvables
1773 // process all remembered posttrans scripts.
1775 postTransCollector.executeScripts();
1777 postTransCollector.discardScripts();
1779 // Check presence of update scripts/messages. If aborting,
1780 // at least log omitted scripts.
1781 if ( ! successfullyInstalledPackages.empty() )
1783 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1784 successfullyInstalledPackages, abort ) )
1786 WAR << "Commit aborted by the user" << endl;
1789 // send messages after scripts in case some script generates output,
1790 // that should be kept in t %ghost message file.
1791 RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1792 successfullyInstalledPackages,
1798 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1802 ///////////////////////////////////////////////////////////////////
1804 rpm::RpmDb & TargetImpl::rpm()
1809 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1811 return _rpm.hasFile(path_str, name_str);
1815 Date TargetImpl::timestamp() const
1817 return _rpm.timestamp();
1820 ///////////////////////////////////////////////////////////////////
1823 parser::ProductFileData baseproductdata( const Pathname & root_r )
1825 parser::ProductFileData ret;
1826 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1828 if ( baseproduct.isFile() )
1832 ret = parser::ProductFileReader::scanFile( baseproduct.path() );
1834 catch ( const Exception & excpt )
1836 ZYPP_CAUGHT( excpt );
1839 else if ( PathInfo( Pathname::assertprefix( root_r, "/etc/products.d" ) ).isDir() )
1841 ERR << "baseproduct symlink is dangling or missing: " << baseproduct << endl;
1846 inline Pathname staticGuessRoot( const Pathname & root_r )
1848 if ( root_r.empty() )
1850 // empty root: use existing Target or assume "/"
1851 Pathname ret ( ZConfig::instance().systemRoot() );
1853 return Pathname("/");
1859 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1861 std::ifstream idfile( file_r.c_str() );
1862 for( iostr::EachLine in( idfile ); in; in.next() )
1864 std::string line( str::trim( *in ) );
1865 if ( ! line.empty() )
1868 return std::string();
1871 ///////////////////////////////////////////////////////////////////
1873 Product::constPtr TargetImpl::baseProduct() const
1875 ResPool pool(ResPool::instance());
1876 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1878 Product::constPtr p = (*it)->asKind<Product>();
1879 if ( p->isTargetDistribution() )
1885 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1887 const Pathname needroot( staticGuessRoot(root_r) );
1888 const Target_constPtr target( getZYpp()->getTarget() );
1889 if ( target && target->root() == needroot )
1890 return target->requestedLocales();
1891 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1894 std::string TargetImpl::targetDistribution() const
1895 { return baseproductdata( _root ).registerTarget(); }
1897 std::string TargetImpl::targetDistribution( const Pathname & root_r )
1898 { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1900 std::string TargetImpl::targetDistributionRelease() const
1901 { return baseproductdata( _root ).registerRelease(); }
1903 std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1904 { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1906 std::string TargetImpl::targetDistributionFlavor() const
1907 { return baseproductdata( _root ).registerFlavor(); }
1909 std::string TargetImpl::targetDistributionFlavor( const Pathname & root_r )
1910 { return baseproductdata( staticGuessRoot(root_r) ).registerFlavor();}
1912 Target::DistributionLabel TargetImpl::distributionLabel() const
1914 Target::DistributionLabel ret;
1915 parser::ProductFileData pdata( baseproductdata( _root ) );
1916 ret.shortName = pdata.shortName();
1917 ret.summary = pdata.summary();
1921 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1923 Target::DistributionLabel ret;
1924 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1925 ret.shortName = pdata.shortName();
1926 ret.summary = pdata.summary();
1930 std::string TargetImpl::distributionVersion() const
1932 if ( _distributionVersion.empty() )
1934 _distributionVersion = TargetImpl::distributionVersion(root());
1935 if ( !_distributionVersion.empty() )
1936 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1938 return _distributionVersion;
1941 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1943 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1944 if ( distributionVersion.empty() )
1946 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1947 // On RHEL, Fedora and others the "product version" is determined by the first package
1948 // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1949 // with the $distroverpkg variable.
1950 scoped_ptr<rpm::RpmDb> tmprpmdb;
1951 if ( ZConfig::instance().systemRoot() == Pathname() )
1955 tmprpmdb.reset( new rpm::RpmDb );
1956 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1963 rpm::librpmDb::db_const_iterator it;
1964 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1965 distributionVersion = it->tag_version();
1967 return distributionVersion;
1971 std::string TargetImpl::distributionFlavor() const
1973 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1976 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1978 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1981 ///////////////////////////////////////////////////////////////////
1983 std::string TargetImpl::anonymousUniqueId() const
1985 return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1988 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1990 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1993 ///////////////////////////////////////////////////////////////////
1995 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1997 // provide on local disk
1998 ManagedFile localfile = provideSrcPackage(srcPackage_r);
2000 rpm().installPackage ( localfile );
2003 ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
2005 // provide on local disk
2006 repo::RepoMediaAccess access_r;
2007 repo::SrcPackageProvider prov( access_r );
2008 return prov.provideSrcPackage( srcPackage_r );
2010 ////////////////////////////////////////////////////////////////
2011 } // namespace target
2012 ///////////////////////////////////////////////////////////////////
2013 /////////////////////////////////////////////////////////////////
2015 ///////////////////////////////////////////////////////////////////