1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/target/TargetImpl.cc
19 #include <sys/types.h>
22 #include "zypp/base/LogTools.h"
23 #include "zypp/base/Exception.h"
24 #include "zypp/base/Iterator.h"
25 #include "zypp/base/Gettext.h"
26 #include "zypp/base/IOStream.h"
27 #include "zypp/base/Functional.h"
28 #include "zypp/base/UserRequestException.h"
29 #include "zypp/base/Json.h"
31 #include "zypp/ZConfig.h"
32 #include "zypp/ZYppFactory.h"
34 #include "zypp/PoolItem.h"
35 #include "zypp/ResObjects.h"
37 #include "zypp/TmpPath.h"
38 #include "zypp/RepoStatus.h"
39 #include "zypp/ExternalProgram.h"
40 #include "zypp/Repository.h"
42 #include "zypp/ResFilters.h"
43 #include "zypp/HistoryLog.h"
44 #include "zypp/target/TargetImpl.h"
45 #include "zypp/target/TargetCallbackReceiver.h"
46 #include "zypp/target/rpm/librpmDb.h"
47 #include "zypp/target/CommitPackageCache.h"
48 #include "zypp/target/RpmPostTransCollector.h"
50 #include "zypp/parser/ProductFileReader.h"
52 #include "zypp/solver/detail/Testcase.h"
54 #include "zypp/repo/SrcPackageProvider.h"
56 #include "zypp/sat/Pool.h"
57 #include "zypp/sat/Transaction.h"
59 #include "zypp/PluginScript.h"
63 ///////////////////////////////////////////////////////////////////
65 { /////////////////////////////////////////////////////////////////
66 ///////////////////////////////////////////////////////////////////
69 // Lazy via template specialisation / should switch to overloading
72 inline std::string toJSON( const ZYppCommitResult::TransactionStepList & steps_r )
74 using sat::Transaction;
77 for ( const Transaction::Step & step : steps_r )
78 // ignore implicit deletes due to obsoletes and non-package actions
79 if ( step.stepType() != Transaction::TRANSACTION_IGNORE )
85 /** See \ref commitbegin on page \ref plugin-commit for the specs. */
87 inline std::string toJSON( const sat::Transaction::Step & step_r )
89 static const std::string strType( "type" );
90 static const std::string strStage( "stage" );
91 static const std::string strSolvable( "solvable" );
93 static const std::string strTypeDel( "-" );
94 static const std::string strTypeIns( "+" );
95 static const std::string strTypeMul( "M" );
97 static const std::string strStageDone( "ok" );
98 static const std::string strStageFailed( "err" );
100 static const std::string strSolvableN( "n" );
101 static const std::string strSolvableE( "e" );
102 static const std::string strSolvableV( "v" );
103 static const std::string strSolvableR( "r" );
104 static const std::string strSolvableA( "a" );
106 using sat::Transaction;
109 switch ( step_r.stepType() )
111 case Transaction::TRANSACTION_IGNORE: /*empty*/ break;
112 case Transaction::TRANSACTION_ERASE: ret.add( strType, strTypeDel ); break;
113 case Transaction::TRANSACTION_INSTALL: ret.add( strType, strTypeIns ); break;
114 case Transaction::TRANSACTION_MULTIINSTALL: ret.add( strType, strTypeMul ); break;
117 switch ( step_r.stepStage() )
119 case Transaction::STEP_TODO: /*empty*/ break;
120 case Transaction::STEP_DONE: ret.add( strStage, strStageDone ); break;
121 case Transaction::STEP_ERROR: ret.add( strStage, strStageFailed ); break;
128 if ( sat::Solvable solv = step_r.satSolvable() )
130 ident = solv.ident();
136 // deleted package; post mortem data stored in Transaction::Step
137 ident = step_r.ident();
138 ed = step_r.edition();
139 arch = step_r.arch();
143 { strSolvableN, ident.asString() },
144 { strSolvableV, ed.version() },
145 { strSolvableR, ed.release() },
146 { strSolvableA, arch.asString() }
148 if ( Edition::epoch_t epoch = ed.epoch() )
149 s.add( strSolvableE, epoch );
151 ret.add( strSolvable, s );
157 ///////////////////////////////////////////////////////////////////
158 ///////////////////////////////////////////////////////////////////
160 { /////////////////////////////////////////////////////////////////
162 /** Helper for commit plugin execution.
165 class CommitPlugins : private base::NonCopyable
168 /** Default ctor: Empty plugin list */
172 /** Dtor: Send PLUGINEND message and close plugins. */
175 if ( ! _scripts.empty() )
176 send( PluginFrame( "PLUGINEND" ) );
177 // ~PluginScript will disconnect all remaining plugins!
180 /** Whether no plugins are waiting */
182 { return _scripts.empty(); }
185 /** Send \ref PluginFrame to all open plugins.
186 * Failed plugins are removed from the execution list.
188 void send( const PluginFrame & frame_r )
190 DBG << "+++++++++++++++ send " << frame_r << endl;
191 for ( auto it = _scripts.begin(); it != _scripts.end(); )
193 doSend( *it, frame_r );
197 it = _scripts.erase( it );
199 DBG << "--------------- send " << frame_r << endl;
202 /** Find and launch plugins sending PLUGINSTART message.
204 * If \a path_r is a directory all executable files whithin are
205 * expected to be plugins. Otherwise \a path_r must point to an
208 void load( const Pathname & path_r )
210 PathInfo pi( path_r );
211 DBG << "+++++++++++++++ load " << pi << endl;
214 std::list<Pathname> entries;
215 if ( filesystem::readdir( entries, pi.path(), false ) != 0 )
217 WAR << "Plugin dir is not readable: " << pi << endl;
220 for_( it, entries.begin(), entries.end() )
223 if ( pii.isFile() && pii.userMayRX() )
227 else if ( pi.isFile() )
229 if ( pi.userMayRX() )
232 WAR << "Plugin file is not executable: " << pi << endl;
236 WAR << "Plugin path is neither dir nor file: " << pi << endl;
238 DBG << "--------------- load " << pi << endl;
242 /** Send \ref PluginFrame and expect valid answer (ACK|_ENOMETHOD).
243 * Upon invalid answer or error, close the plugin. and remove it from the
245 * \returns the received \ref PluginFrame (empty Frame upon Exception)
247 PluginFrame doSend( PluginScript & script_r, const PluginFrame & frame_r )
252 script_r.send( frame_r );
253 ret = script_r.receive();
255 catch( const zypp::Exception & e )
258 if ( ! ( ret.isAckCommand() || ret.isEnomethodCommand() ) )
260 WAR << "Bad plugin response from " << script_r << endl;
261 WAR << dump(ret) << endl;
268 /** Launch a plugin sending PLUGINSTART message. */
269 void doLoad( const PathInfo & pi_r )
271 MIL << "Load plugin: " << pi_r << endl;
273 PluginScript plugin( pi_r.path() );
276 PluginFrame frame( "PLUGINBEGIN" );
277 if ( ZConfig::instance().hasUserData() )
278 frame.setHeader( "userdata", ZConfig::instance().userData() );
280 doSend( plugin, frame ); // closes on error
281 if ( plugin.isOpen() )
282 _scripts.push_back( plugin );
284 catch( const zypp::Exception & e )
286 WAR << "Failed to load plugin " << pi_r << endl;
291 std::list<PluginScript> _scripts;
294 void testCommitPlugins( const Pathname & path_r ) // for testing only
296 USR << "+++++" << endl;
300 USR << "=====" << endl;
302 USR << "-----" << endl;
305 ///////////////////////////////////////////////////////////////////
308 inline PluginFrame transactionPluginFrame( const std::string & command_r, ZYppCommitResult::TransactionStepList & steps_r )
310 return PluginFrame( command_r, json::Object {
311 { "TransactionStepList", steps_r }
315 ///////////////////////////////////////////////////////////////////
317 /** \internal Manage writing a new testcase when doing an upgrade. */
318 void writeUpgradeTestcase()
320 unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
321 MIL << "Testcases to keep: " << toKeep << endl;
324 Target_Ptr target( getZYpp()->getTarget() );
327 WAR << "No Target no Testcase!" << endl;
331 std::string stem( "updateTestcase" );
332 Pathname dir( target->assertRootPrefix("/var/log/") );
333 Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
336 std::list<std::string> content;
337 filesystem::readdir( content, dir, /*dots*/false );
338 std::set<std::string> cases;
339 for_( c, content.begin(), content.end() )
341 if ( str::startsWith( *c, stem ) )
344 if ( cases.size() >= toKeep )
346 unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
347 for_( c, cases.begin(), cases.end() )
349 filesystem::recursive_rmdir( dir/(*c) );
356 MIL << "Write new testcase " << next << endl;
357 getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
360 ///////////////////////////////////////////////////////////////////
362 { /////////////////////////////////////////////////////////////////
364 /** Execute script and report against report_r.
365 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
366 * execution was successfull (<tt>first = true</tt>), or the desired
367 * \c PatchScriptReport::Action in case execution failed
368 * (<tt>first = false</tt>).
370 * \note The packager is responsible for setting the correct permissions
371 * of the script. If the script is not executable it is reported as an
372 * error. We must not modify the permessions.
374 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
375 const Pathname & script_r,
376 callback::SendReport<PatchScriptReport> & report_r )
378 MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
380 HistoryLog historylog;
381 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
382 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
384 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
386 historylog.comment(output);
387 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
389 WAR << "User request to abort script " << script_r << endl;
391 // the rest is handled by exit code evaluation
392 // in case the script has meanwhile finished.
396 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
398 if ( prog.close() != 0 )
400 ret.second = report_r->problem( prog.execError() );
401 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
402 std::ostringstream sstr;
403 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
404 historylog.comment(sstr.str(), /*timestamp*/true);
413 /** Execute script and report against report_r.
414 * Return \c false if user requested \c ABORT.
416 bool executeScript( const Pathname & root_r,
417 const Pathname & script_r,
418 callback::SendReport<PatchScriptReport> & report_r )
420 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
423 action = doExecuteScript( root_r, script_r, report_r );
425 return true; // success
427 switch ( action.second )
429 case PatchScriptReport::ABORT:
430 WAR << "User request to abort at script " << script_r << endl;
431 return false; // requested abort.
434 case PatchScriptReport::IGNORE:
435 WAR << "User request to skip script " << script_r << endl;
436 return true; // requested skip.
439 case PatchScriptReport::RETRY:
442 } while ( action.second == PatchScriptReport::RETRY );
444 // THIS is not intended to be reached:
445 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
446 return false; // abort.
449 /** Look for update scripts named 'name-version-release-*' and
450 * execute them. Return \c false if \c ABORT was requested.
452 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
454 bool RunUpdateScripts( const Pathname & root_r,
455 const Pathname & scriptsPath_r,
456 const std::vector<sat::Solvable> & checkPackages_r,
459 if ( checkPackages_r.empty() )
460 return true; // no installed packages to check
462 MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
463 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
464 if ( ! PathInfo( scriptsDir ).isDir() )
465 return true; // no script dir
467 std::list<std::string> scripts;
468 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
469 if ( scripts.empty() )
470 return true; // no scripts in script dir
472 // Now collect and execute all matching scripts.
473 // On ABORT: at least log all outstanding scripts.
474 // - "name-version-release"
475 // - "name-version-release-*"
477 std::map<std::string, Pathname> unify; // scripts <md5,path>
478 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
480 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
481 for_( sit, scripts.begin(), scripts.end() )
483 if ( ! str::hasPrefix( *sit, prefix ) )
486 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
487 continue; // if not exact match it had to continue with '-'
489 PathInfo script( scriptsDir / *sit );
490 Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
491 std::string unifytag; // must not stay empty
493 if ( script.isFile() )
495 // Assert it's set executable, unify by md5sum.
496 filesystem::addmod( script.path(), 0500 );
497 unifytag = filesystem::md5sum( script.path() );
499 else if ( ! script.isExist() )
501 // Might be a dangling symlink, might be ok if we are in
502 // instsys (absolute symlink within the system below /mnt).
503 // readlink will tell....
504 unifytag = filesystem::readlink( script.path() ).asString();
507 if ( unifytag.empty() )
511 if ( unify[unifytag].empty() )
513 unify[unifytag] = localPath;
517 // translators: We may find the same script content in files with different names.
518 // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
519 // message for a log file. Preferably start translation with "%s"
520 std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
521 MIL << "Skip update script: " << msg << endl;
522 HistoryLog().comment( msg, /*timestamp*/true );
526 if ( abort || aborting_r )
528 WAR << "Aborting: Skip update script " << *sit << endl;
529 HistoryLog().comment(
530 localPath.asString() + _(" execution skipped while aborting"),
535 MIL << "Found update script " << *sit << endl;
536 callback::SendReport<PatchScriptReport> report;
537 report->start( make<Package>( *it ), script.path() );
539 if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
540 abort = true; // requested abort.
547 ///////////////////////////////////////////////////////////////////
549 ///////////////////////////////////////////////////////////////////
551 inline void copyTo( std::ostream & out_r, const Pathname & file_r )
553 std::ifstream infile( file_r.c_str() );
554 for( iostr::EachLine in( infile ); in; in.next() )
556 out_r << *in << endl;
560 inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
562 std::string ret( cmd_r );
563 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
564 SUBST_IF( "%p", notification_r.solvable().asString() );
565 SUBST_IF( "%P", notification_r.file().asString() );
570 void sendNotification( const Pathname & root_r,
571 const UpdateNotifications & notifications_r )
573 if ( notifications_r.empty() )
576 std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
577 MIL << "Notification command is '" << cmdspec << "'" << endl;
578 if ( cmdspec.empty() )
581 std::string::size_type pos( cmdspec.find( '|' ) );
582 if ( pos == std::string::npos )
584 ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
585 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
589 std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
590 std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
592 enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
593 Format format = UNKNOWN;
594 if ( formatStr == "none" )
596 else if ( formatStr == "single" )
598 else if ( formatStr == "digest" )
600 else if ( formatStr == "bulk" )
604 ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
605 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
609 // Take care: commands are ececuted chroot(root_r). The message file
610 // pathnames in notifications_r are local to root_r. For physical access
611 // to the file they need to be prefixed.
613 if ( format == NONE || format == SINGLE )
615 for_( it, notifications_r.begin(), notifications_r.end() )
617 std::vector<std::string> command;
618 if ( format == SINGLE )
619 command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
620 str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
622 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
623 if ( true ) // Wait for feedback
625 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
629 int ret = prog.close();
632 ERR << "Notification command returned with error (" << ret << ")." << endl;
633 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
639 else if ( format == DIGEST || format == BULK )
641 filesystem::TmpFile tmpfile;
642 ofstream out( tmpfile.path().c_str() );
643 for_( it, notifications_r.begin(), notifications_r.end() )
645 if ( format == DIGEST )
647 out << it->file() << endl;
649 else if ( format == BULK )
651 copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
655 std::vector<std::string> command;
656 command.push_back( "<"+tmpfile.path().asString() ); // redirect input
657 str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
659 ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
660 if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
662 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
666 int ret = prog.close();
669 ERR << "Notification command returned with error (" << ret << ")." << endl;
670 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
677 INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
678 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
684 /** Look for update messages named 'name-version-release-*' and
685 * send notification according to \ref ZConfig::updateMessagesNotify.
687 * \see http://en.opensuse.org/Software_Management/Code11/Scripts_and_Messages
689 void RunUpdateMessages( const Pathname & root_r,
690 const Pathname & messagesPath_r,
691 const std::vector<sat::Solvable> & checkPackages_r,
692 ZYppCommitResult & result_r )
694 if ( checkPackages_r.empty() )
695 return; // no installed packages to check
697 MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
698 Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
699 if ( ! PathInfo( messagesDir ).isDir() )
700 return; // no messages dir
702 std::list<std::string> messages;
703 filesystem::readdir( messages, messagesDir, /*dots*/false );
704 if ( messages.empty() )
705 return; // no messages in message dir
707 // Now collect all matching messages in result and send them
708 // - "name-version-release"
709 // - "name-version-release-*"
710 HistoryLog historylog;
711 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
713 std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
714 for_( sit, messages.begin(), messages.end() )
716 if ( ! str::hasPrefix( *sit, prefix ) )
719 if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
720 continue; // if not exact match it had to continue with '-'
722 PathInfo message( messagesDir / *sit );
723 if ( ! message.isFile() || message.size() == 0 )
726 MIL << "Found update message " << *sit << endl;
727 Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
728 result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
729 historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
732 sendNotification( root_r, result_r.updateMessages() );
735 /////////////////////////////////////////////////////////////////
737 ///////////////////////////////////////////////////////////////////
739 void XRunUpdateMessages( const Pathname & root_r,
740 const Pathname & messagesPath_r,
741 const std::vector<sat::Solvable> & checkPackages_r,
742 ZYppCommitResult & result_r )
743 { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
745 ///////////////////////////////////////////////////////////////////
747 IMPL_PTR_TYPE(TargetImpl);
749 TargetImpl_Ptr TargetImpl::_nullimpl;
751 /** Null implementation */
752 TargetImpl_Ptr TargetImpl::nullimpl()
755 _nullimpl = new TargetImpl;
759 ///////////////////////////////////////////////////////////////////
761 // METHOD NAME : TargetImpl::TargetImpl
762 // METHOD TYPE : Ctor
764 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
766 , _requestedLocalesFile( home() / "RequestedLocales" )
767 , _autoInstalledFile( home() / "AutoInstalled" )
768 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
770 _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
772 HistoryLog::setRoot(_root);
776 MIL << "Initialized target on " << _root << endl;
780 * generates a random id using uuidgen
782 static std::string generateRandomId()
784 std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
785 return iostr::getline( uuidprovider );
789 * updates the content of \p filename
790 * if \p condition is true, setting the content
791 * the the value returned by \p value
793 void updateFileContent( const Pathname &filename,
794 boost::function<bool ()> condition,
795 boost::function<string ()> value )
797 string val = value();
798 // if the value is empty, then just dont
799 // do anything, regardless of the condition
805 MIL << "updating '" << filename << "' content." << endl;
807 // if the file does not exist we need to generate the uuid file
809 std::ofstream filestr;
810 // make sure the path exists
811 filesystem::assert_dir( filename.dirname() );
812 filestr.open( filename.c_str() );
814 if ( filestr.good() )
821 // FIXME, should we ignore the error?
822 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
827 /** helper functor */
828 static bool fileMissing( const Pathname &pathname )
830 return ! PathInfo(pathname).isExist();
833 void TargetImpl::createAnonymousId() const
836 // create the anonymous unique id
837 // this value is used for statistics
838 Pathname idpath( home() / "AnonymousUniqueId");
842 updateFileContent( idpath,
843 boost::bind(fileMissing, idpath),
846 catch ( const Exception &e )
848 WAR << "Can't create anonymous id file" << endl;
853 void TargetImpl::createLastDistributionFlavorCache() const
855 // create the anonymous unique id
856 // this value is used for statistics
857 Pathname flavorpath( home() / "LastDistributionFlavor");
859 // is there a product
860 Product::constPtr p = baseProduct();
863 WAR << "No base product, I won't create flavor cache" << endl;
867 string flavor = p->flavor();
872 updateFileContent( flavorpath,
873 // only if flavor is not empty
874 functor::Constant<bool>( ! flavor.empty() ),
875 functor::Constant<string>(flavor) );
877 catch ( const Exception &e )
879 WAR << "Can't create flavor cache" << endl;
884 ///////////////////////////////////////////////////////////////////
886 // METHOD NAME : TargetImpl::~TargetImpl
887 // METHOD TYPE : Dtor
889 TargetImpl::~TargetImpl()
891 _rpm.closeDatabase();
892 MIL << "Targets closed" << endl;
895 ///////////////////////////////////////////////////////////////////
897 // solv file handling
899 ///////////////////////////////////////////////////////////////////
901 Pathname TargetImpl::defaultSolvfilesPath() const
903 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
906 void TargetImpl::clearCache()
908 Pathname base = solvfilesPath();
909 filesystem::recursive_rmdir( base );
912 bool TargetImpl::buildCache()
914 Pathname base = solvfilesPath();
915 Pathname rpmsolv = base/"solv";
916 Pathname rpmsolvcookie = base/"cookie";
918 bool build_rpm_solv = true;
919 // lets see if the rpm solv cache exists
921 RepoStatus rpmstatus( RepoStatus(_root/"var/lib/rpm/Name") && RepoStatus(_root/"etc/products.d") );
923 bool solvexisted = PathInfo(rpmsolv).isExist();
926 // see the status of the cache
927 PathInfo cookie( rpmsolvcookie );
928 MIL << "Read cookie: " << cookie << endl;
929 if ( cookie.isExist() )
931 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
932 // now compare it with the rpm database
933 if ( status == rpmstatus )
934 build_rpm_solv = false;
935 MIL << "Read cookie: " << rpmsolvcookie << " says: "
936 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
940 if ( build_rpm_solv )
942 // if the solvfile dir does not exist yet, we better create it
943 filesystem::assert_dir( base );
945 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
947 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
950 // Can't create temporary solv file, usually due to insufficient permission
951 // (user query while @System solv needs refresh). If so, try switching
952 // to a location within zypps temp. space (will be cleaned at application end).
954 bool switchingToTmpSolvfile = false;
955 Exception ex("Failed to cache rpm database.");
956 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
958 if ( ! solvfilesPathIsTemp() )
960 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
961 rpmsolv = base/"solv";
962 rpmsolvcookie = base/"cookie";
964 filesystem::assert_dir( base );
965 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
969 WAR << "Using a temporary solv file at " << base << endl;
970 switchingToTmpSolvfile = true;
971 _tmpSolvfilesPath = base;
975 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
979 if ( ! switchingToTmpSolvfile )
985 // Take care we unlink the solvfile on exception
986 ManagedFile guard( base, filesystem::recursive_rmdir );
988 std::ostringstream cmd;
990 if ( ! _root.empty() )
991 cmd << " -r '" << _root << "'";
992 cmd << " -X"; // autogenerate pattern/product/... from -package
993 cmd << " -A"; // autogenerate application pseudo packages
994 cmd << " -p '" << Pathname::assertprefix( _root, "/etc/products.d" ) << "'";
996 if ( ! oldSolvFile.empty() )
997 cmd << " '" << oldSolvFile << "'";
999 cmd << " > '" << tmpsolv.path() << "'";
1001 MIL << "Executing: " << cmd << endl;
1002 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
1005 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1006 WAR << " " << output;
1007 cmd << " " << output;
1010 int ret = prog.close();
1013 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
1014 ex.remember( cmd.str() );
1018 ret = filesystem::rename( tmpsolv, rpmsolv );
1020 ZYPP_THROW(Exception("Failed to move cache to final destination"));
1021 // if this fails, don't bother throwing exceptions
1022 filesystem::chmod( rpmsolv, 0644 );
1024 rpmstatus.saveToCookieFile(rpmsolvcookie);
1027 guard.resetDispose();
1029 // Finally send notification to plugins
1030 // NOTE: quick hack looking for spacewalk plugin only
1032 Pathname script( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"system/spacewalk" ) );
1033 if ( PathInfo( script ).isX() )
1035 PluginScript spacewalk( script );
1038 PluginFrame notify( "PACKAGESETCHANGED" );
1039 spacewalk.send( notify );
1041 PluginFrame ret( spacewalk.receive() );
1043 if ( ret.command() == "ERROR" )
1044 ret.writeTo( WAR ) << endl;
1046 catch ( const Exception & excpt )
1048 WAR << excpt.asUserHistory() << endl;
1052 return build_rpm_solv;
1055 void TargetImpl::reload()
1060 void TargetImpl::unload()
1062 Repository system( sat::Pool::instance().findSystemRepo() );
1064 system.eraseFromPool();
1067 void TargetImpl::load( bool force )
1069 bool newCache = buildCache();
1070 MIL << "New cache built: " << (newCache?"true":"false") <<
1071 ", force loading: " << (force?"true":"false") << endl;
1073 // now add the repos to the pool
1074 sat::Pool satpool( sat::Pool::instance() );
1075 Pathname rpmsolv( solvfilesPath() / "solv" );
1076 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
1078 // Providing an empty system repo, unload any old content
1079 Repository system( sat::Pool::instance().findSystemRepo() );
1081 if ( system && ! system.solvablesEmpty() )
1083 if ( newCache || force )
1085 system.eraseFromPool(); // invalidates system
1089 return; // nothing to do
1095 system = satpool.systemRepo();
1100 MIL << "adding " << rpmsolv << " to system" << endl;
1101 system.addSolv( rpmsolv );
1103 catch ( const Exception & exp )
1106 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1110 system.addSolv( rpmsolv );
1113 // (Re)Load the requested locales et al.
1114 // If the requested locales are empty, we leave the pool untouched
1115 // to avoid undoing changes the application applied. We expect this
1116 // to happen on a bare metal installation only. An already existing
1117 // target should be loaded before its settings are changed.
1119 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1120 if ( ! requestedLocales.empty() )
1122 satpool.setRequestedLocales( requestedLocales );
1127 for ( const auto & idstr : _autoInstalledFile.data() )
1128 q.push( idstr.id() );
1129 satpool.setAutoInstalled( q );
1131 if ( ZConfig::instance().apply_locks_file() )
1133 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1134 if ( ! hardLocks.empty() )
1136 ResPool::instance().setHardLockQueries( hardLocks );
1140 // now that the target is loaded, we can cache the flavor
1141 createLastDistributionFlavorCache();
1143 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1146 ///////////////////////////////////////////////////////////////////
1150 ///////////////////////////////////////////////////////////////////
1151 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1153 // ----------------------------------------------------------------- //
1154 ZYppCommitPolicy policy_r( policy_rX );
1156 // Fake outstanding YCP fix: Honour restriction to media 1
1157 // at installation, but install all remaining packages if post-boot.
1158 if ( policy_r.restrictToMedia() > 1 )
1159 policy_r.allMedia();
1161 if ( policy_r.downloadMode() == DownloadDefault ) {
1162 if ( root() == "/" )
1163 policy_r.downloadMode(DownloadInHeaps);
1165 policy_r.downloadMode(DownloadAsNeeded);
1167 // DownloadOnly implies dry-run.
1168 else if ( policy_r.downloadMode() == DownloadOnly )
1169 policy_r.dryRun( true );
1170 // ----------------------------------------------------------------- //
1172 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1174 ///////////////////////////////////////////////////////////////////
1175 // Compute transaction:
1176 ///////////////////////////////////////////////////////////////////
1177 ZYppCommitResult result( root() );
1178 result.rTransaction() = pool_r.resolver().getTransaction();
1179 result.rTransaction().order();
1180 // steps: this is our todo-list
1181 ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1182 if ( policy_r.restrictToMedia() )
1184 // Collect until the 1st package from an unwanted media occurs.
1185 // Further collection could violate install order.
1186 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1187 for_( it, result.transaction().begin(), result.transaction().end() )
1189 if ( makeResObject( *it )->mediaNr() > 1 )
1191 steps.push_back( *it );
1196 result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1198 MIL << "Todo: " << result << endl;
1200 ///////////////////////////////////////////////////////////////////
1201 // Prepare execution of commit plugins:
1202 ///////////////////////////////////////////////////////////////////
1203 CommitPlugins commitPlugins;
1204 if ( root() == "/" && ! policy_r.dryRun() )
1206 Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
1207 commitPlugins.load( plugindir );
1209 if ( ! commitPlugins.empty() )
1210 commitPlugins.send( transactionPluginFrame( "COMMITBEGIN", steps ) );
1212 ///////////////////////////////////////////////////////////////////
1213 // Write out a testcase if we're in dist upgrade mode.
1214 ///////////////////////////////////////////////////////////////////
1215 if ( getZYpp()->resolver()->upgradeMode() )
1217 if ( ! policy_r.dryRun() )
1219 writeUpgradeTestcase();
1223 DBG << "dryRun: Not writing upgrade testcase." << endl;
1227 ///////////////////////////////////////////////////////////////////
1228 // Store non-package data:
1229 ///////////////////////////////////////////////////////////////////
1230 if ( ! policy_r.dryRun() )
1232 filesystem::assert_dir( home() );
1233 // requested locales
1234 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1237 SolvIdentFile::Data newdata;
1238 for ( sat::Queue::value_type id : result.rTransaction().autoInstalled() )
1239 newdata.insert( IdString(id) );
1240 _autoInstalledFile.setData( newdata );
1243 if ( ZConfig::instance().apply_locks_file() )
1245 HardLocksFile::Data newdata;
1246 pool_r.getHardLockQueries( newdata );
1247 _hardLocksFile.setData( newdata );
1252 DBG << "dryRun: Not stroring non-package data." << endl;
1255 ///////////////////////////////////////////////////////////////////
1256 // First collect and display all messages
1257 // associated with patches to be installed.
1258 ///////////////////////////////////////////////////////////////////
1259 if ( ! policy_r.dryRun() )
1261 for_( it, steps.begin(), steps.end() )
1263 if ( ! it->satSolvable().isKind<Patch>() )
1267 if ( ! pi.status().isToBeInstalled() )
1270 Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1271 if ( ! patch ||patch->message().empty() )
1274 MIL << "Show message for " << patch << endl;
1275 callback::SendReport<target::PatchMessageReport> report;
1276 if ( ! report->show( patch ) )
1278 WAR << "commit aborted by the user" << endl;
1279 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1285 DBG << "dryRun: Not checking patch messages." << endl;
1288 ///////////////////////////////////////////////////////////////////
1289 // Remove/install packages.
1290 ///////////////////////////////////////////////////////////////////
1291 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1292 if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1294 // Prepare the package cache. Pass all items requiring download.
1295 CommitPackageCache packageCache( root() );
1296 packageCache.setCommitList( steps.begin(), steps.end() );
1299 if ( policy_r.downloadMode() != DownloadAsNeeded )
1301 // Preload the cache. Until now this means pre-loading all packages.
1302 // Once DownloadInHeaps is fully implemented, this will change and
1303 // we may actually have more than one heap.
1304 for_( it, steps.begin(), steps.end() )
1306 switch ( it->stepType() )
1308 case sat::Transaction::TRANSACTION_INSTALL:
1309 case sat::Transaction::TRANSACTION_MULTIINSTALL:
1310 // proceed: only install actionas may require download.
1314 // next: no download for or non-packages and delete actions.
1320 if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1322 ManagedFile localfile;
1325 // TODO: unify packageCache.get for Package and SrcPackage
1326 if ( pi->isKind<Package>() )
1328 localfile = packageCache.get( pi );
1330 else if ( pi->isKind<SrcPackage>() )
1332 repo::RepoMediaAccess access;
1333 repo::SrcPackageProvider prov( access );
1334 localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1338 INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1341 localfile.resetDispose(); // keep the package file in the cache
1343 catch ( const AbortRequestException & exp )
1345 it->stepStage( sat::Transaction::STEP_ERROR );
1347 WAR << "commit cache preload aborted by the user" << endl;
1348 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1351 catch ( const SkipRequestException & exp )
1354 it->stepStage( sat::Transaction::STEP_ERROR );
1356 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1359 catch ( const Exception & exp )
1361 // bnc #395704: missing catch causes abort.
1362 // TODO see if packageCache fails to handle errors correctly.
1364 it->stepStage( sat::Transaction::STEP_ERROR );
1366 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1375 ERR << "Some packages could not be provided. Aborting commit."<< endl;
1379 if ( ! policy_r.dryRun() )
1381 // if cache is preloaded, check for file conflicts
1382 commitFindFileConflicts( policy_r, result );
1383 commit( policy_r, packageCache, result );
1387 DBG << "dryRun/downloadOnly: Not installing/deleting anything." << endl;
1393 DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1396 ///////////////////////////////////////////////////////////////////
1397 // Send result to commit plugins:
1398 ///////////////////////////////////////////////////////////////////
1399 if ( ! commitPlugins.empty() )
1400 commitPlugins.send( transactionPluginFrame( "COMMITEND", steps ) );
1402 ///////////////////////////////////////////////////////////////////
1403 // Try to rebuild solv file while rpm database is still in cache
1404 ///////////////////////////////////////////////////////////////////
1405 if ( ! policy_r.dryRun() )
1410 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1414 ///////////////////////////////////////////////////////////////////
1418 ///////////////////////////////////////////////////////////////////
1419 void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1420 CommitPackageCache & packageCache_r,
1421 ZYppCommitResult & result_r )
1423 // steps: this is our todo-list
1424 ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1425 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1428 RpmPostTransCollector postTransCollector( _root );
1429 std::vector<sat::Solvable> successfullyInstalledPackages;
1430 TargetImpl::PoolItemList remaining;
1432 for_( step, steps.begin(), steps.end() )
1434 PoolItem citem( *step );
1435 if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1437 if ( citem->isKind<Package>() )
1439 // for packages this means being obsoleted (by rpm)
1440 // thius no additional action is needed.
1441 step->stepStage( sat::Transaction::STEP_DONE );
1446 if ( citem->isKind<Package>() )
1448 Package::constPtr p = citem->asKind<Package>();
1449 if ( citem.status().isToBeInstalled() )
1451 ManagedFile localfile;
1454 localfile = packageCache_r.get( citem );
1456 catch ( const AbortRequestException &e )
1458 WAR << "commit aborted by the user" << endl;
1460 step->stepStage( sat::Transaction::STEP_ERROR );
1463 catch ( const SkipRequestException &e )
1466 WAR << "Skipping package " << p << " in commit" << endl;
1467 step->stepStage( sat::Transaction::STEP_ERROR );
1470 catch ( const Exception &e )
1472 // bnc #395704: missing catch causes abort.
1473 // TODO see if packageCache fails to handle errors correctly.
1475 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1476 step->stepStage( sat::Transaction::STEP_ERROR );
1480 #warning Exception handling
1481 // create a installation progress report proxy
1482 RpmInstallPackageReceiver progress( citem.resolvable() );
1483 progress.connect(); // disconnected on destruction.
1485 bool success = false;
1486 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1487 // Why force and nodeps?
1489 // Because zypp builds the transaction and the resolver asserts that
1490 // everything is fine.
1491 // We use rpm just to unpack and register the package in the database.
1492 // We do this step by step, so rpm is not aware of the bigger context.
1493 // So we turn off rpms internal checks, because we do it inside zypp.
1494 flags |= rpm::RPMINST_NODEPS;
1495 flags |= rpm::RPMINST_FORCE;
1497 if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1498 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1499 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1500 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1504 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1505 if ( postTransCollector.collectScriptFromPackage( localfile ) )
1506 flags |= rpm::RPMINST_NOPOSTTRANS;
1507 rpm().installPackage( localfile, flags );
1508 HistoryLog().install(citem);
1510 if ( progress.aborted() )
1512 WAR << "commit aborted by the user" << endl;
1513 localfile.resetDispose(); // keep the package file in the cache
1515 step->stepStage( sat::Transaction::STEP_ERROR );
1521 step->stepStage( sat::Transaction::STEP_DONE );
1524 catch ( Exception & excpt_r )
1526 ZYPP_CAUGHT(excpt_r);
1527 localfile.resetDispose(); // keep the package file in the cache
1529 if ( policy_r.dryRun() )
1531 WAR << "dry run failed" << endl;
1532 step->stepStage( sat::Transaction::STEP_ERROR );
1536 if ( progress.aborted() )
1538 WAR << "commit aborted by the user" << endl;
1543 WAR << "Install failed" << endl;
1545 step->stepStage( sat::Transaction::STEP_ERROR );
1549 if ( success && !policy_r.dryRun() )
1551 citem.status().resetTransact( ResStatus::USER );
1552 successfullyInstalledPackages.push_back( citem.satSolvable() );
1553 step->stepStage( sat::Transaction::STEP_DONE );
1558 RpmRemovePackageReceiver progress( citem.resolvable() );
1559 progress.connect(); // disconnected on destruction.
1561 bool success = false;
1562 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1563 flags |= rpm::RPMINST_NODEPS;
1564 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1567 rpm().removePackage( p, flags );
1568 HistoryLog().remove(citem);
1570 if ( progress.aborted() )
1572 WAR << "commit aborted by the user" << endl;
1574 step->stepStage( sat::Transaction::STEP_ERROR );
1580 step->stepStage( sat::Transaction::STEP_DONE );
1583 catch (Exception & excpt_r)
1585 ZYPP_CAUGHT( excpt_r );
1586 if ( progress.aborted() )
1588 WAR << "commit aborted by the user" << endl;
1590 step->stepStage( sat::Transaction::STEP_ERROR );
1594 WAR << "removal of " << p << " failed";
1595 step->stepStage( sat::Transaction::STEP_ERROR );
1597 if ( success && !policy_r.dryRun() )
1599 citem.status().resetTransact( ResStatus::USER );
1600 step->stepStage( sat::Transaction::STEP_DONE );
1604 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1606 // Status is changed as the buddy package buddy
1607 // gets installed/deleted. Handle non-buddies only.
1608 if ( ! citem.buddy() )
1610 if ( citem->isKind<Product>() )
1612 Product::constPtr p = citem->asKind<Product>();
1613 if ( citem.status().isToBeInstalled() )
1615 ERR << "Can't install orphan product without release-package! " << citem << endl;
1619 // Deleting the corresponding product entry is all we con do.
1620 // So the product will no longer be visible as installed.
1621 std::string referenceFilename( p->referenceFilename() );
1622 if ( referenceFilename.empty() )
1624 ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1628 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1629 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1631 ERR << "Delete orphan product failed: " << referenceFile << endl;
1636 else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1638 // SrcPackage is install-only
1639 SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1640 installSrcPackage( p );
1643 citem.status().resetTransact( ResStatus::USER );
1644 step->stepStage( sat::Transaction::STEP_DONE );
1647 } // other resolvables
1651 // process all remembered posttrans scripts.
1653 postTransCollector.executeScripts();
1655 postTransCollector.discardScripts();
1657 // Check presence of update scripts/messages. If aborting,
1658 // at least log omitted scripts.
1659 if ( ! successfullyInstalledPackages.empty() )
1661 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1662 successfullyInstalledPackages, abort ) )
1664 WAR << "Commit aborted by the user" << endl;
1667 // send messages after scripts in case some script generates output,
1668 // that should be kept in t %ghost message file.
1669 RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1670 successfullyInstalledPackages,
1676 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1680 ///////////////////////////////////////////////////////////////////
1682 rpm::RpmDb & TargetImpl::rpm()
1687 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1689 return _rpm.hasFile(path_str, name_str);
1693 Date TargetImpl::timestamp() const
1695 return _rpm.timestamp();
1698 ///////////////////////////////////////////////////////////////////
1701 parser::ProductFileData baseproductdata( const Pathname & root_r )
1703 parser::ProductFileData ret;
1704 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1706 if ( baseproduct.isFile() )
1710 ret = parser::ProductFileReader::scanFile( baseproduct.path() );
1712 catch ( const Exception & excpt )
1714 ZYPP_CAUGHT( excpt );
1717 else if ( PathInfo( Pathname::assertprefix( root_r, "/etc/products.d" ) ).isDir() )
1719 ERR << "baseproduct symlink is dangling or missing: " << baseproduct << endl;
1724 inline Pathname staticGuessRoot( const Pathname & root_r )
1726 if ( root_r.empty() )
1728 // empty root: use existing Target or assume "/"
1729 Pathname ret ( ZConfig::instance().systemRoot() );
1731 return Pathname("/");
1737 inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1739 std::ifstream idfile( file_r.c_str() );
1740 for( iostr::EachLine in( idfile ); in; in.next() )
1742 std::string line( str::trim( *in ) );
1743 if ( ! line.empty() )
1746 return std::string();
1749 ///////////////////////////////////////////////////////////////////
1751 Product::constPtr TargetImpl::baseProduct() const
1753 ResPool pool(ResPool::instance());
1754 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1756 Product::constPtr p = (*it)->asKind<Product>();
1757 if ( p->isTargetDistribution() )
1763 LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1765 const Pathname needroot( staticGuessRoot(root_r) );
1766 const Target_constPtr target( getZYpp()->getTarget() );
1767 if ( target && target->root() == needroot )
1768 return target->requestedLocales();
1769 return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
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 Target::DistributionLabel TargetImpl::distributionLabel() const
1786 Target::DistributionLabel ret;
1787 parser::ProductFileData pdata( baseproductdata( _root ) );
1788 ret.shortName = pdata.shortName();
1789 ret.summary = pdata.summary();
1793 Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1795 Target::DistributionLabel ret;
1796 parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1797 ret.shortName = pdata.shortName();
1798 ret.summary = pdata.summary();
1802 std::string TargetImpl::distributionVersion() const
1804 if ( _distributionVersion.empty() )
1806 _distributionVersion = TargetImpl::distributionVersion(root());
1807 if ( !_distributionVersion.empty() )
1808 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1810 return _distributionVersion;
1813 std::string TargetImpl::distributionVersion( const Pathname & root_r )
1815 std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1816 if ( distributionVersion.empty() )
1818 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1819 // On RHEL, Fedora and others the "product version" is determined by the first package
1820 // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1821 // with the $distroverpkg variable.
1822 scoped_ptr<rpm::RpmDb> tmprpmdb;
1823 if ( ZConfig::instance().systemRoot() == Pathname() )
1827 tmprpmdb.reset( new rpm::RpmDb );
1828 tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1835 rpm::librpmDb::db_const_iterator it;
1836 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1837 distributionVersion = it->tag_version();
1839 return distributionVersion;
1843 std::string TargetImpl::distributionFlavor() const
1845 return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1848 std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1850 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1853 ///////////////////////////////////////////////////////////////////
1855 std::string TargetImpl::anonymousUniqueId() const
1857 return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1860 std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1862 return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1865 ///////////////////////////////////////////////////////////////////
1867 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1869 // provide on local disk
1870 ManagedFile localfile = provideSrcPackage(srcPackage_r);
1872 rpm().installPackage ( localfile );
1875 ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1877 // provide on local disk
1878 repo::RepoMediaAccess access_r;
1879 repo::SrcPackageProvider prov( access_r );
1880 return prov.provideSrcPackage( srcPackage_r );
1882 ////////////////////////////////////////////////////////////////
1883 } // namespace target
1884 ///////////////////////////////////////////////////////////////////
1885 /////////////////////////////////////////////////////////////////
1887 ///////////////////////////////////////////////////////////////////