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"
33 #include "zypp/PathInfo.h"
35 #include "zypp/PoolItem.h"
36 #include "zypp/ResObjects.h"
38 #include "zypp/TmpPath.h"
39 #include "zypp/RepoStatus.h"
40 #include "zypp/ExternalProgram.h"
41 #include "zypp/Repository.h"
42 #include "zypp/ShutdownLock_p.h"
44 #include "zypp/ResFilters.h"
45 #include "zypp/HistoryLog.h"
46 #include "zypp/target/TargetImpl.h"
47 #include "zypp/target/TargetCallbackReceiver.h"
48 #include "zypp/target/rpm/librpmDb.h"
49 #include "zypp/target/CommitPackageCache.h"
50 #include "zypp/target/RpmPostTransCollector.h"
52 #include "zypp/parser/ProductFileReader.h"
53 #include "zypp/repo/SrcPackageProvider.h"
55 #include "zypp/sat/Pool.h"
56 #include "zypp/sat/detail/PoolImpl.h"
57 #include "zypp/sat/Transaction.h"
59 #include "zypp/PluginExecutor.h"
63 ///////////////////////////////////////////////////////////////////
66 /////////////////////////////////////////////////////////////////
69 // HACK for bnc#906096: let pool re-evaluate multiversion spec
70 // if target root changes. ZConfig returns data sensitive to
71 // current target root.
72 inline void sigMultiversionSpecChanged()
74 sat::detail::PoolMember::myPool().multiversionSpecChanged();
77 /////////////////////////////////////////////////////////////////
79 ///////////////////////////////////////////////////////////////////
82 // Lazy via template specialisation / should switch to overloading
85 inline std::string toJSON( const ZYppCommitResult::TransactionStepList & steps_r )
87 using sat::Transaction;
90 for ( const Transaction::Step & step : steps_r )
91 // ignore implicit deletes due to obsoletes and non-package actions
92 if ( step.stepType() != Transaction::TRANSACTION_IGNORE )
98 /** See \ref commitbegin on page \ref plugin-commit for the specs. */
100 inline std::string toJSON( const sat::Transaction::Step & step_r )
102 static const std::string strType( "type" );
103 static const std::string strStage( "stage" );
104 static const std::string strSolvable( "solvable" );
106 static const std::string strTypeDel( "-" );
107 static const std::string strTypeIns( "+" );
108 static const std::string strTypeMul( "M" );
110 static const std::string strStageDone( "ok" );
111 static const std::string strStageFailed( "err" );
113 static const std::string strSolvableN( "n" );
114 static const std::string strSolvableE( "e" );
115 static const std::string strSolvableV( "v" );
116 static const std::string strSolvableR( "r" );
117 static const std::string strSolvableA( "a" );
119 using sat::Transaction;
122 switch ( step_r.stepType() )
124 case Transaction::TRANSACTION_IGNORE: /*empty*/ break;
125 case Transaction::TRANSACTION_ERASE: ret.add( strType, strTypeDel ); break;
126 case Transaction::TRANSACTION_INSTALL: ret.add( strType, strTypeIns ); break;
127 case Transaction::TRANSACTION_MULTIINSTALL: ret.add( strType, strTypeMul ); break;
130 switch ( step_r.stepStage() )
132 case Transaction::STEP_TODO: /*empty*/ break;
133 case Transaction::STEP_DONE: ret.add( strStage, strStageDone ); break;
134 case Transaction::STEP_ERROR: ret.add( strStage, strStageFailed ); break;
141 if ( sat::Solvable solv = step_r.satSolvable() )
143 ident = solv.ident();
149 // deleted package; post mortem data stored in Transaction::Step
150 ident = step_r.ident();
151 ed = step_r.edition();
152 arch = step_r.arch();
156 { strSolvableN, ident.asString() },
157 { strSolvableV, ed.version() },
158 { strSolvableR, ed.release() },
159 { strSolvableA, arch.asString() }
161 if ( Edition::epoch_t epoch = ed.epoch() )
162 s.add( strSolvableE, epoch );
164 ret.add( strSolvable, s );
170 ///////////////////////////////////////////////////////////////////
172 ///////////////////////////////////////////////////////////////////
175 ///////////////////////////////////////////////////////////////////
178 SolvIdentFile::Data getUserInstalledFromHistory( const Pathname & historyFile_r )
180 SolvIdentFile::Data onSystemByUserList;
181 // go and parse it: 'who' must constain an '@', then it was installed by user request.
182 // 2009-09-29 07:25:19|install|lirc-remotes|0.8.5-3.2|x86_64|root@opensuse|InstallationImage|a204211eb0...
183 std::ifstream infile( historyFile_r.c_str() );
184 for( iostr::EachLine in( infile ); in; in.next() )
186 const char * ch( (*in).c_str() );
188 if ( *ch < '1' || '9' < *ch )
190 const char * sep1 = ::strchr( ch, '|' ); // | after date
194 // if logs an install or delete
195 bool installs = true;
196 if ( ::strncmp( sep1, "install|", 8 ) )
198 if ( ::strncmp( sep1, "remove |", 8 ) )
199 continue; // no install and no remove
201 installs = false; // remove
203 sep1 += 8; // | after what
204 // get the package name
205 const char * sep2 = ::strchr( sep1, '|' ); // | after name
206 if ( !sep2 || sep1 == sep2 )
208 (*in)[sep2-ch] = '\0';
209 IdString pkg( sep1 );
210 // we're done, if a delete
213 onSystemByUserList.erase( pkg );
216 // now guess whether user installed or not (3rd next field contains 'user@host')
217 if ( (sep1 = ::strchr( sep2+1, '|' )) // | after version
218 && (sep1 = ::strchr( sep1+1, '|' )) // | after arch
219 && (sep2 = ::strchr( sep1+1, '|' )) ) // | after who
221 (*in)[sep2-ch] = '\0';
222 if ( ::strchr( sep1+1, '@' ) )
225 onSystemByUserList.insert( pkg );
230 MIL << "onSystemByUserList found: " << onSystemByUserList.size() << endl;
231 return onSystemByUserList;
234 ///////////////////////////////////////////////////////////////////
236 ///////////////////////////////////////////////////////////////////
239 inline PluginFrame transactionPluginFrame( const std::string & command_r, ZYppCommitResult::TransactionStepList & steps_r )
241 return PluginFrame( command_r, json::Object {
242 { "TransactionStepList", steps_r }
246 ///////////////////////////////////////////////////////////////////
248 /** \internal Manage writing a new testcase when doing an upgrade. */
249 void writeUpgradeTestcase()
251 unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
252 MIL << "Testcases to keep: " << toKeep << endl;
255 Target_Ptr target( getZYpp()->getTarget() );
258 WAR << "No Target no Testcase!" << endl;
262 std::string stem( "updateTestcase" );
263 Pathname dir( target->assertRootPrefix("/var/log/") );
264 Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
267 std::list<std::string> content;
268 filesystem::readdir( content, dir, /*dots*/false );
269 std::set<std::string> cases;
270 for_( c, content.begin(), content.end() )
272 if ( str::startsWith( *c, stem ) )
275 if ( cases.size() >= toKeep )
277 unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
278 for_( c, cases.begin(), cases.end() )
280 filesystem::recursive_rmdir( dir/(*c) );
287 MIL << "Write new testcase " << next << endl;
288 getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
291 ///////////////////////////////////////////////////////////////////
293 { /////////////////////////////////////////////////////////////////
295 /** Execute script and report against report_r.
296 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
297 * execution was successfull (<tt>first = true</tt>), or the desired
298 * \c PatchScriptReport::Action in case execution failed
299 * (<tt>first = false</tt>).
301 * \note The packager is responsible for setting the correct permissions
302 * of the script. If the script is not executable it is reported as an
303 * error. We must not modify the permessions.
305 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
306 const Pathname & script_r,
307 callback::SendReport<PatchScriptReport> & report_r )
309 MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
311 HistoryLog historylog;
312 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
313 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
315 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
317 historylog.comment(output);
318 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
320 WAR << "User request to abort script " << script_r << endl;
322 // the rest is handled by exit code evaluation
323 // in case the script has meanwhile finished.
327 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
329 if ( prog.close() != 0 )
331 ret.second = report_r->problem( prog.execError() );
332 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
333 std::ostringstream sstr;
334 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
335 historylog.comment(sstr.str(), /*timestamp*/true);
344 /** Execute script and report against report_r.
345 * Return \c false if user requested \c ABORT.
347 bool executeScript( const Pathname & root_r,
348 const Pathname & script_r,
349 callback::SendReport<PatchScriptReport> & report_r )
351 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
354 action = doExecuteScript( root_r, script_r, report_r );
356 return true; // success
358 switch ( action.second )
360 case PatchScriptReport::ABORT:
361 WAR << "User request to abort at script " << script_r << endl;
362 return false; // requested abort.
365 case PatchScriptReport::IGNORE:
366 WAR << "User request to skip script " << script_r << endl;
367 return true; // requested skip.
370 case PatchScriptReport::RETRY:
373 } while ( action.second == PatchScriptReport::RETRY );
375 // THIS is not intended to be reached:
376 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
377 return false; // abort.
380 /** Look for update scripts named 'name-version-release-*' and
381 * execute them. Return \c false if \c ABORT was requested.
383 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
385 bool RunUpdateScripts( const Pathname & root_r,
386 const Pathname & scriptsPath_r,
387 const std::vector<sat::Solvable> & checkPackages_r,
390 if ( checkPackages_r.empty() )
391 return true; // no installed packages to check
393 MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
394 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
395 if ( ! PathInfo( scriptsDir ).isDir() )
396 return true; // no script dir
398 std::list<std::string> scripts;
399 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
400 if ( scripts.empty() )
401 return true; // no scripts in script dir
403 // Now collect and execute all matching scripts.
404 // On ABORT: at least log all outstanding scripts.
405 // - "name-version-release"
406 // - "name-version-release-*"
408 std::map<std::string, Pathname> unify; // scripts <md5,path>
409 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
411 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
412 for_( sit, scripts.begin(), scripts.end() )
414 if ( ! str::hasPrefix( *sit, prefix ) )
417 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
418 continue; // if not exact match it had to continue with '-'
420 PathInfo script( scriptsDir / *sit );
421 Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
422 std::string unifytag; // must not stay empty
424 if ( script.isFile() )
426 // Assert it's set executable, unify by md5sum.
427 filesystem::addmod( script.path(), 0500 );
428 unifytag = filesystem::md5sum( script.path() );
430 else if ( ! script.isExist() )
432 // Might be a dangling symlink, might be ok if we are in
433 // instsys (absolute symlink within the system below /mnt).
434 // readlink will tell....
435 unifytag = filesystem::readlink( script.path() ).asString();
438 if ( unifytag.empty() )
442 if ( unify[unifytag].empty() )
444 unify[unifytag] = localPath;
448 // translators: We may find the same script content in files with different names.
449 // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
450 // message for a log file. Preferably start translation with "%s"
451 std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
452 MIL << "Skip update script: " << msg << endl;
453 HistoryLog().comment( msg, /*timestamp*/true );
457 if ( abort || aborting_r )
459 WAR << "Aborting: Skip update script " << *sit << endl;
460 HistoryLog().comment(
461 localPath.asString() + _(" execution skipped while aborting"),
466 MIL << "Found update script " << *sit << endl;
467 callback::SendReport<PatchScriptReport> report;
468 report->start( make<Package>( *it ), script.path() );
470 if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
471 abort = true; // requested abort.
478 ///////////////////////////////////////////////////////////////////
480 ///////////////////////////////////////////////////////////////////
482 inline void copyTo( std::ostream & out_r, const Pathname & file_r )
484 std::ifstream infile( file_r.c_str() );
485 for( iostr::EachLine in( infile ); in; in.next() )
487 out_r << *in << endl;
491 inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
493 std::string ret( cmd_r );
494 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
495 SUBST_IF( "%p", notification_r.solvable().asString() );
496 SUBST_IF( "%P", notification_r.file().asString() );
501 void sendNotification( const Pathname & root_r,
502 const UpdateNotifications & notifications_r )
504 if ( notifications_r.empty() )
507 std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
508 MIL << "Notification command is '" << cmdspec << "'" << endl;
509 if ( cmdspec.empty() )
512 std::string::size_type pos( cmdspec.find( '|' ) );
513 if ( pos == std::string::npos )
515 ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
516 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
520 std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
521 std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
523 enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
524 Format format = UNKNOWN;
525 if ( formatStr == "none" )
527 else if ( formatStr == "single" )
529 else if ( formatStr == "digest" )
531 else if ( formatStr == "bulk" )
535 ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
536 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
540 // Take care: commands are ececuted chroot(root_r). The message file
541 // pathnames in notifications_r are local to root_r. For physical access
542 // to the file they need to be prefixed.
544 if ( format == NONE || format == SINGLE )
546 for_( it, notifications_r.begin(), notifications_r.end() )
548 std::vector<std::string> command;
549 if ( format == SINGLE )
550 command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
551 str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
553 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
554 if ( true ) // Wait for feedback
556 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
560 int ret = prog.close();
563 ERR << "Notification command returned with error (" << ret << ")." << endl;
564 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
570 else if ( format == DIGEST || format == BULK )
572 filesystem::TmpFile tmpfile;
573 ofstream out( tmpfile.path().c_str() );
574 for_( it, notifications_r.begin(), notifications_r.end() )
576 if ( format == DIGEST )
578 out << it->file() << endl;
580 else if ( format == BULK )
582 copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
586 std::vector<std::string> command;
587 command.push_back( "<"+tmpfile.path().asString() ); // redirect input
588 str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
590 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
591 if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
593 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
597 int ret = prog.close();
600 ERR << "Notification command returned with error (" << ret << ")." << endl;
601 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
608 INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
609 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
615 /** Look for update messages named 'name-version-release-*' and
616 * send notification according to \ref ZConfig::updateMessagesNotify.
618 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
620 void RunUpdateMessages( const Pathname & root_r,
621 const Pathname & messagesPath_r,
622 const std::vector<sat::Solvable> & checkPackages_r,
623 ZYppCommitResult & result_r )
625 if ( checkPackages_r.empty() )
626 return; // no installed packages to check
628 MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
629 Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
630 if ( ! PathInfo( messagesDir ).isDir() )
631 return; // no messages dir
633 std::list<std::string> messages;
634 filesystem::readdir( messages, messagesDir, /*dots*/false );
635 if ( messages.empty() )
636 return; // no messages in message dir
638 // Now collect all matching messages in result and send them
639 // - "name-version-release"
640 // - "name-version-release-*"
641 HistoryLog historylog;
642 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
644 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
645 for_( sit, messages.begin(), messages.end() )
647 if ( ! str::hasPrefix( *sit, prefix ) )
650 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
651 continue; // if not exact match it had to continue with '-'
653 PathInfo message( messagesDir / *sit );
654 if ( ! message.isFile() || message.size() == 0 )
657 MIL << "Found update message " << *sit << endl;
658 Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
659 result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
660 historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
663 sendNotification( root_r, result_r.updateMessages() );
666 /////////////////////////////////////////////////////////////////
668 ///////////////////////////////////////////////////////////////////
670 void XRunUpdateMessages( const Pathname & root_r,
671 const Pathname & messagesPath_r,
672 const std::vector<sat::Solvable> & checkPackages_r,
673 ZYppCommitResult & result_r )
674 { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
676 ///////////////////////////////////////////////////////////////////
678 IMPL_PTR_TYPE(TargetImpl);
680 ///////////////////////////////////////////////////////////////////
682 // METHOD NAME : TargetImpl::TargetImpl
683 // METHOD TYPE : Ctor
685 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
687 , _requestedLocalesFile( home() / "RequestedLocales" )
688 , _autoInstalledFile( home() / "AutoInstalled" )
689 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
691 _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
693 HistoryLog::setRoot(_root);
696 sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
697 MIL << "Initialized target on " << _root << endl;
701 * generates a random id using uuidgen
703 static std::string generateRandomId()
705 std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
706 return iostr::getline( uuidprovider );
710 * updates the content of \p filename
711 * if \p condition is true, setting the content
712 * the the value returned by \p value
714 void updateFileContent( const Pathname &filename,
715 boost::function<bool ()> condition,
716 boost::function<string ()> value )
718 string val = value();
719 // if the value is empty, then just dont
720 // do anything, regardless of the condition
726 MIL << "updating '" << filename << "' content." << endl;
728 // if the file does not exist we need to generate the uuid file
730 std::ofstream filestr;
731 // make sure the path exists
732 filesystem::assert_dir( filename.dirname() );
733 filestr.open( filename.c_str() );
735 if ( filestr.good() )
742 // FIXME, should we ignore the error?
743 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
748 /** helper functor */
749 static bool fileMissing( const Pathname &pathname )
751 return ! PathInfo(pathname).isExist();
754 void TargetImpl::createAnonymousId() const
756 // bsc#1024741: Omit creating a new uid for chrooted systems (if it already has one, fine)
760 // Create the anonymous unique id, used for download statistics
761 Pathname idpath( home() / "AnonymousUniqueId");
765 updateFileContent( idpath,
766 boost::bind(fileMissing, idpath),
769 catch ( const Exception &e )
771 WAR << "Can't create anonymous id file" << endl;
776 void TargetImpl::createLastDistributionFlavorCache() const
778 // create the anonymous unique id
779 // this value is used for statistics
780 Pathname flavorpath( home() / "LastDistributionFlavor");
782 // is there a product
783 Product::constPtr p = baseProduct();
786 WAR << "No base product, I won't create flavor cache" << endl;
790 string flavor = p->flavor();
795 updateFileContent( flavorpath,
796 // only if flavor is not empty
797 functor::Constant<bool>( ! flavor.empty() ),
798 functor::Constant<string>(flavor) );
800 catch ( const Exception &e )
802 WAR << "Can't create flavor cache" << endl;
807 ///////////////////////////////////////////////////////////////////
809 // METHOD NAME : TargetImpl::~TargetImpl
810 // METHOD TYPE : Dtor
812 TargetImpl::~TargetImpl()
814 _rpm.closeDatabase();
815 sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
816 MIL << "Targets closed" << endl;
819 ///////////////////////////////////////////////////////////////////
821 // solv file handling
823 ///////////////////////////////////////////////////////////////////
825 Pathname TargetImpl::defaultSolvfilesPath() const
827 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
830 void TargetImpl::clearCache()
832 Pathname base = solvfilesPath();
833 filesystem::recursive_rmdir( base );
836 bool TargetImpl::buildCache()
838 Pathname base = solvfilesPath();
839 Pathname rpmsolv = base/"solv";
840 Pathname rpmsolvcookie = base/"cookie";
842 bool build_rpm_solv = true;
843 // lets see if the rpm solv cache exists
845 RepoStatus rpmstatus( RepoStatus(_root/"var/lib/rpm/Name") && RepoStatus(_root/"etc/products.d") );
847 bool solvexisted = PathInfo(rpmsolv).isExist();
850 // see the status of the cache
851 PathInfo cookie( rpmsolvcookie );
852 MIL << "Read cookie: " << cookie << endl;
853 if ( cookie.isExist() )
855 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
856 // now compare it with the rpm database
857 if ( status == rpmstatus )
858 build_rpm_solv = false;
859 MIL << "Read cookie: " << rpmsolvcookie << " says: "
860 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
864 if ( build_rpm_solv )
866 // if the solvfile dir does not exist yet, we better create it
867 filesystem::assert_dir( base );
869 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
871 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
874 // Can't create temporary solv file, usually due to insufficient permission
875 // (user query while @System solv needs refresh). If so, try switching
876 // to a location within zypps temp. space (will be cleaned at application end).
878 bool switchingToTmpSolvfile = false;
879 Exception ex("Failed to cache rpm database.");
880 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
882 if ( ! solvfilesPathIsTemp() )
884 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
885 rpmsolv = base/"solv";
886 rpmsolvcookie = base/"cookie";
888 filesystem::assert_dir( base );
889 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
893 WAR << "Using a temporary solv file at " << base << endl;
894 switchingToTmpSolvfile = true;
895 _tmpSolvfilesPath = base;
899 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
903 if ( ! switchingToTmpSolvfile )
909 // Take care we unlink the solvfile on exception
910 ManagedFile guard( base, filesystem::recursive_rmdir );
912 ExternalProgram::Arguments cmd;
913 cmd.push_back( "rpmdb2solv" );
914 if ( ! _root.empty() ) {
915 cmd.push_back( "-r" );
916 cmd.push_back( _root.asString() );
918 cmd.push_back( "-X" ); // autogenerate pattern/product/... from -package
919 // bsc#1104415: no more application support // cmd.push_back( "-A" ); // autogenerate application pseudo packages
920 cmd.push_back( "-p" );
921 cmd.push_back( Pathname::assertprefix( _root, "/etc/products.d" ).asString() );
923 if ( ! oldSolvFile.empty() )
924 cmd.push_back( oldSolvFile.asString() );
926 cmd.push_back( "-o" );
927 cmd.push_back( tmpsolv.path().asString() );
929 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
930 std::string errdetail;
932 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
933 WAR << " " << output;
934 if ( errdetail.empty() ) {
935 errdetail = prog.command();
941 int ret = prog.close();
944 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
945 ex.remember( errdetail );
949 ret = filesystem::rename( tmpsolv, rpmsolv );
951 ZYPP_THROW(Exception("Failed to move cache to final destination"));
952 // if this fails, don't bother throwing exceptions
953 filesystem::chmod( rpmsolv, 0644 );
955 rpmstatus.saveToCookieFile(rpmsolvcookie);
958 guard.resetDispose();
959 sat::updateSolvFileIndex( rpmsolv ); // content digest for zypper bash completion
961 // system-hook: Finally send notification to plugins
964 PluginExecutor plugins;
965 plugins.load( ZConfig::instance().pluginsPath()/"system" );
967 plugins.send( PluginFrame( "PACKAGESETCHANGED" ) );
972 // On the fly add missing solv.idx files for bash completion.
973 if ( ! PathInfo(base/"solv.idx").isExist() )
974 sat::updateSolvFileIndex( rpmsolv );
976 return build_rpm_solv;
979 void TargetImpl::reload()
984 void TargetImpl::unload()
986 Repository system( sat::Pool::instance().findSystemRepo() );
988 system.eraseFromPool();
991 void TargetImpl::load( bool force )
993 bool newCache = buildCache();
994 MIL << "New cache built: " << (newCache?"true":"false") <<
995 ", force loading: " << (force?"true":"false") << endl;
997 // now add the repos to the pool
998 sat::Pool satpool( sat::Pool::instance() );
999 Pathname rpmsolv( solvfilesPath() / "solv" );
1000 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
1002 // Providing an empty system repo, unload any old content
1003 Repository system( sat::Pool::instance().findSystemRepo() );
1005 if ( system && ! system.solvablesEmpty() )
1007 if ( newCache || force )
1009 system.eraseFromPool(); // invalidates system
1013 return; // nothing to do
1019 system = satpool.systemRepo();
1024 MIL << "adding " << rpmsolv << " to system" << endl;
1025 system.addSolv( rpmsolv );
1027 catch ( const Exception & exp )
1030 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1034 system.addSolv( rpmsolv );
1036 satpool.rootDir( _root );
1038 // (Re)Load the requested locales et al.
1039 // If the requested locales are empty, we leave the pool untouched
1040 // to avoid undoing changes the application applied. We expect this
1041 // to happen on a bare metal installation only. An already existing
1042 // target should be loaded before its settings are changed.
1044 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1045 if ( ! requestedLocales.empty() )
1047 satpool.initRequestedLocales( requestedLocales );
1051 if ( ! PathInfo( _autoInstalledFile.file() ).isExist() )
1053 // Initialize from history, if it does not exist
1054 Pathname historyFile( Pathname::assertprefix( _root, ZConfig::instance().historyLogFile() ) );
1055 if ( PathInfo( historyFile ).isExist() )
1057 SolvIdentFile::Data onSystemByUser( getUserInstalledFromHistory( historyFile ) );
1058 SolvIdentFile::Data onSystemByAuto;
1059 for_( it, system.solvablesBegin(), system.solvablesEnd() )
1061 IdString ident( (*it).ident() );
1062 if ( onSystemByUser.find( ident ) == onSystemByUser.end() )
1063 onSystemByAuto.insert( ident );
1065 _autoInstalledFile.setData( onSystemByAuto );
1067 // on the fly removed any obsolete SoftLocks file
1068 filesystem::unlink( home() / "SoftLocks" );
1070 // read from AutoInstalled file
1072 for ( const auto & idstr : _autoInstalledFile.data() )
1073 q.push( idstr.id() );
1074 satpool.setAutoInstalled( q );
1077 //load the packages that will trigger the update flag being set
1080 filesystem::Pathname needRebootFile { Pathname::assertprefix( root(), ZConfig::instance().needrebootFile() ) };
1081 if ( filesystem::PathInfo ( needRebootFile ).isExist() ) {
1082 SolvIdentFile file ( needRebootFile );
1083 for ( const auto & idstr : file.data() ) {
1084 q.push( idstr.id() );
1087 #warning Hotfix: temp workaround missing SolvableSpec Parser
1088 // Also consider excluding .rpmnew/.rpmsave/.rpmorig files in needreboot.d
1089 q.push( IdString("kernel-azure").id() );
1090 q.push( IdString("kernel-azure-base").id() );
1091 q.push( IdString("kernel-debug").id() );
1092 q.push( IdString("kernel-debug-base").id() );
1093 q.push( IdString("kernel-default").id() );
1094 q.push( IdString("kernel-default-base").id() );
1095 q.push( IdString("kernel-kvmsmall").id() );
1096 q.push( IdString("kernel-kvmsmall-base").id() );
1097 q.push( IdString("kernel-rt").id() );
1098 q.push( IdString("kernel-rt-base").id() );
1099 q.push( IdString("kernel-rt_debug").id() );
1100 q.push( IdString("kernel-rt_debug-base").id() );
1101 q.push( IdString("kernel-vanilla").id() );
1102 q.push( IdString("kernel-vanilla-base").id() );
1106 filesystem::Pathname needRebootDir { Pathname::assertprefix( root(), ZConfig::instance().needrebootPath() ) };
1107 if ( filesystem::PathInfo ( needRebootDir ).isExist() ) {
1108 filesystem::DirContent ls;
1109 filesystem::readdir( ls, needRebootDir, false );
1111 for ( const filesystem::DirEntry &entry : ls ) {
1113 if ( entry.type != filesystem::FT_FILE )
1116 SolvIdentFile file ( needRebootDir / entry.name );
1117 for ( const auto & idstr : file.data() ) {
1118 q.push( idstr.id() );
1123 satpool.setRebootNeededIdents( q );
1126 if ( ZConfig::instance().apply_locks_file() )
1128 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1129 if ( ! hardLocks.empty() )
1131 ResPool::instance().setHardLockQueries( hardLocks );
1135 // now that the target is loaded, we can cache the flavor
1136 createLastDistributionFlavorCache();
1138 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1141 ///////////////////////////////////////////////////////////////////
1145 ///////////////////////////////////////////////////////////////////
1146 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1148 // ----------------------------------------------------------------- //
1149 ZYppCommitPolicy policy_r( policy_rX );
1150 ShutdownLock lck("Zypp commit running.");
1152 // Fake outstanding YCP fix: Honour restriction to media 1
1153 // at installation, but install all remaining packages if post-boot.
1154 if ( policy_r.restrictToMedia() > 1 )
1155 policy_r.allMedia();
1157 if ( policy_r.downloadMode() == DownloadDefault ) {
1158 if ( root() == "/" )
1159 policy_r.downloadMode(DownloadInHeaps);
1161 policy_r.downloadMode(DownloadAsNeeded);
1163 // DownloadOnly implies dry-run.
1164 else if ( policy_r.downloadMode() == DownloadOnly )
1165 policy_r.dryRun( true );
1166 // ----------------------------------------------------------------- //
1168 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1170 ///////////////////////////////////////////////////////////////////
1171 // Compute transaction:
1172 ///////////////////////////////////////////////////////////////////
1173 ZYppCommitResult result( root() );
1174 result.rTransaction() = pool_r.resolver().getTransaction();
1175 result.rTransaction().order();
1176 // steps: this is our todo-list
1177 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1178 if ( policy_r.restrictToMedia() )
1180 // Collect until the 1st package from an unwanted media occurs.
1181 // Further collection could violate install order.
1182 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1183 for_( it, result.transaction().begin(), result.transaction().end() )
1185 if ( makeResObject( *it )->mediaNr() > 1 )
1187 steps.push_back( *it );
1192 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1194 MIL << "Todo: " << result << endl;
1196 ///////////////////////////////////////////////////////////////////
1197 // Prepare execution of commit plugins:
1198 ///////////////////////////////////////////////////////////////////
1199 PluginExecutor commitPlugins;
1200 if ( root() == "/" && ! policy_r.dryRun() )
1202 commitPlugins.load( ZConfig::instance().pluginsPath()/"commit" );
1204 if ( commitPlugins )
1205 commitPlugins.send( transactionPluginFrame( "COMMITBEGIN", steps ) );
1207 ///////////////////////////////////////////////////////////////////
1208 // Write out a testcase if we're in dist upgrade mode.
1209 ///////////////////////////////////////////////////////////////////
1210 if ( pool_r.resolver().upgradeMode() || pool_r.resolver().upgradingRepos() )
1212 if ( ! policy_r.dryRun() )
1214 writeUpgradeTestcase();
1218 DBG << "dryRun: Not writing upgrade testcase." << endl;
1222 ///////////////////////////////////////////////////////////////////
1223 // Store non-package data:
1224 ///////////////////////////////////////////////////////////////////
1225 if ( ! policy_r.dryRun() )
1227 filesystem::assert_dir( home() );
1228 // requested locales
1229 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1232 SolvIdentFile::Data newdata;
1233 for ( sat::Queue::value_type id : result.rTransaction().autoInstalled() )
1234 newdata.insert( IdString(id) );
1235 _autoInstalledFile.setData( newdata );
1238 if ( ZConfig::instance().apply_locks_file() )
1240 HardLocksFile::Data newdata;
1241 pool_r.getHardLockQueries( newdata );
1242 _hardLocksFile.setData( newdata );
1247 DBG << "dryRun: Not stroring non-package data." << endl;
1250 ///////////////////////////////////////////////////////////////////
1251 // First collect and display all messages
1252 // associated with patches to be installed.
1253 ///////////////////////////////////////////////////////////////////
1254 if ( ! policy_r.dryRun() )
1256 for_( it, steps.begin(), steps.end() )
1258 if ( ! it->satSolvable().isKind<Patch>() )
1262 if ( ! pi.status().isToBeInstalled() )
1265 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1266 if ( ! patch ||patch->message().empty() )
1269 MIL << "Show message for " << patch << endl;
1270 callback::SendReport<target::PatchMessageReport> report;
1271 if ( ! report->show( patch ) )
1273 WAR << "commit aborted by the user" << endl;
1274 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1280 DBG << "dryRun: Not checking patch messages." << endl;
1283 ///////////////////////////////////////////////////////////////////
1284 // Remove/install packages.
1285 ///////////////////////////////////////////////////////////////////
1286 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1287 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1289 // Prepare the package cache. Pass all items requiring download.
1290 CommitPackageCache packageCache;
1291 packageCache.setCommitList( steps.begin(), steps.end() );
1294 if ( policy_r.downloadMode() != DownloadAsNeeded )
1296 // Preload the cache. Until now this means pre-loading all packages.
1297 // Once DownloadInHeaps is fully implemented, this will change and
1298 // we may actually have more than one heap.
1299 for_( it, steps.begin(), steps.end() )
1301 switch ( it->stepType() )
1303 case sat::Transaction::TRANSACTION_INSTALL:
1304 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1305 // proceed: only install actionas may require download.
1309 // next: no download for or non-packages and delete actions.
1315 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1317 ManagedFile localfile;
1320 localfile = packageCache.get( pi );
1321 localfile.resetDispose(); // keep the package file in the cache
1323 catch ( const AbortRequestException & exp )
1325 it->stepStage( sat::Transaction::STEP_ERROR );
1327 WAR << "commit cache preload aborted by the user" << endl;
1328 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1331 catch ( const SkipRequestException & exp )
1334 it->stepStage( sat::Transaction::STEP_ERROR );
1336 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1339 catch ( const Exception & exp )
1341 // bnc #395704: missing catch causes abort.
1342 // TODO see if packageCache fails to handle errors correctly.
1344 it->stepStage( sat::Transaction::STEP_ERROR );
1346 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1351 packageCache.preloaded( true ); // try to avoid duplicate infoInCache CBs in commit
1356 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1360 if ( ! policy_r.dryRun() )
1362 // if cache is preloaded, check for file conflicts
1363 commitFindFileConflicts( policy_r, result );
1364 commit( policy_r, packageCache, result );
1368 DBG << "dryRun/downloadOnly: Not installing/deleting anything." << endl;
1374 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1377 ///////////////////////////////////////////////////////////////////
1378 // Send result to commit plugins:
1379 ///////////////////////////////////////////////////////////////////
1380 if ( commitPlugins )
1381 commitPlugins.send( transactionPluginFrame( "COMMITEND", steps ) );
1383 ///////////////////////////////////////////////////////////////////
1384 // Try to rebuild solv file while rpm database is still in cache
1385 ///////////////////////////////////////////////////////////////////
1386 if ( ! policy_r.dryRun() )
1391 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1395 ///////////////////////////////////////////////////////////////////
1399 ///////////////////////////////////////////////////////////////////
1402 struct NotifyAttemptToModify
1404 NotifyAttemptToModify( ZYppCommitResult & result_r ) : _result( result_r ) {}
1407 { if ( _guard ) { _result.attemptToModify( true ); _guard = false; } }
1410 ZYppCommitResult & _result;
1414 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1415 CommitPackageCache & packageCache_r,
1416 ZYppCommitResult & result_r )
1418 // steps: this is our todo-list
1419 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1420 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1422 HistoryLog().stampCommand();
1424 // Send notification once upon 1st call to rpm
1425 NotifyAttemptToModify attemptToModify( result_r );
1429 RpmPostTransCollector postTransCollector( _root );
1430 std::vector<sat::Solvable> successfullyInstalledPackages;
1431 TargetImpl::PoolItemList remaining;
1433 for_( step, steps.begin(), steps.end() )
1435 PoolItem citem( *step );
1436 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1438 if ( citem->isKind<Package>() )
1440 // for packages this means being obsoleted (by rpm)
1441 // thius no additional action is needed.
1442 step->stepStage( sat::Transaction::STEP_DONE );
1447 if ( citem->isKind<Package>() )
1449 Package::constPtr p = citem->asKind<Package>();
1450 if ( citem.status().isToBeInstalled() )
1452 ManagedFile localfile;
1455 localfile = packageCache_r.get( citem );
1457 catch ( const AbortRequestException &e )
1459 WAR << "commit aborted by the user" << endl;
1461 step->stepStage( sat::Transaction::STEP_ERROR );
1464 catch ( const SkipRequestException &e )
1467 WAR << "Skipping package " << p << " in commit" << endl;
1468 step->stepStage( sat::Transaction::STEP_ERROR );
1471 catch ( const Exception &e )
1473 // bnc #395704: missing catch causes abort.
1474 // TODO see if packageCache fails to handle errors correctly.
1476 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1477 step->stepStage( sat::Transaction::STEP_ERROR );
1481 #warning Exception handling
1482 // create a installation progress report proxy
1483 RpmInstallPackageReceiver progress( citem.resolvable() );
1484 progress.connect(); // disconnected on destruction.
1486 bool success = false;
1487 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1488 // Why force and nodeps?
1490 // Because zypp builds the transaction and the resolver asserts that
1491 // everything is fine.
1492 // We use rpm just to unpack and register the package in the database.
1493 // We do this step by step, so rpm is not aware of the bigger context.
1494 // So we turn off rpms internal checks, because we do it inside zypp.
1495 flags |= rpm::RPMINST_NODEPS;
1496 flags |= rpm::RPMINST_FORCE;
1498 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1499 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1500 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1501 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1506 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1507 if ( postTransCollector.collectScriptFromPackage( localfile ) )
1508 flags |= rpm::RPMINST_NOPOSTTRANS;
1509 rpm().installPackage( localfile, flags );
1510 HistoryLog().install(citem);
1512 if ( progress.aborted() )
1514 WAR << "commit aborted by the user" << endl;
1515 localfile.resetDispose(); // keep the package file in the cache
1517 step->stepStage( sat::Transaction::STEP_ERROR );
1522 if ( citem.identTriggersRebootNeededHint() ) {
1523 auto rebootNeededFile = root() / "/var/run/reboot-needed";
1524 if ( filesystem::assert_file( rebootNeededFile ) == EEXIST)
1525 filesystem::touch( rebootNeededFile );
1529 step->stepStage( sat::Transaction::STEP_DONE );
1532 catch ( Exception & excpt_r )
1534 ZYPP_CAUGHT(excpt_r);
1535 localfile.resetDispose(); // keep the package file in the cache
1537 if ( policy_r.dryRun() )
1539 WAR << "dry run failed" << endl;
1540 step->stepStage( sat::Transaction::STEP_ERROR );
1544 if ( progress.aborted() )
1546 WAR << "commit aborted by the user" << endl;
1551 WAR << "Install failed" << endl;
1553 step->stepStage( sat::Transaction::STEP_ERROR );
1557 if ( success && !policy_r.dryRun() )
1559 citem.status().resetTransact( ResStatus::USER );
1560 successfullyInstalledPackages.push_back( citem.satSolvable() );
1561 step->stepStage( sat::Transaction::STEP_DONE );
1566 RpmRemovePackageReceiver progress( citem.resolvable() );
1567 progress.connect(); // disconnected on destruction.
1569 bool success = false;
1570 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1571 flags |= rpm::RPMINST_NODEPS;
1572 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1577 rpm().removePackage( p, flags );
1578 HistoryLog().remove(citem);
1580 if ( progress.aborted() )
1582 WAR << "commit aborted by the user" << endl;
1584 step->stepStage( sat::Transaction::STEP_ERROR );
1590 step->stepStage( sat::Transaction::STEP_DONE );
1593 catch (Exception & excpt_r)
1595 ZYPP_CAUGHT( excpt_r );
1596 if ( progress.aborted() )
1598 WAR << "commit aborted by the user" << endl;
1600 step->stepStage( sat::Transaction::STEP_ERROR );
1604 WAR << "removal of " << p << " failed";
1605 step->stepStage( sat::Transaction::STEP_ERROR );
1607 if ( success && !policy_r.dryRun() )
1609 citem.status().resetTransact( ResStatus::USER );
1610 step->stepStage( sat::Transaction::STEP_DONE );
1614 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1616 // Status is changed as the buddy package buddy
1617 // gets installed/deleted. Handle non-buddies only.
1618 if ( ! citem.buddy() )
1620 if ( citem->isKind<Product>() )
1622 Product::constPtr p = citem->asKind<Product>();
1623 if ( citem.status().isToBeInstalled() )
1625 ERR << "Can't install orphan product without release-package! " << citem << endl;
1629 // Deleting the corresponding product entry is all we con do.
1630 // So the product will no longer be visible as installed.
1631 std::string referenceFilename( p->referenceFilename() );
1632 if ( referenceFilename.empty() )
1634 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1638 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1639 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1641 ERR << "Delete orphan product failed: " << referenceFile << endl;
1646 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1648 // SrcPackage is install-only
1649 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1650 installSrcPackage( p );
1653 citem.status().resetTransact( ResStatus::USER );
1654 step->stepStage( sat::Transaction::STEP_DONE );
1657 } // other resolvables
1661 // process all remembered posttrans scripts. If aborting,
1662 // at least log omitted scripts.
1663 if ( abort || (abort = !postTransCollector.executeScripts()) )
1664 postTransCollector.discardScripts();
1666 // Check presence of update scripts/messages. If aborting,
1667 // at least log omitted scripts.
1668 if ( ! successfullyInstalledPackages.empty() )
1670 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1671 successfullyInstalledPackages, abort ) )
1673 WAR << "Commit aborted by the user" << endl;
1676 // send messages after scripts in case some script generates output,
1677 // that should be kept in t %ghost message file.
1678 RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1679 successfullyInstalledPackages,
1685 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1689 ///////////////////////////////////////////////////////////////////
1691 rpm::RpmDb & TargetImpl::rpm()
1696 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1698 return _rpm.hasFile(path_str, name_str);
1702 Date TargetImpl::timestamp() const
1704 return _rpm.timestamp();
1707 ///////////////////////////////////////////////////////////////////
1710 parser::ProductFileData baseproductdata( const Pathname & root_r )
1712 parser::ProductFileData ret;
1713 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1715 if ( baseproduct.isFile() )
1719 ret = parser::ProductFileReader::scanFile( baseproduct.path() );
1721 catch ( const Exception & excpt )
1723 ZYPP_CAUGHT( excpt );
1726 else if ( PathInfo( Pathname::assertprefix( root_r, "/etc/products.d" ) ).isDir() )
1728 ERR << "baseproduct symlink is dangling or missing: " << baseproduct << endl;
1733 inline Pathname staticGuessRoot( const Pathname & root_r )
1735 if ( root_r.empty() )
1737 // empty root: use existing Target or assume "/"
1738 Pathname ret ( ZConfig::instance().systemRoot() );
1740 return Pathname("/");
1746 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1748 std::ifstream idfile( file_r.c_str() );
1749 for( iostr::EachLine in( idfile ); in; in.next() )
1751 std::string line( str::trim( *in ) );
1752 if ( ! line.empty() )
1755 return std::string();
1758 ///////////////////////////////////////////////////////////////////
1760 Product::constPtr TargetImpl::baseProduct() const
1762 ResPool pool(ResPool::instance());
1763 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1765 Product::constPtr p = (*it)->asKind<Product>();
1766 if ( p->isTargetDistribution() )
1772 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1774 const Pathname needroot( staticGuessRoot(root_r) );
1775 const Target_constPtr target( getZYpp()->getTarget() );
1776 if ( target && target->root() == needroot )
1777 return target->requestedLocales();
1778 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1781 void TargetImpl::updateAutoInstalled()
1783 MIL << "updateAutoInstalled if changed..." << endl;
1784 SolvIdentFile::Data newdata;
1785 for ( auto id : sat::Pool::instance().autoInstalled() )
1786 newdata.insert( IdString(id) ); // explicit ctor!
1787 _autoInstalledFile.setData( std::move(newdata) );
1790 std::string TargetImpl::targetDistribution() const
1791 { return baseproductdata( _root ).registerTarget(); }
1793 std::string TargetImpl::targetDistribution( const Pathname & root_r )
1794 { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1796 std::string TargetImpl::targetDistributionRelease() const
1797 { return baseproductdata( _root ).registerRelease(); }
1799 std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1800 { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1802 std::string TargetImpl::targetDistributionFlavor() const
1803 { return baseproductdata( _root ).registerFlavor(); }
1805 std::string TargetImpl::targetDistributionFlavor( const Pathname & root_r )
1806 { return baseproductdata( staticGuessRoot(root_r) ).registerFlavor();}
1808 Target::DistributionLabel TargetImpl::distributionLabel() const
1810 Target::DistributionLabel ret;
1811 parser::ProductFileData pdata( baseproductdata( _root ) );
1812 ret.shortName = pdata.shortName();
1813 ret.summary = pdata.summary();
1817 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1819 Target::DistributionLabel ret;
1820 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1821 ret.shortName = pdata.shortName();
1822 ret.summary = pdata.summary();
1826 std::string TargetImpl::distributionVersion() const
1828 if ( _distributionVersion.empty() )
1830 _distributionVersion = TargetImpl::distributionVersion(root());
1831 if ( !_distributionVersion.empty() )
1832 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1834 return _distributionVersion;
1837 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1839 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1840 if ( distributionVersion.empty() )
1842 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1843 // On RHEL, Fedora and others the "product version" is determined by the first package
1844 // providing 'system-release'. This value is not hardcoded in YUM and can be configured
1845 // with the $distroverpkg variable.
1846 scoped_ptr<rpm::RpmDb> tmprpmdb;
1847 if ( ZConfig::instance().systemRoot() == Pathname() )
1851 tmprpmdb.reset( new rpm::RpmDb );
1852 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1859 rpm::librpmDb::db_const_iterator it;
1860 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1861 distributionVersion = it->tag_version();
1863 return distributionVersion;
1867 std::string TargetImpl::distributionFlavor() const
1869 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1872 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1874 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1877 ///////////////////////////////////////////////////////////////////
1880 std::string guessAnonymousUniqueId( const Pathname & root_r )
1882 // bsc#1024741: Omit creating a new uid for chrooted systems (if it already has one, fine)
1883 std::string ret( firstNonEmptyLineIn( root_r / "/var/lib/zypp/AnonymousUniqueId" ) );
1884 if ( ret.empty() && root_r != "/" )
1886 // if it has nonoe, use the outer systems one
1887 ret = firstNonEmptyLineIn( "/var/lib/zypp/AnonymousUniqueId" );
1893 std::string TargetImpl::anonymousUniqueId() const
1895 return guessAnonymousUniqueId( root() );
1898 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1900 return guessAnonymousUniqueId( staticGuessRoot(root_r) );
1903 ///////////////////////////////////////////////////////////////////
1905 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1907 // provide on local disk
1908 ManagedFile localfile = provideSrcPackage(srcPackage_r);
1909 // create a installation progress report proxy
1910 RpmInstallPackageReceiver progress( srcPackage_r );
1911 progress.connect(); // disconnected on destruction.
1913 rpm().installPackage ( localfile );
1916 ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1918 // provide on local disk
1919 repo::RepoMediaAccess access_r;
1920 repo::SrcPackageProvider prov( access_r );
1921 return prov.provideSrcPackage( srcPackage_r );
1923 ////////////////////////////////////////////////////////////////
1924 } // namespace target
1925 ///////////////////////////////////////////////////////////////////
1926 /////////////////////////////////////////////////////////////////
1928 ///////////////////////////////////////////////////////////////////