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 /////////////////////////////////////////////////////////////////
70 // HACK for bnc#906096: let pool re-evaluate multiversion spec
71 // if target root changes. ZConfig returns data sensitive to
72 // current target root.
73 inline void sigMultiversionSpecChanged()
75 sat::detail::PoolMember::myPool().multiversionSpecChanged();
78 /////////////////////////////////////////////////////////////////
80 ///////////////////////////////////////////////////////////////////
83 // Lazy via template specialisation / should switch to overloading
86 inline std::string toJSON( const ZYppCommitResult::TransactionStepList & steps_r )
88 using sat::Transaction;
91 for ( const Transaction::Step & step : steps_r )
92 // ignore implicit deletes due to obsoletes and non-package actions
93 if ( step.stepType() != Transaction::TRANSACTION_IGNORE )
99 /** See \ref commitbegin on page \ref plugin-commit for the specs. */
101 inline std::string toJSON( const sat::Transaction::Step & step_r )
103 static const std::string strType( "type" );
104 static const std::string strStage( "stage" );
105 static const std::string strSolvable( "solvable" );
107 static const std::string strTypeDel( "-" );
108 static const std::string strTypeIns( "+" );
109 static const std::string strTypeMul( "M" );
111 static const std::string strStageDone( "ok" );
112 static const std::string strStageFailed( "err" );
114 static const std::string strSolvableN( "n" );
115 static const std::string strSolvableE( "e" );
116 static const std::string strSolvableV( "v" );
117 static const std::string strSolvableR( "r" );
118 static const std::string strSolvableA( "a" );
120 using sat::Transaction;
123 switch ( step_r.stepType() )
125 case Transaction::TRANSACTION_IGNORE: /*empty*/ break;
126 case Transaction::TRANSACTION_ERASE: ret.add( strType, strTypeDel ); break;
127 case Transaction::TRANSACTION_INSTALL: ret.add( strType, strTypeIns ); break;
128 case Transaction::TRANSACTION_MULTIINSTALL: ret.add( strType, strTypeMul ); break;
131 switch ( step_r.stepStage() )
133 case Transaction::STEP_TODO: /*empty*/ break;
134 case Transaction::STEP_DONE: ret.add( strStage, strStageDone ); break;
135 case Transaction::STEP_ERROR: ret.add( strStage, strStageFailed ); break;
142 if ( sat::Solvable solv = step_r.satSolvable() )
144 ident = solv.ident();
150 // deleted package; post mortem data stored in Transaction::Step
151 ident = step_r.ident();
152 ed = step_r.edition();
153 arch = step_r.arch();
157 { strSolvableN, ident.asString() },
158 { strSolvableV, ed.version() },
159 { strSolvableR, ed.release() },
160 { strSolvableA, arch.asString() }
162 if ( Edition::epoch_t epoch = ed.epoch() )
163 s.add( strSolvableE, epoch );
165 ret.add( strSolvable, s );
171 ///////////////////////////////////////////////////////////////////
173 ///////////////////////////////////////////////////////////////////
176 ///////////////////////////////////////////////////////////////////
179 SolvIdentFile::Data getUserInstalledFromHistory( const Pathname & historyFile_r )
181 SolvIdentFile::Data onSystemByUserList;
182 // go and parse it: 'who' must constain an '@', then it was installed by user request.
183 // 2009-09-29 07:25:19|install|lirc-remotes|0.8.5-3.2|x86_64|root@opensuse|InstallationImage|a204211eb0...
184 std::ifstream infile( historyFile_r.c_str() );
185 for( iostr::EachLine in( infile ); in; in.next() )
187 const char * ch( (*in).c_str() );
189 if ( *ch < '1' || '9' < *ch )
191 const char * sep1 = ::strchr( ch, '|' ); // | after date
195 // if logs an install or delete
196 bool installs = true;
197 if ( ::strncmp( sep1, "install|", 8 ) )
199 if ( ::strncmp( sep1, "remove |", 8 ) )
200 continue; // no install and no remove
202 installs = false; // remove
204 sep1 += 8; // | after what
205 // get the package name
206 const char * sep2 = ::strchr( sep1, '|' ); // | after name
207 if ( !sep2 || sep1 == sep2 )
209 (*in)[sep2-ch] = '\0';
210 IdString pkg( sep1 );
211 // we're done, if a delete
214 onSystemByUserList.erase( pkg );
217 // now guess whether user installed or not (3rd next field contains 'user@host')
218 if ( (sep1 = ::strchr( sep2+1, '|' )) // | after version
219 && (sep1 = ::strchr( sep1+1, '|' )) // | after arch
220 && (sep2 = ::strchr( sep1+1, '|' )) ) // | after who
222 (*in)[sep2-ch] = '\0';
223 if ( ::strchr( sep1+1, '@' ) )
226 onSystemByUserList.insert( pkg );
231 MIL << "onSystemByUserList found: " << onSystemByUserList.size() << endl;
232 return onSystemByUserList;
235 ///////////////////////////////////////////////////////////////////
237 ///////////////////////////////////////////////////////////////////
240 inline PluginFrame transactionPluginFrame( const std::string & command_r, ZYppCommitResult::TransactionStepList & steps_r )
242 return PluginFrame( command_r, json::Object {
243 { "TransactionStepList", steps_r }
247 ///////////////////////////////////////////////////////////////////
249 /** \internal Manage writing a new testcase when doing an upgrade. */
250 void writeUpgradeTestcase()
252 unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
253 MIL << "Testcases to keep: " << toKeep << endl;
256 Target_Ptr target( getZYpp()->getTarget() );
259 WAR << "No Target no Testcase!" << endl;
263 std::string stem( "updateTestcase" );
264 Pathname dir( target->assertRootPrefix("/var/log/") );
265 Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
268 std::list<std::string> content;
269 filesystem::readdir( content, dir, /*dots*/false );
270 std::set<std::string> cases;
271 for_( c, content.begin(), content.end() )
273 if ( str::startsWith( *c, stem ) )
276 if ( cases.size() >= toKeep )
278 unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
279 for_( c, cases.begin(), cases.end() )
281 filesystem::recursive_rmdir( dir/(*c) );
288 MIL << "Write new testcase " << next << endl;
289 getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
292 ///////////////////////////////////////////////////////////////////
294 { /////////////////////////////////////////////////////////////////
296 /** Execute script and report against report_r.
297 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
298 * execution was successfull (<tt>first = true</tt>), or the desired
299 * \c PatchScriptReport::Action in case execution failed
300 * (<tt>first = false</tt>).
302 * \note The packager is responsible for setting the correct permissions
303 * of the script. If the script is not executable it is reported as an
304 * error. We must not modify the permessions.
306 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
307 const Pathname & script_r,
308 callback::SendReport<PatchScriptReport> & report_r )
310 MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
312 HistoryLog historylog;
313 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
314 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
316 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
318 historylog.comment(output);
319 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
321 WAR << "User request to abort script " << script_r << endl;
323 // the rest is handled by exit code evaluation
324 // in case the script has meanwhile finished.
328 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
330 if ( prog.close() != 0 )
332 ret.second = report_r->problem( prog.execError() );
333 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
334 std::ostringstream sstr;
335 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
336 historylog.comment(sstr.str(), /*timestamp*/true);
345 /** Execute script and report against report_r.
346 * Return \c false if user requested \c ABORT.
348 bool executeScript( const Pathname & root_r,
349 const Pathname & script_r,
350 callback::SendReport<PatchScriptReport> & report_r )
352 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
355 action = doExecuteScript( root_r, script_r, report_r );
357 return true; // success
359 switch ( action.second )
361 case PatchScriptReport::ABORT:
362 WAR << "User request to abort at script " << script_r << endl;
363 return false; // requested abort.
366 case PatchScriptReport::IGNORE:
367 WAR << "User request to skip script " << script_r << endl;
368 return true; // requested skip.
371 case PatchScriptReport::RETRY:
374 } while ( action.second == PatchScriptReport::RETRY );
376 // THIS is not intended to be reached:
377 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
378 return false; // abort.
381 /** Look for update scripts named 'name-version-release-*' and
382 * execute them. Return \c false if \c ABORT was requested.
384 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
386 bool RunUpdateScripts( const Pathname & root_r,
387 const Pathname & scriptsPath_r,
388 const std::vector<sat::Solvable> & checkPackages_r,
391 if ( checkPackages_r.empty() )
392 return true; // no installed packages to check
394 MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
395 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
396 if ( ! PathInfo( scriptsDir ).isDir() )
397 return true; // no script dir
399 std::list<std::string> scripts;
400 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
401 if ( scripts.empty() )
402 return true; // no scripts in script dir
404 // Now collect and execute all matching scripts.
405 // On ABORT: at least log all outstanding scripts.
406 // - "name-version-release"
407 // - "name-version-release-*"
409 std::map<std::string, Pathname> unify; // scripts <md5,path>
410 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
412 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
413 for_( sit, scripts.begin(), scripts.end() )
415 if ( ! str::hasPrefix( *sit, prefix ) )
418 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
419 continue; // if not exact match it had to continue with '-'
421 PathInfo script( scriptsDir / *sit );
422 Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
423 std::string unifytag; // must not stay empty
425 if ( script.isFile() )
427 // Assert it's set executable, unify by md5sum.
428 filesystem::addmod( script.path(), 0500 );
429 unifytag = filesystem::md5sum( script.path() );
431 else if ( ! script.isExist() )
433 // Might be a dangling symlink, might be ok if we are in
434 // instsys (absolute symlink within the system below /mnt).
435 // readlink will tell....
436 unifytag = filesystem::readlink( script.path() ).asString();
439 if ( unifytag.empty() )
443 if ( unify[unifytag].empty() )
445 unify[unifytag] = localPath;
449 // translators: We may find the same script content in files with different names.
450 // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
451 // message for a log file. Preferably start translation with "%s"
452 std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
453 MIL << "Skip update script: " << msg << endl;
454 HistoryLog().comment( msg, /*timestamp*/true );
458 if ( abort || aborting_r )
460 WAR << "Aborting: Skip update script " << *sit << endl;
461 HistoryLog().comment(
462 localPath.asString() + _(" execution skipped while aborting"),
467 MIL << "Found update script " << *sit << endl;
468 callback::SendReport<PatchScriptReport> report;
469 report->start( make<Package>( *it ), script.path() );
471 if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
472 abort = true; // requested abort.
479 ///////////////////////////////////////////////////////////////////
481 ///////////////////////////////////////////////////////////////////
483 inline void copyTo( std::ostream & out_r, const Pathname & file_r )
485 std::ifstream infile( file_r.c_str() );
486 for( iostr::EachLine in( infile ); in; in.next() )
488 out_r << *in << endl;
492 inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
494 std::string ret( cmd_r );
495 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
496 SUBST_IF( "%p", notification_r.solvable().asString() );
497 SUBST_IF( "%P", notification_r.file().asString() );
502 void sendNotification( const Pathname & root_r,
503 const UpdateNotifications & notifications_r )
505 if ( notifications_r.empty() )
508 std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
509 MIL << "Notification command is '" << cmdspec << "'" << endl;
510 if ( cmdspec.empty() )
513 std::string::size_type pos( cmdspec.find( '|' ) );
514 if ( pos == std::string::npos )
516 ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
517 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
521 std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
522 std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
524 enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
525 Format format = UNKNOWN;
526 if ( formatStr == "none" )
528 else if ( formatStr == "single" )
530 else if ( formatStr == "digest" )
532 else if ( formatStr == "bulk" )
536 ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
537 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
541 // Take care: commands are ececuted chroot(root_r). The message file
542 // pathnames in notifications_r are local to root_r. For physical access
543 // to the file they need to be prefixed.
545 if ( format == NONE || format == SINGLE )
547 for_( it, notifications_r.begin(), notifications_r.end() )
549 std::vector<std::string> command;
550 if ( format == SINGLE )
551 command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
552 str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
554 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
555 if ( true ) // Wait for feedback
557 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
561 int ret = prog.close();
564 ERR << "Notification command returned with error (" << ret << ")." << endl;
565 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
571 else if ( format == DIGEST || format == BULK )
573 filesystem::TmpFile tmpfile;
574 ofstream out( tmpfile.path().c_str() );
575 for_( it, notifications_r.begin(), notifications_r.end() )
577 if ( format == DIGEST )
579 out << it->file() << endl;
581 else if ( format == BULK )
583 copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
587 std::vector<std::string> command;
588 command.push_back( "<"+tmpfile.path().asString() ); // redirect input
589 str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
591 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
592 if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
594 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
598 int ret = prog.close();
601 ERR << "Notification command returned with error (" << ret << ")." << endl;
602 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
609 INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
610 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
616 /** Look for update messages named 'name-version-release-*' and
617 * send notification according to \ref ZConfig::updateMessagesNotify.
619 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
621 void RunUpdateMessages( const Pathname & root_r,
622 const Pathname & messagesPath_r,
623 const std::vector<sat::Solvable> & checkPackages_r,
624 ZYppCommitResult & result_r )
626 if ( checkPackages_r.empty() )
627 return; // no installed packages to check
629 MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
630 Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
631 if ( ! PathInfo( messagesDir ).isDir() )
632 return; // no messages dir
634 std::list<std::string> messages;
635 filesystem::readdir( messages, messagesDir, /*dots*/false );
636 if ( messages.empty() )
637 return; // no messages in message dir
639 // Now collect all matching messages in result and send them
640 // - "name-version-release"
641 // - "name-version-release-*"
642 HistoryLog historylog;
643 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
645 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
646 for_( sit, messages.begin(), messages.end() )
648 if ( ! str::hasPrefix( *sit, prefix ) )
651 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
652 continue; // if not exact match it had to continue with '-'
654 PathInfo message( messagesDir / *sit );
655 if ( ! message.isFile() || message.size() == 0 )
658 MIL << "Found update message " << *sit << endl;
659 Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
660 result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
661 historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
664 sendNotification( root_r, result_r.updateMessages() );
667 /////////////////////////////////////////////////////////////////
669 ///////////////////////////////////////////////////////////////////
671 void XRunUpdateMessages( const Pathname & root_r,
672 const Pathname & messagesPath_r,
673 const std::vector<sat::Solvable> & checkPackages_r,
674 ZYppCommitResult & result_r )
675 { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
677 ///////////////////////////////////////////////////////////////////
679 IMPL_PTR_TYPE(TargetImpl);
681 ///////////////////////////////////////////////////////////////////
683 // METHOD NAME : TargetImpl::TargetImpl
684 // METHOD TYPE : Ctor
686 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
688 , _requestedLocalesFile( home() / "RequestedLocales" )
689 , _autoInstalledFile( home() / "AutoInstalled" )
690 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
692 _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
694 HistoryLog::setRoot(_root);
697 sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
698 MIL << "Initialized target on " << _root << endl;
702 * generates a random id using uuidgen
704 static std::string generateRandomId()
706 std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
707 return iostr::getline( uuidprovider );
711 * updates the content of \p filename
712 * if \p condition is true, setting the content
713 * the the value returned by \p value
715 void updateFileContent( const Pathname &filename,
716 boost::function<bool ()> condition,
717 boost::function<string ()> value )
719 string val = value();
720 // if the value is empty, then just dont
721 // do anything, regardless of the condition
727 MIL << "updating '" << filename << "' content." << endl;
729 // if the file does not exist we need to generate the uuid file
731 std::ofstream filestr;
732 // make sure the path exists
733 filesystem::assert_dir( filename.dirname() );
734 filestr.open( filename.c_str() );
736 if ( filestr.good() )
743 // FIXME, should we ignore the error?
744 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
749 /** helper functor */
750 static bool fileMissing( const Pathname &pathname )
752 return ! PathInfo(pathname).isExist();
755 void TargetImpl::createAnonymousId() const
757 // bsc#1024741: Omit creating a new uid for chrooted systems (if it already has one, fine)
761 // Create the anonymous unique id, used for download statistics
762 Pathname idpath( home() / "AnonymousUniqueId");
766 updateFileContent( idpath,
767 boost::bind(fileMissing, idpath),
770 catch ( const Exception &e )
772 WAR << "Can't create anonymous id file" << endl;
777 void TargetImpl::createLastDistributionFlavorCache() const
779 // create the anonymous unique id
780 // this value is used for statistics
781 Pathname flavorpath( home() / "LastDistributionFlavor");
783 // is there a product
784 Product::constPtr p = baseProduct();
787 WAR << "No base product, I won't create flavor cache" << endl;
791 string flavor = p->flavor();
796 updateFileContent( flavorpath,
797 // only if flavor is not empty
798 functor::Constant<bool>( ! flavor.empty() ),
799 functor::Constant<string>(flavor) );
801 catch ( const Exception &e )
803 WAR << "Can't create flavor cache" << endl;
808 ///////////////////////////////////////////////////////////////////
810 // METHOD NAME : TargetImpl::~TargetImpl
811 // METHOD TYPE : Dtor
813 TargetImpl::~TargetImpl()
815 _rpm.closeDatabase();
816 sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
817 MIL << "Targets closed" << endl;
820 ///////////////////////////////////////////////////////////////////
822 // solv file handling
824 ///////////////////////////////////////////////////////////////////
826 Pathname TargetImpl::defaultSolvfilesPath() const
828 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
831 void TargetImpl::clearCache()
833 Pathname base = solvfilesPath();
834 filesystem::recursive_rmdir( base );
837 bool TargetImpl::buildCache()
839 Pathname base = solvfilesPath();
840 Pathname rpmsolv = base/"solv";
841 Pathname rpmsolvcookie = base/"cookie";
843 bool build_rpm_solv = true;
844 // lets see if the rpm solv cache exists
846 RepoStatus rpmstatus( RepoStatus(_root/"var/lib/rpm/Name") && RepoStatus(_root/"etc/products.d") );
848 bool solvexisted = PathInfo(rpmsolv).isExist();
851 // see the status of the cache
852 PathInfo cookie( rpmsolvcookie );
853 MIL << "Read cookie: " << cookie << endl;
854 if ( cookie.isExist() )
856 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
857 // now compare it with the rpm database
858 if ( status == rpmstatus )
859 build_rpm_solv = false;
860 MIL << "Read cookie: " << rpmsolvcookie << " says: "
861 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
865 if ( build_rpm_solv )
867 // if the solvfile dir does not exist yet, we better create it
868 filesystem::assert_dir( base );
870 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
872 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
875 // Can't create temporary solv file, usually due to insufficient permission
876 // (user query while @System solv needs refresh). If so, try switching
877 // to a location within zypps temp. space (will be cleaned at application end).
879 bool switchingToTmpSolvfile = false;
880 Exception ex("Failed to cache rpm database.");
881 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
883 if ( ! solvfilesPathIsTemp() )
885 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
886 rpmsolv = base/"solv";
887 rpmsolvcookie = base/"cookie";
889 filesystem::assert_dir( base );
890 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
894 WAR << "Using a temporary solv file at " << base << endl;
895 switchingToTmpSolvfile = true;
896 _tmpSolvfilesPath = base;
900 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
904 if ( ! switchingToTmpSolvfile )
910 // Take care we unlink the solvfile on exception
911 ManagedFile guard( base, filesystem::recursive_rmdir );
913 ExternalProgram::Arguments cmd;
914 cmd.push_back( "rpmdb2solv" );
915 if ( ! _root.empty() ) {
916 cmd.push_back( "-r" );
917 cmd.push_back( _root.asString() );
919 cmd.push_back( "-X" ); // autogenerate pattern/product/... from -package
920 // bsc#1104415: no more application support // cmd.push_back( "-A" ); // autogenerate application pseudo packages
921 cmd.push_back( "-p" );
922 cmd.push_back( Pathname::assertprefix( _root, "/etc/products.d" ).asString() );
924 if ( ! oldSolvFile.empty() )
925 cmd.push_back( oldSolvFile.asString() );
927 cmd.push_back( "-o" );
928 cmd.push_back( tmpsolv.path().asString() );
930 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
931 std::string errdetail;
933 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
934 WAR << " " << output;
935 if ( errdetail.empty() ) {
936 errdetail = prog.command();
942 int ret = prog.close();
945 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
946 ex.remember( errdetail );
950 ret = filesystem::rename( tmpsolv, rpmsolv );
952 ZYPP_THROW(Exception("Failed to move cache to final destination"));
953 // if this fails, don't bother throwing exceptions
954 filesystem::chmod( rpmsolv, 0644 );
956 rpmstatus.saveToCookieFile(rpmsolvcookie);
959 guard.resetDispose();
960 sat::updateSolvFileIndex( rpmsolv ); // content digest for zypper bash completion
962 // system-hook: Finally send notification to plugins
965 PluginExecutor plugins;
966 plugins.load( ZConfig::instance().pluginsPath()/"system" );
968 plugins.send( PluginFrame( "PACKAGESETCHANGED" ) );
973 // On the fly add missing solv.idx files for bash completion.
974 if ( ! PathInfo(base/"solv.idx").isExist() )
975 sat::updateSolvFileIndex( rpmsolv );
977 return build_rpm_solv;
980 void TargetImpl::reload()
985 void TargetImpl::unload()
987 Repository system( sat::Pool::instance().findSystemRepo() );
989 system.eraseFromPool();
992 void TargetImpl::load( bool force )
994 bool newCache = buildCache();
995 MIL << "New cache built: " << (newCache?"true":"false") <<
996 ", force loading: " << (force?"true":"false") << endl;
998 // now add the repos to the pool
999 sat::Pool satpool( sat::Pool::instance() );
1000 Pathname rpmsolv( solvfilesPath() / "solv" );
1001 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
1003 // Providing an empty system repo, unload any old content
1004 Repository system( sat::Pool::instance().findSystemRepo() );
1006 if ( system && ! system.solvablesEmpty() )
1008 if ( newCache || force )
1010 system.eraseFromPool(); // invalidates system
1014 return; // nothing to do
1020 system = satpool.systemRepo();
1025 MIL << "adding " << rpmsolv << " to system" << endl;
1026 system.addSolv( rpmsolv );
1028 catch ( const Exception & exp )
1031 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1035 system.addSolv( rpmsolv );
1037 satpool.rootDir( _root );
1039 // (Re)Load the requested locales et al.
1040 // If the requested locales are empty, we leave the pool untouched
1041 // to avoid undoing changes the application applied. We expect this
1042 // to happen on a bare metal installation only. An already existing
1043 // target should be loaded before its settings are changed.
1045 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1046 if ( ! requestedLocales.empty() )
1048 satpool.initRequestedLocales( requestedLocales );
1052 if ( ! PathInfo( _autoInstalledFile.file() ).isExist() )
1054 // Initialize from history, if it does not exist
1055 Pathname historyFile( Pathname::assertprefix( _root, ZConfig::instance().historyLogFile() ) );
1056 if ( PathInfo( historyFile ).isExist() )
1058 SolvIdentFile::Data onSystemByUser( getUserInstalledFromHistory( historyFile ) );
1059 SolvIdentFile::Data onSystemByAuto;
1060 for_( it, system.solvablesBegin(), system.solvablesEnd() )
1062 IdString ident( (*it).ident() );
1063 if ( onSystemByUser.find( ident ) == onSystemByUser.end() )
1064 onSystemByAuto.insert( ident );
1066 _autoInstalledFile.setData( onSystemByAuto );
1068 // on the fly removed any obsolete SoftLocks file
1069 filesystem::unlink( home() / "SoftLocks" );
1071 // read from AutoInstalled file
1073 for ( const auto & idstr : _autoInstalledFile.data() )
1074 q.push( idstr.id() );
1075 satpool.setAutoInstalled( q );
1078 // Load the needreboot package specs
1080 sat::SolvableSpec needrebootSpec;
1082 Pathname needrebootFile { Pathname::assertprefix( root(), ZConfig::instance().needrebootFile() ) };
1083 if ( PathInfo( needrebootFile ).isFile() )
1084 needrebootSpec.parseFrom( needrebootFile );
1086 Pathname needrebootDir { Pathname::assertprefix( root(), ZConfig::instance().needrebootPath() ) };
1087 if ( PathInfo( needrebootDir ).isDir() )
1089 static const StrMatcher isRpmConfigBackup( "\\.rpm(new|save|orig)$", Match::REGEX );
1091 filesystem::dirForEach( needrebootDir, filesystem::matchNoDots(),
1092 [&]( const Pathname & dir_r, const char *const str_r )->bool
1094 if ( ! isRpmConfigBackup( str_r ) )
1096 Pathname needrebootFile { needrebootDir / str_r };
1097 if ( PathInfo( needrebootFile ).isFile() )
1098 needrebootSpec.parseFrom( needrebootFile );
1104 INT << "Needreboot " << needrebootSpec << endl;
1105 satpool.setNeedrebootSpec( std::move(needrebootSpec) );
1108 if ( ZConfig::instance().apply_locks_file() )
1110 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1111 if ( ! hardLocks.empty() )
1113 ResPool::instance().setHardLockQueries( hardLocks );
1117 // now that the target is loaded, we can cache the flavor
1118 createLastDistributionFlavorCache();
1120 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1123 ///////////////////////////////////////////////////////////////////
1127 ///////////////////////////////////////////////////////////////////
1128 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1130 // ----------------------------------------------------------------- //
1131 ZYppCommitPolicy policy_r( policy_rX );
1132 ShutdownLock lck("Zypp commit running.");
1134 // Fake outstanding YCP fix: Honour restriction to media 1
1135 // at installation, but install all remaining packages if post-boot.
1136 if ( policy_r.restrictToMedia() > 1 )
1137 policy_r.allMedia();
1139 if ( policy_r.downloadMode() == DownloadDefault ) {
1140 if ( root() == "/" )
1141 policy_r.downloadMode(DownloadInHeaps);
1143 policy_r.downloadMode(DownloadAsNeeded);
1145 // DownloadOnly implies dry-run.
1146 else if ( policy_r.downloadMode() == DownloadOnly )
1147 policy_r.dryRun( true );
1148 // ----------------------------------------------------------------- //
1150 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1152 ///////////////////////////////////////////////////////////////////
1153 // Compute transaction:
1154 ///////////////////////////////////////////////////////////////////
1155 ZYppCommitResult result( root() );
1156 result.rTransaction() = pool_r.resolver().getTransaction();
1157 result.rTransaction().order();
1158 // steps: this is our todo-list
1159 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1160 if ( policy_r.restrictToMedia() )
1162 // Collect until the 1st package from an unwanted media occurs.
1163 // Further collection could violate install order.
1164 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1165 for_( it, result.transaction().begin(), result.transaction().end() )
1167 if ( makeResObject( *it )->mediaNr() > 1 )
1169 steps.push_back( *it );
1174 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1176 MIL << "Todo: " << result << endl;
1178 ///////////////////////////////////////////////////////////////////
1179 // Prepare execution of commit plugins:
1180 ///////////////////////////////////////////////////////////////////
1181 PluginExecutor commitPlugins;
1182 if ( root() == "/" && ! policy_r.dryRun() )
1184 commitPlugins.load( ZConfig::instance().pluginsPath()/"commit" );
1186 if ( commitPlugins )
1187 commitPlugins.send( transactionPluginFrame( "COMMITBEGIN", steps ) );
1189 ///////////////////////////////////////////////////////////////////
1190 // Write out a testcase if we're in dist upgrade mode.
1191 ///////////////////////////////////////////////////////////////////
1192 if ( pool_r.resolver().upgradeMode() || pool_r.resolver().upgradingRepos() )
1194 if ( ! policy_r.dryRun() )
1196 writeUpgradeTestcase();
1200 DBG << "dryRun: Not writing upgrade testcase." << endl;
1204 ///////////////////////////////////////////////////////////////////
1205 // Store non-package data:
1206 ///////////////////////////////////////////////////////////////////
1207 if ( ! policy_r.dryRun() )
1209 filesystem::assert_dir( home() );
1210 // requested locales
1211 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1214 SolvIdentFile::Data newdata;
1215 for ( sat::Queue::value_type id : result.rTransaction().autoInstalled() )
1216 newdata.insert( IdString(id) );
1217 _autoInstalledFile.setData( newdata );
1220 if ( ZConfig::instance().apply_locks_file() )
1222 HardLocksFile::Data newdata;
1223 pool_r.getHardLockQueries( newdata );
1224 _hardLocksFile.setData( newdata );
1229 DBG << "dryRun: Not stroring non-package data." << endl;
1232 ///////////////////////////////////////////////////////////////////
1233 // First collect and display all messages
1234 // associated with patches to be installed.
1235 ///////////////////////////////////////////////////////////////////
1236 if ( ! policy_r.dryRun() )
1238 for_( it, steps.begin(), steps.end() )
1240 if ( ! it->satSolvable().isKind<Patch>() )
1244 if ( ! pi.status().isToBeInstalled() )
1247 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1248 if ( ! patch ||patch->message().empty() )
1251 MIL << "Show message for " << patch << endl;
1252 callback::SendReport<target::PatchMessageReport> report;
1253 if ( ! report->show( patch ) )
1255 WAR << "commit aborted by the user" << endl;
1256 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1262 DBG << "dryRun: Not checking patch messages." << endl;
1265 ///////////////////////////////////////////////////////////////////
1266 // Remove/install packages.
1267 ///////////////////////////////////////////////////////////////////
1268 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1269 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1271 // Prepare the package cache. Pass all items requiring download.
1272 CommitPackageCache packageCache;
1273 packageCache.setCommitList( steps.begin(), steps.end() );
1276 if ( policy_r.downloadMode() != DownloadAsNeeded )
1278 // Preload the cache. Until now this means pre-loading all packages.
1279 // Once DownloadInHeaps is fully implemented, this will change and
1280 // we may actually have more than one heap.
1281 for_( it, steps.begin(), steps.end() )
1283 switch ( it->stepType() )
1285 case sat::Transaction::TRANSACTION_INSTALL:
1286 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1287 // proceed: only install actionas may require download.
1291 // next: no download for or non-packages and delete actions.
1297 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1299 ManagedFile localfile;
1302 localfile = packageCache.get( pi );
1303 localfile.resetDispose(); // keep the package file in the cache
1305 catch ( const AbortRequestException & exp )
1307 it->stepStage( sat::Transaction::STEP_ERROR );
1309 WAR << "commit cache preload aborted by the user" << endl;
1310 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1313 catch ( const SkipRequestException & exp )
1316 it->stepStage( sat::Transaction::STEP_ERROR );
1318 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1321 catch ( const Exception & exp )
1323 // bnc #395704: missing catch causes abort.
1324 // TODO see if packageCache fails to handle errors correctly.
1326 it->stepStage( sat::Transaction::STEP_ERROR );
1328 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1333 packageCache.preloaded( true ); // try to avoid duplicate infoInCache CBs in commit
1338 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1342 if ( ! policy_r.dryRun() )
1344 // if cache is preloaded, check for file conflicts
1345 commitFindFileConflicts( policy_r, result );
1346 commit( policy_r, packageCache, result );
1350 DBG << "dryRun/downloadOnly: Not installing/deleting anything." << endl;
1356 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1359 ///////////////////////////////////////////////////////////////////
1360 // Send result to commit plugins:
1361 ///////////////////////////////////////////////////////////////////
1362 if ( commitPlugins )
1363 commitPlugins.send( transactionPluginFrame( "COMMITEND", steps ) );
1365 ///////////////////////////////////////////////////////////////////
1366 // Try to rebuild solv file while rpm database is still in cache
1367 ///////////////////////////////////////////////////////////////////
1368 if ( ! policy_r.dryRun() )
1373 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1377 ///////////////////////////////////////////////////////////////////
1381 ///////////////////////////////////////////////////////////////////
1384 struct NotifyAttemptToModify
1386 NotifyAttemptToModify( ZYppCommitResult & result_r ) : _result( result_r ) {}
1389 { if ( _guard ) { _result.attemptToModify( true ); _guard = false; } }
1392 ZYppCommitResult & _result;
1396 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1397 CommitPackageCache & packageCache_r,
1398 ZYppCommitResult & result_r )
1400 // steps: this is our todo-list
1401 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1402 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1404 HistoryLog().stampCommand();
1406 // Send notification once upon 1st call to rpm
1407 NotifyAttemptToModify attemptToModify( result_r );
1411 RpmPostTransCollector postTransCollector( _root );
1412 std::vector<sat::Solvable> successfullyInstalledPackages;
1413 TargetImpl::PoolItemList remaining;
1415 for_( step, steps.begin(), steps.end() )
1417 PoolItem citem( *step );
1418 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1420 if ( citem->isKind<Package>() )
1422 // for packages this means being obsoleted (by rpm)
1423 // thius no additional action is needed.
1424 step->stepStage( sat::Transaction::STEP_DONE );
1429 if ( citem->isKind<Package>() )
1431 Package::constPtr p = citem->asKind<Package>();
1432 if ( citem.status().isToBeInstalled() )
1434 ManagedFile localfile;
1437 localfile = packageCache_r.get( citem );
1439 catch ( const AbortRequestException &e )
1441 WAR << "commit aborted by the user" << endl;
1443 step->stepStage( sat::Transaction::STEP_ERROR );
1446 catch ( const SkipRequestException &e )
1449 WAR << "Skipping package " << p << " in commit" << endl;
1450 step->stepStage( sat::Transaction::STEP_ERROR );
1453 catch ( const Exception &e )
1455 // bnc #395704: missing catch causes abort.
1456 // TODO see if packageCache fails to handle errors correctly.
1458 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1459 step->stepStage( sat::Transaction::STEP_ERROR );
1463 #warning Exception handling
1464 // create a installation progress report proxy
1465 RpmInstallPackageReceiver progress( citem.resolvable() );
1466 progress.connect(); // disconnected on destruction.
1468 bool success = false;
1469 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1470 // Why force and nodeps?
1472 // Because zypp builds the transaction and the resolver asserts that
1473 // everything is fine.
1474 // We use rpm just to unpack and register the package in the database.
1475 // We do this step by step, so rpm is not aware of the bigger context.
1476 // So we turn off rpms internal checks, because we do it inside zypp.
1477 flags |= rpm::RPMINST_NODEPS;
1478 flags |= rpm::RPMINST_FORCE;
1480 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1481 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1482 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1483 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1488 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1489 if ( postTransCollector.collectScriptFromPackage( localfile ) )
1490 flags |= rpm::RPMINST_NOPOSTTRANS;
1491 rpm().installPackage( localfile, flags );
1492 HistoryLog().install(citem);
1494 if ( progress.aborted() )
1496 WAR << "commit aborted by the user" << endl;
1497 localfile.resetDispose(); // keep the package file in the cache
1499 step->stepStage( sat::Transaction::STEP_ERROR );
1504 if ( citem.isNeedreboot() ) {
1505 auto rebootNeededFile = root() / "/var/run/reboot-needed";
1506 if ( filesystem::assert_file( rebootNeededFile ) == EEXIST)
1507 filesystem::touch( rebootNeededFile );
1511 step->stepStage( sat::Transaction::STEP_DONE );
1514 catch ( Exception & excpt_r )
1516 ZYPP_CAUGHT(excpt_r);
1517 localfile.resetDispose(); // keep the package file in the cache
1519 if ( policy_r.dryRun() )
1521 WAR << "dry run failed" << endl;
1522 step->stepStage( sat::Transaction::STEP_ERROR );
1526 if ( progress.aborted() )
1528 WAR << "commit aborted by the user" << endl;
1533 WAR << "Install failed" << endl;
1535 step->stepStage( sat::Transaction::STEP_ERROR );
1539 if ( success && !policy_r.dryRun() )
1541 citem.status().resetTransact( ResStatus::USER );
1542 successfullyInstalledPackages.push_back( citem.satSolvable() );
1543 step->stepStage( sat::Transaction::STEP_DONE );
1548 RpmRemovePackageReceiver progress( citem.resolvable() );
1549 progress.connect(); // disconnected on destruction.
1551 bool success = false;
1552 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1553 flags |= rpm::RPMINST_NODEPS;
1554 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1559 rpm().removePackage( p, flags );
1560 HistoryLog().remove(citem);
1562 if ( progress.aborted() )
1564 WAR << "commit aborted by the user" << endl;
1566 step->stepStage( sat::Transaction::STEP_ERROR );
1572 step->stepStage( sat::Transaction::STEP_DONE );
1575 catch (Exception & excpt_r)
1577 ZYPP_CAUGHT( excpt_r );
1578 if ( progress.aborted() )
1580 WAR << "commit aborted by the user" << endl;
1582 step->stepStage( sat::Transaction::STEP_ERROR );
1586 WAR << "removal of " << p << " failed";
1587 step->stepStage( sat::Transaction::STEP_ERROR );
1589 if ( success && !policy_r.dryRun() )
1591 citem.status().resetTransact( ResStatus::USER );
1592 step->stepStage( sat::Transaction::STEP_DONE );
1596 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1598 // Status is changed as the buddy package buddy
1599 // gets installed/deleted. Handle non-buddies only.
1600 if ( ! citem.buddy() )
1602 if ( citem->isKind<Product>() )
1604 Product::constPtr p = citem->asKind<Product>();
1605 if ( citem.status().isToBeInstalled() )
1607 ERR << "Can't install orphan product without release-package! " << citem << endl;
1611 // Deleting the corresponding product entry is all we con do.
1612 // So the product will no longer be visible as installed.
1613 std::string referenceFilename( p->referenceFilename() );
1614 if ( referenceFilename.empty() )
1616 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1620 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1621 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1623 ERR << "Delete orphan product failed: " << referenceFile << endl;
1628 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1630 // SrcPackage is install-only
1631 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1632 installSrcPackage( p );
1635 citem.status().resetTransact( ResStatus::USER );
1636 step->stepStage( sat::Transaction::STEP_DONE );
1639 } // other resolvables
1643 // process all remembered posttrans scripts. If aborting,
1644 // at least log omitted scripts.
1645 if ( abort || (abort = !postTransCollector.executeScripts()) )
1646 postTransCollector.discardScripts();
1648 // Check presence of update scripts/messages. If aborting,
1649 // at least log omitted scripts.
1650 if ( ! successfullyInstalledPackages.empty() )
1652 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1653 successfullyInstalledPackages, abort ) )
1655 WAR << "Commit aborted by the user" << endl;
1658 // send messages after scripts in case some script generates output,
1659 // that should be kept in t %ghost message file.
1660 RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1661 successfullyInstalledPackages,
1667 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1671 ///////////////////////////////////////////////////////////////////
1673 rpm::RpmDb & TargetImpl::rpm()
1678 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1680 return _rpm.hasFile(path_str, name_str);
1684 Date TargetImpl::timestamp() const
1686 return _rpm.timestamp();
1689 ///////////////////////////////////////////////////////////////////
1692 parser::ProductFileData baseproductdata( const Pathname & root_r )
1694 parser::ProductFileData ret;
1695 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1697 if ( baseproduct.isFile() )
1701 ret = parser::ProductFileReader::scanFile( baseproduct.path() );
1703 catch ( const Exception & excpt )
1705 ZYPP_CAUGHT( excpt );
1708 else if ( PathInfo( Pathname::assertprefix( root_r, "/etc/products.d" ) ).isDir() )
1710 ERR << "baseproduct symlink is dangling or missing: " << baseproduct << endl;
1715 inline Pathname staticGuessRoot( const Pathname & root_r )
1717 if ( root_r.empty() )
1719 // empty root: use existing Target or assume "/"
1720 Pathname ret ( ZConfig::instance().systemRoot() );
1722 return Pathname("/");
1728 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1730 std::ifstream idfile( file_r.c_str() );
1731 for( iostr::EachLine in( idfile ); in; in.next() )
1733 std::string line( str::trim( *in ) );
1734 if ( ! line.empty() )
1737 return std::string();
1740 ///////////////////////////////////////////////////////////////////
1742 Product::constPtr TargetImpl::baseProduct() const
1744 ResPool pool(ResPool::instance());
1745 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1747 Product::constPtr p = (*it)->asKind<Product>();
1748 if ( p->isTargetDistribution() )
1754 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1756 const Pathname needroot( staticGuessRoot(root_r) );
1757 const Target_constPtr target( getZYpp()->getTarget() );
1758 if ( target && target->root() == needroot )
1759 return target->requestedLocales();
1760 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1763 void TargetImpl::updateAutoInstalled()
1765 MIL << "updateAutoInstalled if changed..." << endl;
1766 SolvIdentFile::Data newdata;
1767 for ( auto id : sat::Pool::instance().autoInstalled() )
1768 newdata.insert( IdString(id) ); // explicit ctor!
1769 _autoInstalledFile.setData( std::move(newdata) );
1772 std::string TargetImpl::targetDistribution() const
1773 { return baseproductdata( _root ).registerTarget(); }
1775 std::string TargetImpl::targetDistribution( const Pathname & root_r )
1776 { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1778 std::string TargetImpl::targetDistributionRelease() const
1779 { return baseproductdata( _root ).registerRelease(); }
1781 std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1782 { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1784 std::string TargetImpl::targetDistributionFlavor() const
1785 { return baseproductdata( _root ).registerFlavor(); }
1787 std::string TargetImpl::targetDistributionFlavor( const Pathname & root_r )
1788 { return baseproductdata( staticGuessRoot(root_r) ).registerFlavor();}
1790 Target::DistributionLabel TargetImpl::distributionLabel() const
1792 Target::DistributionLabel ret;
1793 parser::ProductFileData pdata( baseproductdata( _root ) );
1794 ret.shortName = pdata.shortName();
1795 ret.summary = pdata.summary();
1799 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1801 Target::DistributionLabel ret;
1802 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1803 ret.shortName = pdata.shortName();
1804 ret.summary = pdata.summary();
1808 std::string TargetImpl::distributionVersion() const
1810 if ( _distributionVersion.empty() )
1812 _distributionVersion = TargetImpl::distributionVersion(root());
1813 if ( !_distributionVersion.empty() )
1814 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1816 return _distributionVersion;
1819 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1821 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1822 if ( distributionVersion.empty() )
1824 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1825 // On RHEL, Fedora and others the "product version" is determined by the first package
1826 // providing 'system-release'. This value is not hardcoded in YUM and can be configured
1827 // with the $distroverpkg variable.
1828 scoped_ptr<rpm::RpmDb> tmprpmdb;
1829 if ( ZConfig::instance().systemRoot() == Pathname() )
1833 tmprpmdb.reset( new rpm::RpmDb );
1834 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1841 rpm::librpmDb::db_const_iterator it;
1842 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1843 distributionVersion = it->tag_version();
1845 return distributionVersion;
1849 std::string TargetImpl::distributionFlavor() const
1851 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1854 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1856 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1859 ///////////////////////////////////////////////////////////////////
1862 std::string guessAnonymousUniqueId( const Pathname & root_r )
1864 // bsc#1024741: Omit creating a new uid for chrooted systems (if it already has one, fine)
1865 std::string ret( firstNonEmptyLineIn( root_r / "/var/lib/zypp/AnonymousUniqueId" ) );
1866 if ( ret.empty() && root_r != "/" )
1868 // if it has nonoe, use the outer systems one
1869 ret = firstNonEmptyLineIn( "/var/lib/zypp/AnonymousUniqueId" );
1875 std::string TargetImpl::anonymousUniqueId() const
1877 return guessAnonymousUniqueId( root() );
1880 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1882 return guessAnonymousUniqueId( staticGuessRoot(root_r) );
1885 ///////////////////////////////////////////////////////////////////
1887 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1889 // provide on local disk
1890 ManagedFile localfile = provideSrcPackage(srcPackage_r);
1891 // create a installation progress report proxy
1892 RpmInstallPackageReceiver progress( srcPackage_r );
1893 progress.connect(); // disconnected on destruction.
1895 rpm().installPackage ( localfile );
1898 ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1900 // provide on local disk
1901 repo::RepoMediaAccess access_r;
1902 repo::SrcPackageProvider prov( access_r );
1903 return prov.provideSrcPackage( srcPackage_r );
1905 ////////////////////////////////////////////////////////////////
1906 } // namespace target
1907 ///////////////////////////////////////////////////////////////////
1908 /////////////////////////////////////////////////////////////////
1910 ///////////////////////////////////////////////////////////////////