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/SolvableSpec.h>
58 #include <zypp/sat/Transaction.h>
60 #include <zypp/PluginExecutor.h>
64 ///////////////////////////////////////////////////////////////////
67 #include <solv/repo_rpmdb.h>
73 inline std::string rpmDbStateHash( const Pathname & root_r )
76 AutoDispose<void*> state { ::rpm_state_create( sat::Pool::instance().get(), root_r.c_str() ), ::rpm_state_free };
77 AutoDispose<Chksum*> chk { ::solv_chksum_create( REPOKEY_TYPE_SHA1 ), []( Chksum *chk ) -> void {
78 ::solv_chksum_free( chk, nullptr );
80 if ( ::rpm_hash_database_state( state, chk ) == 0 )
83 const unsigned char * md5 = ::solv_chksum_get( chk, &md5l );
84 ret = ::pool_bin2hex( sat::Pool::instance().get(), md5, md5l );
87 WAR << "rpm_hash_database_state failed" << endl;
91 inline RepoStatus rpmDbRepoStatus( const Pathname & root_r )
92 { return RepoStatus( rpmDbStateHash( root_r ), Date() ); }
96 ///////////////////////////////////////////////////////////////////
98 ///////////////////////////////////////////////////////////////////
101 /////////////////////////////////////////////////////////////////
104 // HACK for bnc#906096: let pool re-evaluate multiversion spec
105 // if target root changes. ZConfig returns data sensitive to
106 // current target root.
107 inline void sigMultiversionSpecChanged()
109 sat::detail::PoolMember::myPool().multiversionSpecChanged();
112 /////////////////////////////////////////////////////////////////
114 ///////////////////////////////////////////////////////////////////
117 // Lazy via template specialisation / should switch to overloading
120 inline std::string toJSON( const ZYppCommitResult::TransactionStepList & steps_r )
122 using sat::Transaction;
125 for ( const Transaction::Step & step : steps_r )
126 // ignore implicit deletes due to obsoletes and non-package actions
127 if ( step.stepType() != Transaction::TRANSACTION_IGNORE )
133 /** See \ref commitbegin on page \ref plugin-commit for the specs. */
135 inline std::string toJSON( const sat::Transaction::Step & step_r )
137 static const std::string strType( "type" );
138 static const std::string strStage( "stage" );
139 static const std::string strSolvable( "solvable" );
141 static const std::string strTypeDel( "-" );
142 static const std::string strTypeIns( "+" );
143 static const std::string strTypeMul( "M" );
145 static const std::string strStageDone( "ok" );
146 static const std::string strStageFailed( "err" );
148 static const std::string strSolvableN( "n" );
149 static const std::string strSolvableE( "e" );
150 static const std::string strSolvableV( "v" );
151 static const std::string strSolvableR( "r" );
152 static const std::string strSolvableA( "a" );
154 using sat::Transaction;
157 switch ( step_r.stepType() )
159 case Transaction::TRANSACTION_IGNORE: /*empty*/ break;
160 case Transaction::TRANSACTION_ERASE: ret.add( strType, strTypeDel ); break;
161 case Transaction::TRANSACTION_INSTALL: ret.add( strType, strTypeIns ); break;
162 case Transaction::TRANSACTION_MULTIINSTALL: ret.add( strType, strTypeMul ); break;
165 switch ( step_r.stepStage() )
167 case Transaction::STEP_TODO: /*empty*/ break;
168 case Transaction::STEP_DONE: ret.add( strStage, strStageDone ); break;
169 case Transaction::STEP_ERROR: ret.add( strStage, strStageFailed ); break;
176 if ( sat::Solvable solv = step_r.satSolvable() )
178 ident = solv.ident();
184 // deleted package; post mortem data stored in Transaction::Step
185 ident = step_r.ident();
186 ed = step_r.edition();
187 arch = step_r.arch();
191 { strSolvableN, ident.asString() },
192 { strSolvableV, ed.version() },
193 { strSolvableR, ed.release() },
194 { strSolvableA, arch.asString() }
196 if ( Edition::epoch_t epoch = ed.epoch() )
197 s.add( strSolvableE, epoch );
199 ret.add( strSolvable, s );
205 ///////////////////////////////////////////////////////////////////
207 ///////////////////////////////////////////////////////////////////
210 ///////////////////////////////////////////////////////////////////
213 SolvIdentFile::Data getUserInstalledFromHistory( const Pathname & historyFile_r )
215 SolvIdentFile::Data onSystemByUserList;
216 // go and parse it: 'who' must constain an '@', then it was installed by user request.
217 // 2009-09-29 07:25:19|install|lirc-remotes|0.8.5-3.2|x86_64|root@opensuse|InstallationImage|a204211eb0...
218 std::ifstream infile( historyFile_r.c_str() );
219 for( iostr::EachLine in( infile ); in; in.next() )
221 const char * ch( (*in).c_str() );
223 if ( *ch < '1' || '9' < *ch )
225 const char * sep1 = ::strchr( ch, '|' ); // | after date
229 // if logs an install or delete
230 bool installs = true;
231 if ( ::strncmp( sep1, "install|", 8 ) )
233 if ( ::strncmp( sep1, "remove |", 8 ) )
234 continue; // no install and no remove
236 installs = false; // remove
238 sep1 += 8; // | after what
239 // get the package name
240 const char * sep2 = ::strchr( sep1, '|' ); // | after name
241 if ( !sep2 || sep1 == sep2 )
243 (*in)[sep2-ch] = '\0';
244 IdString pkg( sep1 );
245 // we're done, if a delete
248 onSystemByUserList.erase( pkg );
251 // now guess whether user installed or not (3rd next field contains 'user@host')
252 if ( (sep1 = ::strchr( sep2+1, '|' )) // | after version
253 && (sep1 = ::strchr( sep1+1, '|' )) // | after arch
254 && (sep2 = ::strchr( sep1+1, '|' )) ) // | after who
256 (*in)[sep2-ch] = '\0';
257 if ( ::strchr( sep1+1, '@' ) )
260 onSystemByUserList.insert( pkg );
265 MIL << "onSystemByUserList found: " << onSystemByUserList.size() << endl;
266 return onSystemByUserList;
269 ///////////////////////////////////////////////////////////////////
271 ///////////////////////////////////////////////////////////////////
274 inline PluginFrame transactionPluginFrame( const std::string & command_r, ZYppCommitResult::TransactionStepList & steps_r )
276 return PluginFrame( command_r, json::Object {
277 { "TransactionStepList", steps_r }
281 ///////////////////////////////////////////////////////////////////
283 /** \internal Manage writing a new testcase when doing an upgrade. */
284 void writeUpgradeTestcase()
286 unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
287 MIL << "Testcases to keep: " << toKeep << endl;
290 Target_Ptr target( getZYpp()->getTarget() );
293 WAR << "No Target no Testcase!" << endl;
297 std::string stem( "updateTestcase" );
298 Pathname dir( target->assertRootPrefix("/var/log/") );
299 Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
302 std::list<std::string> content;
303 filesystem::readdir( content, dir, /*dots*/false );
304 std::set<std::string> cases;
305 for_( c, content.begin(), content.end() )
307 if ( str::startsWith( *c, stem ) )
310 if ( cases.size() >= toKeep )
312 unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
313 for_( c, cases.begin(), cases.end() )
315 filesystem::recursive_rmdir( dir/(*c) );
322 MIL << "Write new testcase " << next << endl;
323 getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
326 ///////////////////////////////////////////////////////////////////
328 { /////////////////////////////////////////////////////////////////
330 /** Execute script and report against report_r.
331 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
332 * execution was successfull (<tt>first = true</tt>), or the desired
333 * \c PatchScriptReport::Action in case execution failed
334 * (<tt>first = false</tt>).
336 * \note The packager is responsible for setting the correct permissions
337 * of the script. If the script is not executable it is reported as an
338 * error. We must not modify the permessions.
340 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
341 const Pathname & script_r,
342 callback::SendReport<PatchScriptReport> & report_r )
344 MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
346 HistoryLog historylog;
347 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
348 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
350 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
352 historylog.comment(output);
353 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
355 WAR << "User request to abort script " << script_r << endl;
357 // the rest is handled by exit code evaluation
358 // in case the script has meanwhile finished.
362 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
364 if ( prog.close() != 0 )
366 ret.second = report_r->problem( prog.execError() );
367 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
368 std::ostringstream sstr;
369 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
370 historylog.comment(sstr.str(), /*timestamp*/true);
379 /** Execute script and report against report_r.
380 * Return \c false if user requested \c ABORT.
382 bool executeScript( const Pathname & root_r,
383 const Pathname & script_r,
384 callback::SendReport<PatchScriptReport> & report_r )
386 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
389 action = doExecuteScript( root_r, script_r, report_r );
391 return true; // success
393 switch ( action.second )
395 case PatchScriptReport::ABORT:
396 WAR << "User request to abort at script " << script_r << endl;
397 return false; // requested abort.
400 case PatchScriptReport::IGNORE:
401 WAR << "User request to skip script " << script_r << endl;
402 return true; // requested skip.
405 case PatchScriptReport::RETRY:
408 } while ( action.second == PatchScriptReport::RETRY );
410 // THIS is not intended to be reached:
411 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
412 return false; // abort.
415 /** Look for update scripts named 'name-version-release-*' and
416 * execute them. Return \c false if \c ABORT was requested.
418 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
420 bool RunUpdateScripts( const Pathname & root_r,
421 const Pathname & scriptsPath_r,
422 const std::vector<sat::Solvable> & checkPackages_r,
425 if ( checkPackages_r.empty() )
426 return true; // no installed packages to check
428 MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
429 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
430 if ( ! PathInfo( scriptsDir ).isDir() )
431 return true; // no script dir
433 std::list<std::string> scripts;
434 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
435 if ( scripts.empty() )
436 return true; // no scripts in script dir
438 // Now collect and execute all matching scripts.
439 // On ABORT: at least log all outstanding scripts.
440 // - "name-version-release"
441 // - "name-version-release-*"
443 std::map<std::string, Pathname> unify; // scripts <md5,path>
444 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
446 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
447 for_( sit, scripts.begin(), scripts.end() )
449 if ( ! str::hasPrefix( *sit, prefix ) )
452 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
453 continue; // if not exact match it had to continue with '-'
455 PathInfo script( scriptsDir / *sit );
456 Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
457 std::string unifytag; // must not stay empty
459 if ( script.isFile() )
461 // Assert it's set executable, unify by md5sum.
462 filesystem::addmod( script.path(), 0500 );
463 unifytag = filesystem::md5sum( script.path() );
465 else if ( ! script.isExist() )
467 // Might be a dangling symlink, might be ok if we are in
468 // instsys (absolute symlink within the system below /mnt).
469 // readlink will tell....
470 unifytag = filesystem::readlink( script.path() ).asString();
473 if ( unifytag.empty() )
477 if ( unify[unifytag].empty() )
479 unify[unifytag] = localPath;
483 // translators: We may find the same script content in files with different names.
484 // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
485 // message for a log file. Preferably start translation with "%s"
486 std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
487 MIL << "Skip update script: " << msg << endl;
488 HistoryLog().comment( msg, /*timestamp*/true );
492 if ( abort || aborting_r )
494 WAR << "Aborting: Skip update script " << *sit << endl;
495 HistoryLog().comment(
496 localPath.asString() + _(" execution skipped while aborting"),
501 MIL << "Found update script " << *sit << endl;
502 callback::SendReport<PatchScriptReport> report;
503 report->start( make<Package>( *it ), script.path() );
505 if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
506 abort = true; // requested abort.
513 ///////////////////////////////////////////////////////////////////
515 ///////////////////////////////////////////////////////////////////
517 inline void copyTo( std::ostream & out_r, const Pathname & file_r )
519 std::ifstream infile( file_r.c_str() );
520 for( iostr::EachLine in( infile ); in; in.next() )
522 out_r << *in << endl;
526 inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
528 std::string ret( cmd_r );
529 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
530 SUBST_IF( "%p", notification_r.solvable().asString() );
531 SUBST_IF( "%P", notification_r.file().asString() );
536 void sendNotification( const Pathname & root_r,
537 const UpdateNotifications & notifications_r )
539 if ( notifications_r.empty() )
542 std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
543 MIL << "Notification command is '" << cmdspec << "'" << endl;
544 if ( cmdspec.empty() )
547 std::string::size_type pos( cmdspec.find( '|' ) );
548 if ( pos == std::string::npos )
550 ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
551 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
555 std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
556 std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
558 enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
559 Format format = UNKNOWN;
560 if ( formatStr == "none" )
562 else if ( formatStr == "single" )
564 else if ( formatStr == "digest" )
566 else if ( formatStr == "bulk" )
570 ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
571 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
575 // Take care: commands are ececuted chroot(root_r). The message file
576 // pathnames in notifications_r are local to root_r. For physical access
577 // to the file they need to be prefixed.
579 if ( format == NONE || format == SINGLE )
581 for_( it, notifications_r.begin(), notifications_r.end() )
583 std::vector<std::string> command;
584 if ( format == SINGLE )
585 command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
586 str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
588 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
589 if ( true ) // Wait for feedback
591 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
595 int ret = prog.close();
598 ERR << "Notification command returned with error (" << ret << ")." << endl;
599 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
605 else if ( format == DIGEST || format == BULK )
607 filesystem::TmpFile tmpfile;
608 std::ofstream out( tmpfile.path().c_str() );
609 for_( it, notifications_r.begin(), notifications_r.end() )
611 if ( format == DIGEST )
613 out << it->file() << endl;
615 else if ( format == BULK )
617 copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
621 std::vector<std::string> command;
622 command.push_back( "<"+tmpfile.path().asString() ); // redirect input
623 str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
625 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
626 if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
628 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
632 int ret = prog.close();
635 ERR << "Notification command returned with error (" << ret << ")." << endl;
636 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
643 INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
644 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
650 /** Look for update messages named 'name-version-release-*' and
651 * send notification according to \ref ZConfig::updateMessagesNotify.
653 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
655 void RunUpdateMessages( const Pathname & root_r,
656 const Pathname & messagesPath_r,
657 const std::vector<sat::Solvable> & checkPackages_r,
658 ZYppCommitResult & result_r )
660 if ( checkPackages_r.empty() )
661 return; // no installed packages to check
663 MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
664 Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
665 if ( ! PathInfo( messagesDir ).isDir() )
666 return; // no messages dir
668 std::list<std::string> messages;
669 filesystem::readdir( messages, messagesDir, /*dots*/false );
670 if ( messages.empty() )
671 return; // no messages in message dir
673 // Now collect all matching messages in result and send them
674 // - "name-version-release"
675 // - "name-version-release-*"
676 HistoryLog historylog;
677 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
679 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
680 for_( sit, messages.begin(), messages.end() )
682 if ( ! str::hasPrefix( *sit, prefix ) )
685 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
686 continue; // if not exact match it had to continue with '-'
688 PathInfo message( messagesDir / *sit );
689 if ( ! message.isFile() || message.size() == 0 )
692 MIL << "Found update message " << *sit << endl;
693 Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
694 result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
695 historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
698 sendNotification( root_r, result_r.updateMessages() );
701 /** jsc#SLE-5116: Log patch status changes to history.
702 * Adjust precomputed set if transaction is incomplete.
704 void logPatchStatusChanges( const sat::Transaction & transaction_r, TargetImpl & target_r )
706 ResPool::ChangedPseudoInstalled changedPseudoInstalled { ResPool::instance().changedPseudoInstalled() };
707 if ( changedPseudoInstalled.empty() )
710 if ( ! transaction_r.actionEmpty( ~sat::Transaction::STEP_DONE ) )
712 // Need to recompute the patch list if commit is incomplete!
713 // We remember the initially established status, then reload the
714 // Target to get the current patch status. Then compare.
715 WAR << "Need to recompute the patch status changes as commit is incomplete!" << endl;
716 ResPool::EstablishedStates establishedStates{ ResPool::instance().establishedStates() };
718 changedPseudoInstalled = establishedStates.changedPseudoInstalled();
721 HistoryLog historylog;
722 for ( const auto & el : changedPseudoInstalled )
723 historylog.patchStateChange( el.first, el.second );
726 /////////////////////////////////////////////////////////////////
728 ///////////////////////////////////////////////////////////////////
730 void XRunUpdateMessages( const Pathname & root_r,
731 const Pathname & messagesPath_r,
732 const std::vector<sat::Solvable> & checkPackages_r,
733 ZYppCommitResult & result_r )
734 { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
736 ///////////////////////////////////////////////////////////////////
738 IMPL_PTR_TYPE(TargetImpl);
740 ///////////////////////////////////////////////////////////////////
742 // METHOD NAME : TargetImpl::TargetImpl
743 // METHOD TYPE : Ctor
745 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
747 , _requestedLocalesFile( home() / "RequestedLocales" )
748 , _autoInstalledFile( home() / "AutoInstalled" )
749 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
750 , _vendorAttr( Pathname::assertprefix( _root, ZConfig::instance().vendorPath() ) )
752 _rpm.initDatabase( root_r, doRebuild_r );
754 HistoryLog::setRoot(_root);
757 sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
758 MIL << "Initialized target on " << _root << endl;
762 * generates a random id using uuidgen
764 static std::string generateRandomId()
766 std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
767 return iostr::getline( uuidprovider );
771 * updates the content of \p filename
772 * if \p condition is true, setting the content
773 * the the value returned by \p value
775 void updateFileContent( const Pathname &filename,
776 boost::function<bool ()> condition,
777 boost::function<std::string ()> value )
779 std::string val = value();
780 // if the value is empty, then just dont
781 // do anything, regardless of the condition
787 MIL << "updating '" << filename << "' content." << endl;
789 // if the file does not exist we need to generate the uuid file
791 std::ofstream filestr;
792 // make sure the path exists
793 filesystem::assert_dir( filename.dirname() );
794 filestr.open( filename.c_str() );
796 if ( filestr.good() )
803 // FIXME, should we ignore the error?
804 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
809 /** helper functor */
810 static bool fileMissing( const Pathname &pathname )
812 return ! PathInfo(pathname).isExist();
815 void TargetImpl::createAnonymousId() const
817 // bsc#1024741: Omit creating a new uid for chrooted systems (if it already has one, fine)
821 // Create the anonymous unique id, used for download statistics
822 Pathname idpath( home() / "AnonymousUniqueId");
826 updateFileContent( idpath,
827 boost::bind(fileMissing, idpath),
830 catch ( const Exception &e )
832 WAR << "Can't create anonymous id file" << endl;
837 void TargetImpl::createLastDistributionFlavorCache() const
839 // create the anonymous unique id
840 // this value is used for statistics
841 Pathname flavorpath( home() / "LastDistributionFlavor");
843 // is there a product
844 Product::constPtr p = baseProduct();
847 WAR << "No base product, I won't create flavor cache" << endl;
851 std::string flavor = p->flavor();
856 updateFileContent( flavorpath,
857 // only if flavor is not empty
858 functor::Constant<bool>( ! flavor.empty() ),
859 functor::Constant<std::string>(flavor) );
861 catch ( const Exception &e )
863 WAR << "Can't create flavor cache" << endl;
868 ///////////////////////////////////////////////////////////////////
870 // METHOD NAME : TargetImpl::~TargetImpl
871 // METHOD TYPE : Dtor
873 TargetImpl::~TargetImpl()
875 _rpm.closeDatabase();
876 sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
877 MIL << "Targets closed" << endl;
880 ///////////////////////////////////////////////////////////////////
882 // solv file handling
884 ///////////////////////////////////////////////////////////////////
886 Pathname TargetImpl::defaultSolvfilesPath() const
888 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
891 void TargetImpl::clearCache()
893 Pathname base = solvfilesPath();
894 filesystem::recursive_rmdir( base );
897 bool TargetImpl::buildCache()
899 Pathname base = solvfilesPath();
900 Pathname rpmsolv = base/"solv";
901 Pathname rpmsolvcookie = base/"cookie";
903 bool build_rpm_solv = true;
904 // lets see if the rpm solv cache exists
906 RepoStatus rpmstatus( rpmDbRepoStatus(_root) && RepoStatus(_root/"etc/products.d") );
908 bool solvexisted = PathInfo(rpmsolv).isExist();
911 // see the status of the cache
912 PathInfo cookie( rpmsolvcookie );
913 MIL << "Read cookie: " << cookie << endl;
914 if ( cookie.isExist() )
916 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
917 // now compare it with the rpm database
918 if ( status == rpmstatus )
919 build_rpm_solv = false;
920 MIL << "Read cookie: " << rpmsolvcookie << " says: "
921 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
925 if ( build_rpm_solv )
927 // if the solvfile dir does not exist yet, we better create it
928 filesystem::assert_dir( base );
930 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
932 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
935 // Can't create temporary solv file, usually due to insufficient permission
936 // (user query while @System solv needs refresh). If so, try switching
937 // to a location within zypps temp. space (will be cleaned at application end).
939 bool switchingToTmpSolvfile = false;
940 Exception ex("Failed to cache rpm database.");
941 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
943 if ( ! solvfilesPathIsTemp() )
945 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
946 rpmsolv = base/"solv";
947 rpmsolvcookie = base/"cookie";
949 filesystem::assert_dir( base );
950 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
954 WAR << "Using a temporary solv file at " << base << endl;
955 switchingToTmpSolvfile = true;
956 _tmpSolvfilesPath = base;
960 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
964 if ( ! switchingToTmpSolvfile )
970 // Take care we unlink the solvfile on exception
971 ManagedFile guard( base, filesystem::recursive_rmdir );
973 ExternalProgram::Arguments cmd;
974 cmd.push_back( "rpmdb2solv" );
975 if ( ! _root.empty() ) {
976 cmd.push_back( "-r" );
977 cmd.push_back( _root.asString() );
979 cmd.push_back( "-X" ); // autogenerate pattern/product/... from -package
980 // bsc#1104415: no more application support // cmd.push_back( "-A" ); // autogenerate application pseudo packages
981 cmd.push_back( "-p" );
982 cmd.push_back( Pathname::assertprefix( _root, "/etc/products.d" ).asString() );
984 if ( ! oldSolvFile.empty() )
985 cmd.push_back( oldSolvFile.asString() );
987 cmd.push_back( "-o" );
988 cmd.push_back( tmpsolv.path().asString() );
990 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
991 std::string errdetail;
993 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
994 WAR << " " << output;
995 if ( errdetail.empty() ) {
996 errdetail = prog.command();
1002 int ret = prog.close();
1005 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
1006 ex.remember( errdetail );
1010 ret = filesystem::rename( tmpsolv, rpmsolv );
1012 ZYPP_THROW(Exception("Failed to move cache to final destination"));
1013 // if this fails, don't bother throwing exceptions
1014 filesystem::chmod( rpmsolv, 0644 );
1016 rpmstatus.saveToCookieFile(rpmsolvcookie);
1019 guard.resetDispose();
1020 sat::updateSolvFileIndex( rpmsolv ); // content digest for zypper bash completion
1022 // system-hook: Finally send notification to plugins
1023 if ( root() == "/" )
1025 PluginExecutor plugins;
1026 plugins.load( ZConfig::instance().pluginsPath()/"system" );
1028 plugins.send( PluginFrame( "PACKAGESETCHANGED" ) );
1033 // On the fly add missing solv.idx files for bash completion.
1034 if ( ! PathInfo(base/"solv.idx").isExist() )
1035 sat::updateSolvFileIndex( rpmsolv );
1037 return build_rpm_solv;
1040 void TargetImpl::reload()
1045 void TargetImpl::unload()
1047 Repository system( sat::Pool::instance().findSystemRepo() );
1049 system.eraseFromPool();
1052 void TargetImpl::load( bool force )
1054 bool newCache = buildCache();
1055 MIL << "New cache built: " << (newCache?"true":"false") <<
1056 ", force loading: " << (force?"true":"false") << endl;
1058 // now add the repos to the pool
1059 sat::Pool satpool( sat::Pool::instance() );
1060 Pathname rpmsolv( solvfilesPath() / "solv" );
1061 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
1063 // Providing an empty system repo, unload any old content
1064 Repository system( sat::Pool::instance().findSystemRepo() );
1066 if ( system && ! system.solvablesEmpty() )
1068 if ( newCache || force )
1070 system.eraseFromPool(); // invalidates system
1074 return; // nothing to do
1080 system = satpool.systemRepo();
1085 MIL << "adding " << rpmsolv << " to system" << endl;
1086 system.addSolv( rpmsolv );
1088 catch ( const Exception & exp )
1091 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1095 system.addSolv( rpmsolv );
1097 satpool.rootDir( _root );
1099 // (Re)Load the requested locales et al.
1100 // If the requested locales are empty, we leave the pool untouched
1101 // to avoid undoing changes the application applied. We expect this
1102 // to happen on a bare metal installation only. An already existing
1103 // target should be loaded before its settings are changed.
1105 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1106 if ( ! requestedLocales.empty() )
1108 satpool.initRequestedLocales( requestedLocales );
1112 if ( ! PathInfo( _autoInstalledFile.file() ).isExist() )
1114 // Initialize from history, if it does not exist
1115 Pathname historyFile( Pathname::assertprefix( _root, ZConfig::instance().historyLogFile() ) );
1116 if ( PathInfo( historyFile ).isExist() )
1118 SolvIdentFile::Data onSystemByUser( getUserInstalledFromHistory( historyFile ) );
1119 SolvIdentFile::Data onSystemByAuto;
1120 for_( it, system.solvablesBegin(), system.solvablesEnd() )
1122 IdString ident( (*it).ident() );
1123 if ( onSystemByUser.find( ident ) == onSystemByUser.end() )
1124 onSystemByAuto.insert( ident );
1126 _autoInstalledFile.setData( onSystemByAuto );
1128 // on the fly removed any obsolete SoftLocks file
1129 filesystem::unlink( home() / "SoftLocks" );
1131 // read from AutoInstalled file
1133 for ( const auto & idstr : _autoInstalledFile.data() )
1134 q.push( idstr.id() );
1135 satpool.setAutoInstalled( q );
1138 // Load the needreboot package specs
1140 sat::SolvableSpec needrebootSpec;
1142 Pathname needrebootFile { Pathname::assertprefix( root(), ZConfig::instance().needrebootFile() ) };
1143 if ( PathInfo( needrebootFile ).isFile() )
1144 needrebootSpec.parseFrom( needrebootFile );
1146 Pathname needrebootDir { Pathname::assertprefix( root(), ZConfig::instance().needrebootPath() ) };
1147 if ( PathInfo( needrebootDir ).isDir() )
1149 static const StrMatcher isRpmConfigBackup( "\\.rpm(new|save|orig)$", Match::REGEX );
1151 filesystem::dirForEach( needrebootDir, filesystem::matchNoDots(),
1152 [&]( const Pathname & dir_r, const char *const str_r )->bool
1154 if ( ! isRpmConfigBackup( str_r ) )
1156 Pathname needrebootFile { needrebootDir / str_r };
1157 if ( PathInfo( needrebootFile ).isFile() )
1158 needrebootSpec.parseFrom( needrebootFile );
1163 satpool.setNeedrebootSpec( std::move(needrebootSpec) );
1166 if ( ZConfig::instance().apply_locks_file() )
1168 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1169 if ( ! hardLocks.empty() )
1171 ResPool::instance().setHardLockQueries( hardLocks );
1175 // now that the target is loaded, we can cache the flavor
1176 createLastDistributionFlavorCache();
1178 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1181 ///////////////////////////////////////////////////////////////////
1185 ///////////////////////////////////////////////////////////////////
1186 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1188 // ----------------------------------------------------------------- //
1189 ZYppCommitPolicy policy_r( policy_rX );
1190 bool explicitDryRun = policy_r.dryRun(); // explicit dry run will trigger a fileconflict check, implicit (download-only) not.
1192 ShutdownLock lck("Zypp commit running.");
1194 // Fake outstanding YCP fix: Honour restriction to media 1
1195 // at installation, but install all remaining packages if post-boot.
1196 if ( policy_r.restrictToMedia() > 1 )
1197 policy_r.allMedia();
1199 if ( policy_r.downloadMode() == DownloadDefault ) {
1200 if ( root() == "/" )
1201 policy_r.downloadMode(DownloadInHeaps);
1203 policy_r.downloadMode(DownloadAsNeeded);
1205 // DownloadOnly implies dry-run.
1206 else if ( policy_r.downloadMode() == DownloadOnly )
1207 policy_r.dryRun( true );
1208 // ----------------------------------------------------------------- //
1210 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1212 ///////////////////////////////////////////////////////////////////
1213 // Compute transaction:
1214 ///////////////////////////////////////////////////////////////////
1215 ZYppCommitResult result( root() );
1216 result.rTransaction() = pool_r.resolver().getTransaction();
1217 result.rTransaction().order();
1218 // steps: this is our todo-list
1219 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1220 if ( policy_r.restrictToMedia() )
1222 // Collect until the 1st package from an unwanted media occurs.
1223 // Further collection could violate install order.
1224 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1225 for_( it, result.transaction().begin(), result.transaction().end() )
1227 if ( makeResObject( *it )->mediaNr() > 1 )
1229 steps.push_back( *it );
1234 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1236 MIL << "Todo: " << result << endl;
1238 ///////////////////////////////////////////////////////////////////
1239 // Prepare execution of commit plugins:
1240 ///////////////////////////////////////////////////////////////////
1241 PluginExecutor commitPlugins;
1242 if ( root() == "/" && ! policy_r.dryRun() )
1244 commitPlugins.load( ZConfig::instance().pluginsPath()/"commit" );
1246 if ( commitPlugins )
1247 commitPlugins.send( transactionPluginFrame( "COMMITBEGIN", steps ) );
1249 ///////////////////////////////////////////////////////////////////
1250 // Write out a testcase if we're in dist upgrade mode.
1251 ///////////////////////////////////////////////////////////////////
1252 if ( pool_r.resolver().upgradeMode() || pool_r.resolver().upgradingRepos() )
1254 if ( ! policy_r.dryRun() )
1256 writeUpgradeTestcase();
1260 DBG << "dryRun: Not writing upgrade testcase." << endl;
1264 ///////////////////////////////////////////////////////////////////
1265 // Store non-package data:
1266 ///////////////////////////////////////////////////////////////////
1267 if ( ! policy_r.dryRun() )
1269 filesystem::assert_dir( home() );
1270 // requested locales
1271 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1274 SolvIdentFile::Data newdata;
1275 for ( sat::Queue::value_type id : result.rTransaction().autoInstalled() )
1276 newdata.insert( IdString(id) );
1277 _autoInstalledFile.setData( newdata );
1280 if ( ZConfig::instance().apply_locks_file() )
1282 HardLocksFile::Data newdata;
1283 pool_r.getHardLockQueries( newdata );
1284 _hardLocksFile.setData( newdata );
1289 DBG << "dryRun: Not stroring non-package data." << endl;
1292 ///////////////////////////////////////////////////////////////////
1293 // First collect and display all messages
1294 // associated with patches to be installed.
1295 ///////////////////////////////////////////////////////////////////
1296 if ( ! policy_r.dryRun() )
1298 for_( it, steps.begin(), steps.end() )
1300 if ( ! it->satSolvable().isKind<Patch>() )
1304 if ( ! pi.status().isToBeInstalled() )
1307 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1308 if ( ! patch ||patch->message().empty() )
1311 MIL << "Show message for " << patch << endl;
1312 callback::SendReport<target::PatchMessageReport> report;
1313 if ( ! report->show( patch ) )
1315 WAR << "commit aborted by the user" << endl;
1316 ZYPP_THROW( TargetAbortedException( ) );
1322 DBG << "dryRun: Not checking patch messages." << endl;
1325 ///////////////////////////////////////////////////////////////////
1326 // Remove/install packages.
1327 ///////////////////////////////////////////////////////////////////
1328 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1329 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1331 // Prepare the package cache. Pass all items requiring download.
1332 CommitPackageCache packageCache;
1333 packageCache.setCommitList( steps.begin(), steps.end() );
1336 if ( policy_r.downloadMode() != DownloadAsNeeded )
1338 // Preload the cache. Until now this means pre-loading all packages.
1339 // Once DownloadInHeaps is fully implemented, this will change and
1340 // we may actually have more than one heap.
1341 for_( it, steps.begin(), steps.end() )
1343 switch ( it->stepType() )
1345 case sat::Transaction::TRANSACTION_INSTALL:
1346 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1347 // proceed: only install actionas may require download.
1351 // next: no download for or non-packages and delete actions.
1357 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1359 ManagedFile localfile;
1362 localfile = packageCache.get( pi );
1363 localfile.resetDispose(); // keep the package file in the cache
1365 catch ( const AbortRequestException & exp )
1367 it->stepStage( sat::Transaction::STEP_ERROR );
1369 WAR << "commit cache preload aborted by the user" << endl;
1370 ZYPP_THROW( TargetAbortedException( ) );
1373 catch ( const SkipRequestException & exp )
1376 it->stepStage( sat::Transaction::STEP_ERROR );
1378 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1381 catch ( const Exception & exp )
1383 // bnc #395704: missing catch causes abort.
1384 // TODO see if packageCache fails to handle errors correctly.
1386 it->stepStage( sat::Transaction::STEP_ERROR );
1388 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1393 packageCache.preloaded( true ); // try to avoid duplicate infoInCache CBs in commit
1398 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1402 if ( ! policy_r.dryRun() )
1404 // if cache is preloaded, check for file conflicts
1405 commitFindFileConflicts( policy_r, result );
1406 commit( policy_r, packageCache, result );
1410 DBG << "dryRun/downloadOnly: Not installing/deleting anything." << endl;
1411 if ( explicitDryRun ) {
1412 // if cache is preloaded, check for file conflicts
1413 commitFindFileConflicts( policy_r, result );
1420 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1421 if ( explicitDryRun ) {
1422 // if cache is preloaded, check for file conflicts
1423 commitFindFileConflicts( policy_r, result );
1427 ///////////////////////////////////////////////////////////////////
1428 // Send result to commit plugins:
1429 ///////////////////////////////////////////////////////////////////
1430 if ( commitPlugins )
1431 commitPlugins.send( transactionPluginFrame( "COMMITEND", steps ) );
1433 ///////////////////////////////////////////////////////////////////
1434 // Try to rebuild solv file while rpm database is still in cache
1435 ///////////////////////////////////////////////////////////////////
1436 if ( ! policy_r.dryRun() )
1441 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1445 ///////////////////////////////////////////////////////////////////
1449 ///////////////////////////////////////////////////////////////////
1452 struct NotifyAttemptToModify
1454 NotifyAttemptToModify( ZYppCommitResult & result_r ) : _result( result_r ) {}
1457 { if ( _guard ) { _result.attemptToModify( true ); _guard = false; } }
1460 ZYppCommitResult & _result;
1464 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1465 CommitPackageCache & packageCache_r,
1466 ZYppCommitResult & result_r )
1468 // steps: this is our todo-list
1469 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1470 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1472 HistoryLog().stampCommand();
1474 // Send notification once upon 1st call to rpm
1475 NotifyAttemptToModify attemptToModify( result_r );
1479 RpmPostTransCollector postTransCollector( _root );
1480 std::vector<sat::Solvable> successfullyInstalledPackages;
1481 TargetImpl::PoolItemList remaining;
1483 for_( step, steps.begin(), steps.end() )
1485 PoolItem citem( *step );
1486 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1488 if ( citem->isKind<Package>() )
1490 // for packages this means being obsoleted (by rpm)
1491 // thius no additional action is needed.
1492 step->stepStage( sat::Transaction::STEP_DONE );
1497 if ( citem->isKind<Package>() )
1499 Package::constPtr p = citem->asKind<Package>();
1500 if ( citem.status().isToBeInstalled() )
1502 ManagedFile localfile;
1505 localfile = packageCache_r.get( citem );
1507 catch ( const AbortRequestException &e )
1509 WAR << "commit aborted by the user" << endl;
1511 step->stepStage( sat::Transaction::STEP_ERROR );
1514 catch ( const SkipRequestException &e )
1517 WAR << "Skipping package " << p << " in commit" << endl;
1518 step->stepStage( sat::Transaction::STEP_ERROR );
1521 catch ( const Exception &e )
1523 // bnc #395704: missing catch causes abort.
1524 // TODO see if packageCache fails to handle errors correctly.
1526 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1527 step->stepStage( sat::Transaction::STEP_ERROR );
1531 #warning Exception handling
1532 // create a installation progress report proxy
1533 RpmInstallPackageReceiver progress( citem.resolvable() );
1534 progress.connect(); // disconnected on destruction.
1536 bool success = false;
1537 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1538 // Why force and nodeps?
1540 // Because zypp builds the transaction and the resolver asserts that
1541 // everything is fine.
1542 // We use rpm just to unpack and register the package in the database.
1543 // We do this step by step, so rpm is not aware of the bigger context.
1544 // So we turn off rpms internal checks, because we do it inside zypp.
1545 flags |= rpm::RPMINST_NODEPS;
1546 flags |= rpm::RPMINST_FORCE;
1548 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1549 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1550 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1551 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1556 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1557 if ( postTransCollector.collectScriptFromPackage( localfile ) )
1558 flags |= rpm::RPMINST_NOPOSTTRANS;
1559 rpm().installPackage( localfile, flags );
1560 HistoryLog().install(citem);
1562 if ( progress.aborted() )
1564 WAR << "commit aborted by the user" << endl;
1565 localfile.resetDispose(); // keep the package file in the cache
1567 step->stepStage( sat::Transaction::STEP_ERROR );
1572 if ( citem.isNeedreboot() ) {
1573 auto rebootNeededFile = root() / "/var/run/reboot-needed";
1574 if ( filesystem::assert_file( rebootNeededFile ) == EEXIST)
1575 filesystem::touch( rebootNeededFile );
1579 step->stepStage( sat::Transaction::STEP_DONE );
1582 catch ( Exception & excpt_r )
1584 ZYPP_CAUGHT(excpt_r);
1585 localfile.resetDispose(); // keep the package file in the cache
1587 if ( policy_r.dryRun() )
1589 WAR << "dry run failed" << endl;
1590 step->stepStage( sat::Transaction::STEP_ERROR );
1594 if ( progress.aborted() )
1596 WAR << "commit aborted by the user" << endl;
1601 WAR << "Install failed" << endl;
1603 step->stepStage( sat::Transaction::STEP_ERROR );
1607 if ( success && !policy_r.dryRun() )
1609 citem.status().resetTransact( ResStatus::USER );
1610 successfullyInstalledPackages.push_back( citem.satSolvable() );
1611 step->stepStage( sat::Transaction::STEP_DONE );
1616 RpmRemovePackageReceiver progress( citem.resolvable() );
1617 progress.connect(); // disconnected on destruction.
1619 bool success = false;
1620 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1621 flags |= rpm::RPMINST_NODEPS;
1622 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1627 rpm().removePackage( p, flags );
1628 HistoryLog().remove(citem);
1630 if ( progress.aborted() )
1632 WAR << "commit aborted by the user" << endl;
1634 step->stepStage( sat::Transaction::STEP_ERROR );
1640 step->stepStage( sat::Transaction::STEP_DONE );
1643 catch (Exception & excpt_r)
1645 ZYPP_CAUGHT( excpt_r );
1646 if ( progress.aborted() )
1648 WAR << "commit aborted by the user" << endl;
1650 step->stepStage( sat::Transaction::STEP_ERROR );
1654 WAR << "removal of " << p << " failed";
1655 step->stepStage( sat::Transaction::STEP_ERROR );
1657 if ( success && !policy_r.dryRun() )
1659 citem.status().resetTransact( ResStatus::USER );
1660 step->stepStage( sat::Transaction::STEP_DONE );
1664 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1666 // Status is changed as the buddy package buddy
1667 // gets installed/deleted. Handle non-buddies only.
1668 if ( ! citem.buddy() )
1670 if ( citem->isKind<Product>() )
1672 Product::constPtr p = citem->asKind<Product>();
1673 if ( citem.status().isToBeInstalled() )
1675 ERR << "Can't install orphan product without release-package! " << citem << endl;
1679 // Deleting the corresponding product entry is all we con do.
1680 // So the product will no longer be visible as installed.
1681 std::string referenceFilename( p->referenceFilename() );
1682 if ( referenceFilename.empty() )
1684 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1688 Pathname referencePath { Pathname("/etc/products.d") / referenceFilename }; // no root prefix for rpmdb lookup!
1689 if ( ! rpm().hasFile( referencePath.asString() ) )
1691 // If it's not owned by a package, we can delete it.
1692 referencePath = Pathname::assertprefix( _root, referencePath ); // now add a root prefix
1693 if ( filesystem::unlink( referencePath ) != 0 )
1694 ERR << "Delete orphan product failed: " << referencePath << endl;
1698 WAR << "Won't remove orphan product: '/etc/products.d/" << referenceFilename << "' is owned by a package." << endl;
1703 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1705 // SrcPackage is install-only
1706 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1707 installSrcPackage( p );
1710 citem.status().resetTransact( ResStatus::USER );
1711 step->stepStage( sat::Transaction::STEP_DONE );
1714 } // other resolvables
1718 // process all remembered posttrans scripts. If aborting,
1719 // at least log omitted scripts.
1720 if ( abort || (abort = !postTransCollector.executeScripts()) )
1721 postTransCollector.discardScripts();
1723 // Check presence of update scripts/messages. If aborting,
1724 // at least log omitted scripts.
1725 if ( ! successfullyInstalledPackages.empty() )
1727 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1728 successfullyInstalledPackages, abort ) )
1730 WAR << "Commit aborted by the user" << endl;
1733 // send messages after scripts in case some script generates output,
1734 // that should be kept in t %ghost message file.
1735 RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1736 successfullyInstalledPackages,
1740 // jsc#SLE-5116: Log patch status changes to history
1741 // NOTE: Should be the last action as it may need to reload
1742 // the Target in case of an incomplete transaction.
1743 logPatchStatusChanges( result_r.transaction(), *this );
1747 HistoryLog().comment( "Commit was aborted." );
1748 ZYPP_THROW( TargetAbortedException( ) );
1752 ///////////////////////////////////////////////////////////////////
1754 rpm::RpmDb & TargetImpl::rpm()
1759 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1761 return _rpm.hasFile(path_str, name_str);
1764 ///////////////////////////////////////////////////////////////////
1767 parser::ProductFileData baseproductdata( const Pathname & root_r )
1769 parser::ProductFileData ret;
1770 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1772 if ( baseproduct.isFile() )
1776 ret = parser::ProductFileReader::scanFile( baseproduct.path() );
1778 catch ( const Exception & excpt )
1780 ZYPP_CAUGHT( excpt );
1783 else if ( PathInfo( Pathname::assertprefix( root_r, "/etc/products.d" ) ).isDir() )
1785 ERR << "baseproduct symlink is dangling or missing: " << baseproduct << endl;
1790 inline Pathname staticGuessRoot( const Pathname & root_r )
1792 if ( root_r.empty() )
1794 // empty root: use existing Target or assume "/"
1795 Pathname ret ( ZConfig::instance().systemRoot() );
1797 return Pathname("/");
1803 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1805 std::ifstream idfile( file_r.c_str() );
1806 for( iostr::EachLine in( idfile ); in; in.next() )
1808 std::string line( str::trim( *in ) );
1809 if ( ! line.empty() )
1812 return std::string();
1815 ///////////////////////////////////////////////////////////////////
1817 Product::constPtr TargetImpl::baseProduct() const
1819 ResPool pool(ResPool::instance());
1820 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1822 Product::constPtr p = (*it)->asKind<Product>();
1823 if ( p->isTargetDistribution() )
1829 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1831 const Pathname needroot( staticGuessRoot(root_r) );
1832 const Target_constPtr target( getZYpp()->getTarget() );
1833 if ( target && target->root() == needroot )
1834 return target->requestedLocales();
1835 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1838 void TargetImpl::updateAutoInstalled()
1840 MIL << "updateAutoInstalled if changed..." << endl;
1841 SolvIdentFile::Data newdata;
1842 for ( auto id : sat::Pool::instance().autoInstalled() )
1843 newdata.insert( IdString(id) ); // explicit ctor!
1844 _autoInstalledFile.setData( std::move(newdata) );
1847 std::string TargetImpl::targetDistribution() const
1848 { return baseproductdata( _root ).registerTarget(); }
1850 std::string TargetImpl::targetDistribution( const Pathname & root_r )
1851 { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1853 std::string TargetImpl::targetDistributionRelease() const
1854 { return baseproductdata( _root ).registerRelease(); }
1856 std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1857 { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1859 std::string TargetImpl::targetDistributionFlavor() const
1860 { return baseproductdata( _root ).registerFlavor(); }
1862 std::string TargetImpl::targetDistributionFlavor( const Pathname & root_r )
1863 { return baseproductdata( staticGuessRoot(root_r) ).registerFlavor();}
1865 Target::DistributionLabel TargetImpl::distributionLabel() const
1867 Target::DistributionLabel ret;
1868 parser::ProductFileData pdata( baseproductdata( _root ) );
1869 ret.shortName = pdata.shortName();
1870 ret.summary = pdata.summary();
1874 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1876 Target::DistributionLabel ret;
1877 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1878 ret.shortName = pdata.shortName();
1879 ret.summary = pdata.summary();
1883 std::string TargetImpl::distributionVersion() const
1885 if ( _distributionVersion.empty() )
1887 _distributionVersion = TargetImpl::distributionVersion(root());
1888 if ( !_distributionVersion.empty() )
1889 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1891 return _distributionVersion;
1894 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1896 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1897 if ( distributionVersion.empty() )
1899 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1900 // On RHEL, Fedora and others the "product version" is determined by the first package
1901 // providing 'system-release'. This value is not hardcoded in YUM and can be configured
1902 // with the $distroverpkg variable.
1903 scoped_ptr<rpm::RpmDb> tmprpmdb;
1904 if ( ZConfig::instance().systemRoot() == Pathname() )
1908 tmprpmdb.reset( new rpm::RpmDb );
1909 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1916 rpm::librpmDb::db_const_iterator it;
1917 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1918 distributionVersion = it->tag_version();
1920 return distributionVersion;
1924 std::string TargetImpl::distributionFlavor() const
1926 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1929 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1931 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1934 ///////////////////////////////////////////////////////////////////
1937 std::string guessAnonymousUniqueId( const Pathname & root_r )
1939 // bsc#1024741: Omit creating a new uid for chrooted systems (if it already has one, fine)
1940 std::string ret( firstNonEmptyLineIn( root_r / "/var/lib/zypp/AnonymousUniqueId" ) );
1941 if ( ret.empty() && root_r != "/" )
1943 // if it has nonoe, use the outer systems one
1944 ret = firstNonEmptyLineIn( "/var/lib/zypp/AnonymousUniqueId" );
1950 std::string TargetImpl::anonymousUniqueId() const
1952 return guessAnonymousUniqueId( root() );
1955 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1957 return guessAnonymousUniqueId( staticGuessRoot(root_r) );
1960 ///////////////////////////////////////////////////////////////////
1962 void TargetImpl::vendorAttr( VendorAttr vendorAttr_r )
1964 MIL << "New VendorAttr: " << vendorAttr_r << endl;
1965 _vendorAttr = std::move(vendorAttr_r);
1967 ///////////////////////////////////////////////////////////////////
1969 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1971 // provide on local disk
1972 ManagedFile localfile = provideSrcPackage(srcPackage_r);
1973 // create a installation progress report proxy
1974 RpmInstallPackageReceiver progress( srcPackage_r );
1975 progress.connect(); // disconnected on destruction.
1977 rpm().installPackage ( localfile );
1980 ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1982 // provide on local disk
1983 repo::RepoMediaAccess access_r;
1984 repo::SrcPackageProvider prov( access_r );
1985 return prov.provideSrcPackage( srcPackage_r );
1987 ////////////////////////////////////////////////////////////////
1988 } // namespace target
1989 ///////////////////////////////////////////////////////////////////
1990 /////////////////////////////////////////////////////////////////
1992 ///////////////////////////////////////////////////////////////////