libzypp 9.41.1

TargetImpl.cc

Go to the documentation of this file.
00001 /*---------------------------------------------------------------------\
00002 |                          ____ _   __ __ ___                          |
00003 |                         |__  / \ / / . \ . \                         |
00004 |                           / / \ V /|  _/  _/                         |
00005 |                          / /__ | | | | | |                           |
00006 |                         /_____||_| |_| |_|                           |
00007 |                                                                      |
00008 \---------------------------------------------------------------------*/
00012 #include <iostream>
00013 #include <fstream>
00014 #include <sstream>
00015 #include <string>
00016 #include <list>
00017 #include <set>
00018 
00019 #include <sys/types.h>
00020 #include <dirent.h>
00021 
00022 #include "zypp/base/LogTools.h"
00023 #include "zypp/base/Exception.h"
00024 #include "zypp/base/Iterator.h"
00025 #include "zypp/base/Gettext.h"
00026 #include "zypp/base/IOStream.h"
00027 #include "zypp/base/Functional.h"
00028 #include "zypp/base/UserRequestException.h"
00029 
00030 #include "zypp/ZConfig.h"
00031 #include "zypp/ZYppFactory.h"
00032 
00033 #include "zypp/PoolItem.h"
00034 #include "zypp/ResObjects.h"
00035 #include "zypp/Url.h"
00036 #include "zypp/TmpPath.h"
00037 #include "zypp/RepoStatus.h"
00038 #include "zypp/ExternalProgram.h"
00039 #include "zypp/Repository.h"
00040 
00041 #include "zypp/ResFilters.h"
00042 #include "zypp/HistoryLog.h"
00043 #include "zypp/target/TargetImpl.h"
00044 #include "zypp/target/TargetCallbackReceiver.h"
00045 #include "zypp/target/rpm/librpmDb.h"
00046 #include "zypp/target/CommitPackageCache.h"
00047 
00048 #include "zypp/parser/ProductFileReader.h"
00049 
00050 #include "zypp/pool/GetResolvablesToInsDel.h"
00051 #include "zypp/solver/detail/Testcase.h"
00052 
00053 #include "zypp/repo/DeltaCandidates.h"
00054 #include "zypp/repo/PackageProvider.h"
00055 #include "zypp/repo/SrcPackageProvider.h"
00056 
00057 #include "zypp/sat/Pool.h"
00058 #include "zypp/sat/Transaction.h"
00059 
00060 #include "zypp/PluginExecutor.h"
00061 
00062 using namespace std;
00063 
00065 namespace zypp
00066 { 
00067 
00068   namespace target
00069   { 
00070 
00072 
00074     void writeUpgradeTestcase()
00075     {
00076       unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
00077       MIL << "Testcases to keep: " << toKeep << endl;
00078       if ( !toKeep )
00079         return;
00080       Target_Ptr target( getZYpp()->getTarget() );
00081       if ( ! target )
00082       {
00083         WAR << "No Target no Testcase!" << endl;
00084         return;
00085       }
00086 
00087       std::string stem( "updateTestcase" );
00088       Pathname dir( target->assertRootPrefix("/var/log/") );
00089       Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
00090 
00091       {
00092         std::list<std::string> content;
00093         filesystem::readdir( content, dir, /*dots*/false );
00094         std::set<std::string> cases;
00095         for_( c, content.begin(), content.end() )
00096         {
00097           if ( str::startsWith( *c, stem ) )
00098             cases.insert( *c );
00099         }
00100         if ( cases.size() >= toKeep )
00101         {
00102           unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
00103           for_( c, cases.begin(), cases.end() )
00104           {
00105             filesystem::recursive_rmdir( dir/(*c) );
00106             if ( ! --toDel )
00107               break;
00108           }
00109         }
00110       }
00111 
00112       MIL << "Write new testcase " << next << endl;
00113       getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
00114     }
00115 
00117     namespace
00118     { 
00119 
00130       std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
00131                                                                  const Pathname & script_r,
00132                                                                  callback::SendReport<PatchScriptReport> & report_r )
00133       {
00134         MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
00135 
00136         HistoryLog historylog;
00137         historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
00138         ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
00139 
00140         for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
00141         {
00142           historylog.comment(output);
00143           if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
00144           {
00145             WAR << "User request to abort script " << script_r << endl;
00146             prog.kill();
00147             // the rest is handled by exit code evaluation
00148             // in case the script has meanwhile finished.
00149           }
00150         }
00151 
00152         std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
00153 
00154         if ( prog.close() != 0 )
00155         {
00156           ret.second = report_r->problem( prog.execError() );
00157           WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
00158           std::ostringstream sstr;
00159           sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
00160           historylog.comment(sstr.str(), /*timestamp*/true);
00161           return ret;
00162         }
00163 
00164         report_r->finish();
00165         ret.first = true;
00166         return ret;
00167       }
00168 
00172       bool executeScript( const Pathname & root_r,
00173                           const Pathname & script_r,
00174                           callback::SendReport<PatchScriptReport> & report_r )
00175       {
00176         std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
00177 
00178         do {
00179           action = doExecuteScript( root_r, script_r, report_r );
00180           if ( action.first )
00181             return true; // success
00182 
00183           switch ( action.second )
00184           {
00185             case PatchScriptReport::ABORT:
00186               WAR << "User request to abort at script " << script_r << endl;
00187               return false; // requested abort.
00188               break;
00189 
00190             case PatchScriptReport::IGNORE:
00191               WAR << "User request to skip script " << script_r << endl;
00192               return true; // requested skip.
00193               break;
00194 
00195             case PatchScriptReport::RETRY:
00196               break; // again
00197           }
00198         } while ( action.second == PatchScriptReport::RETRY );
00199 
00200         // THIS is not intended to be reached:
00201         INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
00202         return false; // abort.
00203       }
00204 
00210       bool RunUpdateScripts( const Pathname & root_r,
00211                              const Pathname & scriptsPath_r,
00212                              const std::vector<sat::Solvable> & checkPackages_r,
00213                              bool aborting_r )
00214       {
00215         if ( checkPackages_r.empty() )
00216           return true; // no installed packages to check
00217 
00218         MIL << "Looking for new update scripts in (" <<  root_r << ")" << scriptsPath_r << endl;
00219         Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
00220         if ( ! PathInfo( scriptsDir ).isDir() )
00221           return true; // no script dir
00222 
00223         std::list<std::string> scripts;
00224         filesystem::readdir( scripts, scriptsDir, /*dots*/false );
00225         if ( scripts.empty() )
00226           return true; // no scripts in script dir
00227 
00228         // Now collect and execute all matching scripts.
00229         // On ABORT: at least log all outstanding scripts.
00230         // - "name-version-release"
00231         // - "name-version-release-*"
00232         bool abort = false;
00233         std::map<std::string, Pathname> unify; // scripts <md5,path>
00234         for_( it, checkPackages_r.begin(), checkPackages_r.end() )
00235         {
00236           std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
00237           for_( sit, scripts.begin(), scripts.end() )
00238           {
00239             if ( ! str::hasPrefix( *sit, prefix ) )
00240               continue;
00241 
00242             if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
00243               continue; // if not exact match it had to continue with '-'
00244 
00245             PathInfo script( scriptsDir / *sit );
00246             if ( ! script.isFile() )
00247               continue;
00248 
00249             // Assert it's set executable
00250             filesystem::addmod( script.path(), 0500 );
00251 
00252             Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
00253 
00254             // Unify scripts by md5sum
00255             std::string md5sum( filesystem::md5sum( script.path() ) );
00256             if ( unify[md5sum].empty() )
00257             {
00258               unify[md5sum] = localPath;
00259             }
00260             else
00261             {
00262               // translators: We may find the same script content in files with different names.
00263               // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
00264               // message for a log file. Preferably start translation with "%s"
00265               std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[md5sum].c_str() ) );
00266               MIL << "Skip update script: " << msg << endl;
00267               HistoryLog().comment( msg, /*timestamp*/true );
00268               continue;
00269             }
00270 
00271             if ( abort || aborting_r )
00272             {
00273               WAR << "Aborting: Skip update script " << *sit << endl;
00274               HistoryLog().comment(
00275                   localPath.asString() + _(" execution skipped while aborting"),
00276                   /*timestamp*/true);
00277             }
00278             else
00279             {
00280               MIL << "Found update script " << *sit << endl;
00281               callback::SendReport<PatchScriptReport> report;
00282               report->start( make<Package>( *it ), script.path() );
00283 
00284               if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
00285                 abort = true; // requested abort.
00286             }
00287           }
00288         }
00289         return !abort;
00290       }
00291 
00293       //
00295 
00296       inline void copyTo( std::ostream & out_r, const Pathname & file_r )
00297       {
00298         std::ifstream infile( file_r.c_str() );
00299         for( iostr::EachLine in( infile ); in; in.next() )
00300         {
00301           out_r << *in << endl;
00302         }
00303       }
00304 
00305       inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
00306       {
00307         std::string ret( cmd_r );
00308 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
00309         SUBST_IF( "%p", notification_r.solvable().asString() );
00310         SUBST_IF( "%P", notification_r.file().asString() );
00311 #undef SUBST_IF
00312         return ret;
00313       }
00314 
00315       void sendNotification( const Pathname & root_r,
00316                              const UpdateNotifications & notifications_r )
00317       {
00318         if ( notifications_r.empty() )
00319           return;
00320 
00321         std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
00322         MIL << "Notification command is '" << cmdspec << "'" << endl;
00323         if ( cmdspec.empty() )
00324           return;
00325 
00326         std::string::size_type pos( cmdspec.find( '|' ) );
00327         if ( pos == std::string::npos )
00328         {
00329           ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
00330           HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
00331           return;
00332         }
00333 
00334         std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
00335         std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
00336 
00337         enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
00338         Format format = UNKNOWN;
00339         if ( formatStr == "none" )
00340           format = NONE;
00341         else if ( formatStr == "single" )
00342           format = SINGLE;
00343         else if ( formatStr == "digest" )
00344           format = DIGEST;
00345         else if ( formatStr == "bulk" )
00346           format = BULK;
00347         else
00348         {
00349           ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
00350           HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
00351          return;
00352         }
00353 
00354         // Take care: commands are ececuted chroot(root_r). The message file
00355         // pathnames in notifications_r are local to root_r. For physical access
00356         // to the file they need to be prefixed.
00357 
00358         if ( format == NONE || format == SINGLE )
00359         {
00360           for_( it, notifications_r.begin(), notifications_r.end() )
00361           {
00362             std::vector<std::string> command;
00363             if ( format == SINGLE )
00364               command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
00365             str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
00366 
00367             ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
00368             if ( true ) // Wait for feedback
00369             {
00370               for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
00371               {
00372                 DBG << line;
00373               }
00374               int ret = prog.close();
00375               if ( ret != 0 )
00376               {
00377                 ERR << "Notification command returned with error (" << ret << ")." << endl;
00378                 HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
00379                 return;
00380               }
00381             }
00382           }
00383         }
00384         else if ( format == DIGEST || format == BULK )
00385         {
00386           filesystem::TmpFile tmpfile;
00387           ofstream out( tmpfile.path().c_str() );
00388           for_( it, notifications_r.begin(), notifications_r.end() )
00389           {
00390             if ( format == DIGEST )
00391             {
00392               out << it->file() << endl;
00393             }
00394             else if ( format == BULK )
00395             {
00396               copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
00397             }
00398           }
00399 
00400           std::vector<std::string> command;
00401           command.push_back( "<"+tmpfile.path().asString() ); // redirect input
00402           str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
00403 
00404           ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
00405           if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
00406           {
00407             for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
00408             {
00409               DBG << line;
00410             }
00411             int ret = prog.close();
00412             if ( ret != 0 )
00413             {
00414               ERR << "Notification command returned with error (" << ret << ")." << endl;
00415               HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
00416               return;
00417             }
00418           }
00419         }
00420         else
00421         {
00422           INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
00423           HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
00424           return;
00425         }
00426       }
00427 
00428 
00434       void RunUpdateMessages( const Pathname & root_r,
00435                               const Pathname & messagesPath_r,
00436                               const std::vector<sat::Solvable> & checkPackages_r,
00437                               ZYppCommitResult & result_r )
00438       {
00439         if ( checkPackages_r.empty() )
00440           return; // no installed packages to check
00441 
00442         MIL << "Looking for new update messages in (" <<  root_r << ")" << messagesPath_r << endl;
00443         Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
00444         if ( ! PathInfo( messagesDir ).isDir() )
00445           return; // no messages dir
00446 
00447         std::list<std::string> messages;
00448         filesystem::readdir( messages, messagesDir, /*dots*/false );
00449         if ( messages.empty() )
00450           return; // no messages in message dir
00451 
00452         // Now collect all matching messages in result and send them
00453         // - "name-version-release"
00454         // - "name-version-release-*"
00455         HistoryLog historylog;
00456         for_( it, checkPackages_r.begin(), checkPackages_r.end() )
00457         {
00458           std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
00459           for_( sit, messages.begin(), messages.end() )
00460           {
00461             if ( ! str::hasPrefix( *sit, prefix ) )
00462               continue;
00463 
00464             if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
00465               continue; // if not exact match it had to continue with '-'
00466 
00467             PathInfo message( messagesDir / *sit );
00468             if ( ! message.isFile() || message.size() == 0 )
00469               continue;
00470 
00471             MIL << "Found update message " << *sit << endl;
00472             Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
00473             result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
00474             historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
00475           }
00476         }
00477         sendNotification( root_r, result_r.updateMessages() );
00478       }
00479 
00481     } // namespace
00483 
00484     void XRunUpdateMessages( const Pathname & root_r,
00485                              const Pathname & messagesPath_r,
00486                              const std::vector<sat::Solvable> & checkPackages_r,
00487                              ZYppCommitResult & result_r )
00488     { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
00489 
00491     struct QueryInstalledEditionHelper
00492     {
00493       bool operator()( const std::string & name_r,
00494                        const Edition &     ed_r,
00495                        const Arch &        arch_r ) const
00496       {
00497         rpm::librpmDb::db_const_iterator it;
00498         for ( it.findByName( name_r ); *it; ++it )
00499           {
00500             if ( arch_r == it->tag_arch()
00501                  && ( ed_r == Edition::noedition || ed_r == it->tag_edition() ) )
00502               {
00503                 return true;
00504               }
00505           }
00506         return false;
00507       }
00508     };
00509 
00515     struct RepoProvidePackage
00516     {
00517       ResPool _pool;
00518       repo::RepoMediaAccess &_access;
00519 
00520       RepoProvidePackage( repo::RepoMediaAccess &access, ResPool pool_r )
00521         : _pool(pool_r), _access(access)
00522       {}
00523 
00524       ManagedFile operator()( const PoolItem & pi )
00525       {
00526         // Redirect PackageProvider queries for installed editions
00527         // (in case of patch/delta rpm processing) to rpmDb.
00528         repo::PackageProviderPolicy packageProviderPolicy;
00529         packageProviderPolicy.queryInstalledCB( QueryInstalledEditionHelper() );
00530 
00531         Package::constPtr p = asKind<Package>(pi.resolvable());
00532 
00533         // Build a repository list for repos
00534         // contributing to the pool
00535         std::list<Repository> repos( _pool.knownRepositoriesBegin(), _pool.knownRepositoriesEnd() );
00536         repo::DeltaCandidates deltas(repos, p->name());
00537         repo::PackageProvider pkgProvider( _access, p, deltas, packageProviderPolicy );
00538 
00539         ManagedFile ret( pkgProvider.providePackage() );
00540         return ret;
00541       }
00542     };
00544 
00545     IMPL_PTR_TYPE(TargetImpl);
00546 
00547     TargetImpl_Ptr TargetImpl::_nullimpl;
00548 
00550     TargetImpl_Ptr TargetImpl::nullimpl()
00551     {
00552       if (_nullimpl == 0)
00553         _nullimpl = new TargetImpl;
00554       return _nullimpl;
00555     }
00556 
00558     //
00559     //  METHOD NAME : TargetImpl::TargetImpl
00560     //  METHOD TYPE : Ctor
00561     //
00562     TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
00563     : _root( root_r )
00564     , _requestedLocalesFile( home() / "RequestedLocales" )
00565     , _softLocksFile( home() / "SoftLocks" )
00566     , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
00567     {
00568       _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
00569 
00570       HistoryLog::setRoot(_root);
00571 
00572       createAnonymousId();
00573 
00574       MIL << "Initialized target on " << _root << endl;
00575     }
00576 
00580     static string generateRandomId()
00581     {
00582       string id;
00583       const char* argv[] =
00584       {
00585          "/usr/bin/uuidgen",
00586          NULL
00587       };
00588 
00589       ExternalProgram prog( argv,
00590                             ExternalProgram::Normal_Stderr,
00591                             false, -1, true);
00592       std::string line;
00593       for(line = prog.receiveLine();
00594           ! line.empty();
00595           line = prog.receiveLine() )
00596       {
00597           MIL << line << endl;
00598           id = line;
00599           break;
00600       }
00601       prog.close();
00602       return id;
00603     }
00604 
00610     void updateFileContent( const Pathname &filename,
00611                             boost::function<bool ()> condition,
00612                             boost::function<string ()> value )
00613     {
00614         string val = value();
00615         // if the value is empty, then just dont
00616         // do anything, regardless of the condition
00617         if ( val.empty() )
00618             return;
00619 
00620         if ( condition() )
00621         {
00622             MIL << "updating '" << filename << "' content." << endl;
00623 
00624             // if the file does not exist we need to generate the uuid file
00625 
00626             std::ofstream filestr;
00627             // make sure the path exists
00628             filesystem::assert_dir( filename.dirname() );
00629             filestr.open( filename.c_str() );
00630 
00631             if ( filestr.good() )
00632             {
00633                 filestr << val;
00634                 filestr.close();
00635             }
00636             else
00637             {
00638                 // FIXME, should we ignore the error?
00639                 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
00640             }
00641         }
00642     }
00643 
00645     static bool fileMissing( const Pathname &pathname )
00646     {
00647         return ! PathInfo(pathname).isExist();
00648     }
00649 
00650     void TargetImpl::createAnonymousId() const
00651     {
00652 
00653       // create the anonymous unique id
00654       // this value is used for statistics
00655       Pathname idpath( home() / "AnonymousUniqueId");
00656 
00657       try
00658       {
00659         updateFileContent( idpath,
00660                            boost::bind(fileMissing, idpath),
00661                            generateRandomId );
00662       }
00663       catch ( const Exception &e )
00664       {
00665         WAR << "Can't create anonymous id file" << endl;
00666       }
00667 
00668     }
00669 
00670     void TargetImpl::createLastDistributionFlavorCache() const
00671     {
00672       // create the anonymous unique id
00673       // this value is used for statistics
00674       Pathname flavorpath( home() / "LastDistributionFlavor");
00675 
00676       // is there a product
00677       Product::constPtr p = baseProduct();
00678       if ( ! p )
00679       {
00680           WAR << "No base product, I won't create flavor cache" << endl;
00681           return;
00682       }
00683 
00684       string flavor = p->flavor();
00685 
00686       try
00687       {
00688 
00689         updateFileContent( flavorpath,
00690                            // only if flavor is not empty
00691                            functor::Constant<bool>( ! flavor.empty() ),
00692                            functor::Constant<string>(flavor) );
00693       }
00694       catch ( const Exception &e )
00695       {
00696         WAR << "Can't create flavor cache" << endl;
00697         return;
00698       }
00699     }
00700 
00702     //
00703     //  METHOD NAME : TargetImpl::~TargetImpl
00704     //  METHOD TYPE : Dtor
00705     //
00706     TargetImpl::~TargetImpl()
00707     {
00708       _rpm.closeDatabase();
00709       MIL << "Targets closed" << endl;
00710     }
00711 
00713     //
00714     // solv file handling
00715     //
00717 
00718     Pathname TargetImpl::defaultSolvfilesPath() const
00719     {
00720       return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
00721     }
00722 
00723     void TargetImpl::clearCache()
00724     {
00725       Pathname base = solvfilesPath();
00726       filesystem::recursive_rmdir( base );
00727     }
00728 
00729     void TargetImpl::buildCache()
00730     {
00731       Pathname base = solvfilesPath();
00732       Pathname rpmsolv       = base/"solv";
00733       Pathname rpmsolvcookie = base/"cookie";
00734 
00735       bool build_rpm_solv = true;
00736       // lets see if the rpm solv cache exists
00737 
00738       RepoStatus rpmstatus( RepoStatus( _root/"/var/lib/rpm/Name" )
00739                             && (_root/"/etc/products.d") );
00740 
00741       bool solvexisted = PathInfo(rpmsolv).isExist();
00742       if ( solvexisted )
00743       {
00744         // see the status of the cache
00745         PathInfo cookie( rpmsolvcookie );
00746         MIL << "Read cookie: " << cookie << endl;
00747         if ( cookie.isExist() )
00748         {
00749           RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
00750           // now compare it with the rpm database
00751           if ( status.checksum() == rpmstatus.checksum() )
00752             build_rpm_solv = false;
00753           MIL << "Read cookie: " << rpmsolvcookie << " says: "
00754               << (build_rpm_solv ? "outdated" : "uptodate") << endl;
00755         }
00756       }
00757 
00758       if ( build_rpm_solv )
00759       {
00760         // if the solvfile dir does not exist yet, we better create it
00761         filesystem::assert_dir( base );
00762 
00763         Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
00764 
00765         filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
00766         if ( !tmpsolv )
00767         {
00768           // Can't create temporary solv file, usually due to insufficient permission
00769           // (user query while @System solv needs refresh). If so, try switching
00770           // to a location within zypps temp. space (will be cleaned at application end).
00771 
00772           bool switchingToTmpSolvfile = false;
00773           Exception ex("Failed to cache rpm database.");
00774           ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
00775 
00776           if ( ! solvfilesPathIsTemp() )
00777           {
00778             base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
00779             rpmsolv       = base/"solv";
00780             rpmsolvcookie = base/"cookie";
00781 
00782             filesystem::assert_dir( base );
00783             tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
00784 
00785             if ( tmpsolv )
00786             {
00787               WAR << "Using a temporary solv file at " << base << endl;
00788               switchingToTmpSolvfile = true;
00789               _tmpSolvfilesPath = base;
00790             }
00791             else
00792             {
00793               ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
00794             }
00795           }
00796 
00797           if ( ! switchingToTmpSolvfile )
00798           {
00799             ZYPP_THROW(ex);
00800           }
00801         }
00802 
00803         // Take care we unlink the solvfile on exception
00804         ManagedFile guard( base, filesystem::recursive_rmdir );
00805 
00806         std::ostringstream cmd;
00807         cmd << "rpmdb2solv";
00808         if ( ! _root.empty() )
00809           cmd << " -r '" << _root << "'";
00810 
00811         cmd << " -p '" << Pathname::assertprefix( _root, "/etc/products.d" ) << "'";
00812 
00813         if ( ! oldSolvFile.empty() )
00814           cmd << " '" << oldSolvFile << "'";
00815 
00816         cmd << "  > '" << tmpsolv.path() << "'";
00817 
00818         MIL << "Executing: " << cmd << endl;
00819         ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
00820 
00821         cmd << endl;
00822         for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
00823           WAR << "  " << output;
00824           cmd << "     " << output;
00825         }
00826 
00827         int ret = prog.close();
00828         if ( ret != 0 )
00829         {
00830           Exception ex(str::form("Failed to cache rpm database (%d).", ret));
00831           ex.remember( cmd.str() );
00832           ZYPP_THROW(ex);
00833         }
00834 
00835         ret = filesystem::rename( tmpsolv, rpmsolv );
00836         if ( ret != 0 )
00837           ZYPP_THROW(Exception("Failed to move cache to final destination"));
00838         // if this fails, don't bother throwing exceptions
00839         filesystem::chmod( rpmsolv, 0644 );
00840 
00841         rpmstatus.saveToCookieFile(rpmsolvcookie);
00842 
00843         // We keep it.
00844         guard.resetDispose();
00845 
00846         // system-hook: Finally send notification to plugins
00847         if ( root() == "/" )
00848         {
00849           PluginExecutor plugins;
00850           plugins.load( ZConfig::instance().pluginsPath()/"system" );
00851           if ( plugins )
00852             plugins.send( PluginFrame( "PACKAGESETCHANGED" ) );
00853         }
00854       }
00855     }
00856 
00857     void TargetImpl::unload()
00858     {
00859       Repository system( sat::Pool::instance().findSystemRepo() );
00860       if ( system )
00861         system.eraseFromPool();
00862     }
00863 
00864 
00865     void TargetImpl::load()
00866     {
00867       buildCache();
00868 
00869       // now add the repos to the pool
00870       sat::Pool satpool( sat::Pool::instance() );
00871       Pathname rpmsolv( solvfilesPath() / "solv" );
00872       MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
00873 
00874       // Providing an empty system repo, unload any old content
00875       Repository system( sat::Pool::instance().findSystemRepo() );
00876       if ( system && ! system.solvablesEmpty() )
00877       {
00878         system.eraseFromPool(); // invalidates system
00879       }
00880       if ( ! system )
00881       {
00882         system = satpool.systemRepo();
00883       }
00884 
00885       try
00886       {
00887         system.addSolv( rpmsolv );
00888       }
00889       catch ( const Exception & exp )
00890       {
00891         ZYPP_CAUGHT( exp );
00892         MIL << "Try to handle exception by rebuilding the solv-file" << endl;
00893         clearCache();
00894         buildCache();
00895 
00896         system.addSolv( rpmsolv );
00897       }
00898 
00899       // (Re)Load the requested locales et al.
00900       // If the requested locales are empty, we leave the pool untouched
00901       // to avoid undoing changes the application applied. We expect this
00902       // to happen on a bare metal installation only. An already existing
00903       // target should be loaded before its settings are changed.
00904       {
00905         const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
00906         if ( ! requestedLocales.empty() )
00907         {
00908           satpool.setRequestedLocales( requestedLocales );
00909         }
00910       }
00911       {
00912         SoftLocksFile::Data softLocks( _softLocksFile.data() );
00913         if ( ! softLocks.empty() )
00914         {
00915           // Don't soft lock any installed item.
00916           for_( it, system.solvablesBegin(), system.solvablesEnd() )
00917           {
00918             softLocks.erase( it->ident() );
00919           }
00920           ResPool::instance().setAutoSoftLocks( softLocks );
00921         }
00922       }
00923       if ( ZConfig::instance().apply_locks_file() )
00924       {
00925         const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
00926         if ( ! hardLocks.empty() )
00927         {
00928           ResPool::instance().setHardLockQueries( hardLocks );
00929         }
00930       }
00931 
00932       // now that the target is loaded, we can cache the flavor
00933       createLastDistributionFlavorCache();
00934 
00935       MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
00936     }
00937 
00939     //
00940     // COMMIT
00941     //
00943     ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
00944     {
00945       // ----------------------------------------------------------------- //
00946       ZYppCommitPolicy policy_r( policy_rX );
00947 
00948       // Fake outstanding YCP fix: Honour restriction to media 1
00949       // at installation, but install all remaining packages if post-boot.
00950       if ( policy_r.restrictToMedia() > 1 )
00951         policy_r.allMedia();
00952 
00953       if ( policy_r.downloadMode() == DownloadDefault ) {
00954         if ( root() == "/" )
00955           policy_r.downloadMode(DownloadInHeaps);
00956         else
00957           policy_r.downloadMode(DownloadAsNeeded);
00958       }
00959       // DownloadOnly implies dry-run.
00960       else if ( policy_r.downloadMode() == DownloadOnly )
00961         policy_r.dryRun( true );
00962       // ----------------------------------------------------------------- //
00963 
00964       MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
00965 
00967       // Prepare execution of commit plugins:
00969       PluginExecutor commitPlugins;
00970       if ( root() == "/" && ! policy_r.dryRun() )
00971       {
00972         commitPlugins.load( ZConfig::instance().pluginsPath()/"commit" );
00973       }
00974 
00976       // Write out a testcase if we're in dist upgrade mode.
00978       if ( pool_r.resolver().upgradeMode() || pool_r.resolver().upgradingRepos() )
00979       {
00980         if ( ! policy_r.dryRun() )
00981         {
00982           writeUpgradeTestcase();
00983         }
00984         else
00985         {
00986           DBG << "dryRun: Not writing upgrade testcase." << endl;
00987         }
00988       }
00989 
00991       // Store non-package data:
00993       if ( ! policy_r.dryRun() )
00994       {
00995         filesystem::assert_dir( home() );
00996         // requested locales
00997         _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
00998         // weak locks
00999         {
01000           SoftLocksFile::Data newdata;
01001           pool_r.getActiveSoftLocks( newdata );
01002           _softLocksFile.setData( newdata );
01003         }
01004         // hard locks
01005         if ( ZConfig::instance().apply_locks_file() )
01006         {
01007           HardLocksFile::Data newdata;
01008           pool_r.getHardLockQueries( newdata );
01009           _hardLocksFile.setData( newdata );
01010         }
01011       }
01012       else
01013       {
01014         DBG << "dryRun: Not stroring non-package data." << endl;
01015       }
01016 
01018       // Compute transaction:
01020       ZYppCommitResult result( root() );
01021       result.rTransaction() = pool_r.resolver().getTransaction();
01022       result.rTransaction().order();
01023       // steps: this is our todo-list
01024       ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
01025       if ( policy_r.restrictToMedia() )
01026       {
01027         // Collect until the 1st package from an unwanted media occurs.
01028         // Further collection could violate install order.
01029         MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
01030         for_( it, result.transaction().begin(), result.transaction().end() )
01031         {
01032           if ( makeResObject( *it )->mediaNr() > 1 )
01033             break;
01034           steps.push_back( *it );
01035         }
01036       }
01037       else
01038       {
01039         result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
01040       }
01041       MIL << "Todo: " << result << endl;
01042 
01044       // First collect and display all messages
01045       // associated with patches to be installed.
01047       if ( ! policy_r.dryRun() )
01048       {
01049         for_( it, steps.begin(), steps.end() )
01050         {
01051           if ( ! it->satSolvable().isKind<Patch>() )
01052             continue;
01053 
01054           PoolItem pi( *it );
01055           if ( ! pi.status().isToBeInstalled() )
01056             continue;
01057 
01058           Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
01059           if ( ! patch ||patch->message().empty()  )
01060             continue;
01061 
01062           MIL << "Show message for " << patch << endl;
01063           callback::SendReport<target::PatchMessageReport> report;
01064           if ( ! report->show( patch ) )
01065           {
01066             WAR << "commit aborted by the user" << endl;
01067             ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
01068           }
01069         }
01070       }
01071       else
01072       {
01073         DBG << "dryRun: Not checking patch messages." << endl;
01074       }
01075 
01077       // Remove/install packages.
01079       DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
01080       if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
01081       {
01082         // Prepare the package cache. Pass all items requiring download.
01083         repo::RepoMediaAccess access;
01084         RepoProvidePackage repoProvidePackage( access, pool_r );
01085         CommitPackageCache packageCache( root() / "tmp", repoProvidePackage );
01086         packageCache.setCommitList( steps.begin(), steps.end() );
01087 
01088         bool miss = false;
01089         if ( policy_r.downloadMode() != DownloadAsNeeded )
01090         {
01091           // Preload the cache. Until now this means pre-loading all packages.
01092           // Once DownloadInHeaps is fully implemented, this will change and
01093           // we may actually have more than one heap.
01094           for_( it, steps.begin(), steps.end() )
01095           {
01096             switch ( it->stepType() )
01097             {
01098               case sat::Transaction::TRANSACTION_INSTALL:
01099               case sat::Transaction::TRANSACTION_MULTIINSTALL:
01100                 // proceed: only install actionas may require download.
01101                 break;
01102 
01103               default:
01104                 // next: no download for or non-packages and delete actions.
01105                 continue;
01106                 break;
01107             }
01108 
01109             PoolItem pi( *it );
01110             if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
01111             {
01112               ManagedFile localfile;
01113               try
01114               {
01115                 // TODO: unify packageCache.get for Package and SrcPackage
01116                 if ( pi->isKind<Package>() )
01117                 {
01118                   localfile = packageCache.get( pi );
01119                 }
01120                 else if ( pi->isKind<SrcPackage>() )
01121                 {
01122                   repo::RepoMediaAccess access;
01123                   repo::SrcPackageProvider prov( access );
01124                   localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
01125                 }
01126                 else
01127                 {
01128                   INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
01129                   continue;
01130                 }
01131                 localfile.resetDispose(); // keep the package file in the cache
01132               }
01133               catch ( const AbortRequestException & exp )
01134               {
01135                 it->stepStage( sat::Transaction::STEP_ERROR );
01136                 miss = true;
01137                 WAR << "commit cache preload aborted by the user" << endl;
01138                 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
01139                 break;
01140               }
01141               catch ( const SkipRequestException & exp )
01142               {
01143                 ZYPP_CAUGHT( exp );
01144                 it->stepStage( sat::Transaction::STEP_ERROR );
01145                 miss = true;
01146                 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
01147                 continue;
01148               }
01149               catch ( const Exception & exp )
01150               {
01151                 // bnc #395704: missing catch causes abort.
01152                 // TODO see if packageCache fails to handle errors correctly.
01153                 ZYPP_CAUGHT( exp );
01154                 it->stepStage( sat::Transaction::STEP_ERROR );
01155                 miss = true;
01156                 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
01157                 continue;
01158               }
01159             }
01160           }
01161         }
01162 
01163         if ( miss )
01164         {
01165           ERR << "Some packages could not be provided. Aborting commit."<< endl;
01166         }
01167         else if ( ! policy_r.dryRun() )
01168         {
01169           commit( policy_r, packageCache, result );
01170         }
01171         else
01172         {
01173           DBG << "dryRun: Not installing/deleting anything." << endl;
01174         }
01175       }
01176       else
01177       {
01178         DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
01179       }
01180 
01182       // Try to rebuild solv file while rpm database is still in cache
01184       if ( ! policy_r.dryRun() )
01185       {
01186         buildCache();
01187       }
01188 
01189       // for DEPRECATED old ZyppCommitResult results:
01191       // build return statistics
01193       result._errors.clear();
01194       result._remaining.clear();
01195       result._srcremaining.clear();
01196       unsigned toInstall = 0;
01197       for_( step, steps.begin(), steps.end() )
01198       {
01199         if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
01200         {
01201           // For non-packages only products might have beed installed.
01202           // All the rest is ignored.
01203           if ( step->satSolvable().isSystem() || ! step->satSolvable().isKind<Product>() )
01204             continue;
01205         }
01206         else if ( step->stepType() == sat::Transaction::TRANSACTION_ERASE )
01207         {
01208           continue;
01209         }
01210         // to be installed:
01211         ++toInstall;
01212         switch ( step->stepStage() )
01213         {
01214           case sat::Transaction::STEP_TODO:
01215             if ( step->satSolvable().isKind<Package>() )
01216               result._remaining.push_back( PoolItem( *step ) );
01217             else if ( step->satSolvable().isKind<SrcPackage>() )
01218               result._srcremaining.push_back( PoolItem( *step ) );
01219             break;
01220           case sat::Transaction::STEP_DONE:
01221             // NOOP
01222             break;
01223           case sat::Transaction::STEP_ERROR:
01224             result._errors.push_back( PoolItem( *step ) );
01225             break;
01226         }
01227       }
01228       result._result = (toInstall - result._remaining.size());
01230 
01231       MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
01232       return result;
01233     }
01234 
01236     //
01237     // COMMIT internal
01238     //
01240     void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
01241                              CommitPackageCache & packageCache_r,
01242                              ZYppCommitResult & result_r )
01243     {
01244       // steps: this is our todo-list
01245       ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
01246       MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
01247 
01248       bool abort = false;
01249       std::vector<sat::Solvable> successfullyInstalledPackages;
01250       TargetImpl::PoolItemList remaining;
01251 
01252       for_( step, steps.begin(), steps.end() )
01253       {
01254         PoolItem citem( *step );
01255         if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
01256         {
01257           if ( citem->isKind<Package>() )
01258           {
01259             // for packages this means being obsoleted (by rpm)
01260             // thius no additional action is needed.
01261             step->stepStage( sat::Transaction::STEP_DONE );
01262             continue;
01263           }
01264         }
01265 
01266         if ( citem->isKind<Package>() )
01267         {
01268           Package::constPtr p = citem->asKind<Package>();
01269           if ( citem.status().isToBeInstalled() )
01270           {
01271             ManagedFile localfile;
01272             try
01273             {
01274               localfile = packageCache_r.get( citem );
01275             }
01276             catch ( const AbortRequestException &e )
01277             {
01278               WAR << "commit aborted by the user" << endl;
01279               abort = true;
01280               step->stepStage( sat::Transaction::STEP_ERROR );
01281               break;
01282             }
01283             catch ( const SkipRequestException &e )
01284             {
01285               ZYPP_CAUGHT( e );
01286               WAR << "Skipping package " << p << " in commit" << endl;
01287               step->stepStage( sat::Transaction::STEP_ERROR );
01288               continue;
01289             }
01290             catch ( const Exception &e )
01291             {
01292               // bnc #395704: missing catch causes abort.
01293               // TODO see if packageCache fails to handle errors correctly.
01294               ZYPP_CAUGHT( e );
01295               INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
01296               step->stepStage( sat::Transaction::STEP_ERROR );
01297               continue;
01298             }
01299 
01300 #warning Exception handling
01301             // create a installation progress report proxy
01302             RpmInstallPackageReceiver progress( citem.resolvable() );
01303             progress.connect(); // disconnected on destruction.
01304 
01305             bool success = false;
01306             rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
01307             // Why force and nodeps?
01308             //
01309             // Because zypp builds the transaction and the resolver asserts that
01310             // everything is fine.
01311             // We use rpm just to unpack and register the package in the database.
01312             // We do this step by step, so rpm is not aware of the bigger context.
01313             // So we turn off rpms internal checks, because we do it inside zypp.
01314             flags |= rpm::RPMINST_NODEPS;
01315             flags |= rpm::RPMINST_FORCE;
01316             //
01317             if (p->multiversionInstall())  flags |= rpm::RPMINST_NOUPGRADE;
01318             if (policy_r.dryRun())         flags |= rpm::RPMINST_TEST;
01319             if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
01320             if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
01321 
01322             try
01323             {
01324               progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
01325               rpm().installPackage( localfile, flags );
01326               HistoryLog().install(citem);
01327 
01328               if ( progress.aborted() )
01329               {
01330                 WAR << "commit aborted by the user" << endl;
01331                 localfile.resetDispose(); // keep the package file in the cache
01332                 abort = true;
01333                 step->stepStage( sat::Transaction::STEP_ERROR );
01334                 break;
01335               }
01336               else
01337               {
01338                 success = true;
01339                 step->stepStage( sat::Transaction::STEP_DONE );
01340               }
01341             }
01342             catch ( Exception & excpt_r )
01343             {
01344               ZYPP_CAUGHT(excpt_r);
01345               localfile.resetDispose(); // keep the package file in the cache
01346 
01347               if ( policy_r.dryRun() )
01348               {
01349                 WAR << "dry run failed" << endl;
01350                 step->stepStage( sat::Transaction::STEP_ERROR );
01351                 break;
01352               }
01353               // else
01354               if ( progress.aborted() )
01355               {
01356                 WAR << "commit aborted by the user" << endl;
01357                 abort = true;
01358               }
01359               else
01360               {
01361                 WAR << "Install failed" << endl;
01362               }
01363               step->stepStage( sat::Transaction::STEP_ERROR );
01364               break; // stop
01365             }
01366 
01367             if ( success && !policy_r.dryRun() )
01368             {
01369               citem.status().resetTransact( ResStatus::USER );
01370               successfullyInstalledPackages.push_back( citem.satSolvable() );
01371               step->stepStage( sat::Transaction::STEP_DONE );
01372             }
01373           }
01374           else
01375           {
01376             RpmRemovePackageReceiver progress( citem.resolvable() );
01377             progress.connect(); // disconnected on destruction.
01378 
01379             bool success = false;
01380             rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
01381             flags |= rpm::RPMINST_NODEPS;
01382             if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
01383             try
01384             {
01385               rpm().removePackage( p, flags );
01386               HistoryLog().remove(citem);
01387 
01388               if ( progress.aborted() )
01389               {
01390                 WAR << "commit aborted by the user" << endl;
01391                 abort = true;
01392                 step->stepStage( sat::Transaction::STEP_ERROR );
01393                 break;
01394               }
01395               else
01396               {
01397                 success = true;
01398                 step->stepStage( sat::Transaction::STEP_DONE );
01399               }
01400             }
01401             catch (Exception & excpt_r)
01402             {
01403               ZYPP_CAUGHT( excpt_r );
01404               if ( progress.aborted() )
01405               {
01406                 WAR << "commit aborted by the user" << endl;
01407                 abort = true;
01408                 step->stepStage( sat::Transaction::STEP_ERROR );
01409                 break;
01410               }
01411               // else
01412               WAR << "removal of " << p << " failed";
01413               step->stepStage( sat::Transaction::STEP_ERROR );
01414             }
01415             if ( success && !policy_r.dryRun() )
01416             {
01417               citem.status().resetTransact( ResStatus::USER );
01418               step->stepStage( sat::Transaction::STEP_DONE );
01419             }
01420           }
01421         }
01422         else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
01423         {
01424           // Status is changed as the buddy package buddy
01425           // gets installed/deleted. Handle non-buddies only.
01426           if ( ! citem.buddy() )
01427           {
01428             if ( citem->isKind<Product>() )
01429             {
01430               Product::constPtr p = citem->asKind<Product>();
01431               if ( citem.status().isToBeInstalled() )
01432               {
01433                 ERR << "Can't install orphan product without release-package! " << citem << endl;
01434               }
01435               else
01436               {
01437                 // Deleting the corresponding product entry is all we con do.
01438                 // So the product will no longer be visible as installed.
01439                 std::string referenceFilename( p->referenceFilename() );
01440                 if ( referenceFilename.empty() )
01441                 {
01442                   ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
01443                 }
01444                 else
01445                 {
01446                   PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
01447                   if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
01448                   {
01449                     ERR << "Delete orphan product failed: " << referenceFile << endl;
01450                   }
01451                 }
01452               }
01453             }
01454             else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
01455             {
01456               // SrcPackage is install-only
01457               SrcPackage::constPtr p = citem->asKind<SrcPackage>();
01458               installSrcPackage( p );
01459             }
01460 
01461             citem.status().resetTransact( ResStatus::USER );
01462             step->stepStage( sat::Transaction::STEP_DONE );
01463           }
01464 
01465         }  // other resolvables
01466 
01467       } // for
01468 
01469       // Check presence of update scripts/messages. If aborting,
01470       // at least log omitted scripts.
01471       if ( ! successfullyInstalledPackages.empty() )
01472       {
01473         if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
01474                                  successfullyInstalledPackages, abort ) )
01475         {
01476           WAR << "Commit aborted by the user" << endl;
01477           abort = true;
01478         }
01479         // send messages after scripts in case some script generates output,
01480         // that should be kept in t %ghost message file.
01481         RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
01482                            successfullyInstalledPackages,
01483                            result_r );
01484       }
01485 
01486       if ( abort )
01487       {
01488         ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
01489       }
01490     }
01491 
01493 
01494     rpm::RpmDb & TargetImpl::rpm()
01495     {
01496       return _rpm;
01497     }
01498 
01499     bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
01500     {
01501       return _rpm.hasFile(path_str, name_str);
01502     }
01503 
01504 
01505     Date TargetImpl::timestamp() const
01506     {
01507       return _rpm.timestamp();
01508     }
01509 
01511 
01512     Product::constPtr TargetImpl::baseProduct() const
01513     {
01514       ResPool pool(ResPool::instance());
01515       for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
01516       {
01517         Product::constPtr p = (*it)->asKind<Product>();
01518         if ( p->isTargetDistribution() )
01519           return p;
01520       }
01521       return 0L;
01522     }
01523 
01525 
01526     namespace
01527     {
01528       parser::ProductFileData baseproductdata( const Pathname & root_r )
01529       {
01530         PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
01531         if ( baseproduct.isFile() )
01532         {
01533           try
01534           {
01535             return parser::ProductFileReader::scanFile( baseproduct.path() );
01536           }
01537           catch ( const Exception & excpt )
01538           {
01539             ZYPP_CAUGHT( excpt );
01540           }
01541         }
01542         return parser::ProductFileData();
01543       }
01544 
01545       inline Pathname staticGuessRoot( const Pathname & root_r )
01546       {
01547         if ( root_r.empty() )
01548         {
01549           // empty root: use existing Target or assume "/"
01550           Pathname ret ( ZConfig::instance().systemRoot() );
01551           if ( ret.empty() )
01552             return Pathname("/");
01553           return ret;
01554         }
01555         return root_r;
01556       }
01557 
01558       inline std::string firstNonEmptyLineIn( const Pathname & file_r )
01559       {
01560         std::ifstream idfile( file_r.c_str() );
01561         for( iostr::EachLine in( idfile ); in; in.next() )
01562         {
01563           std::string line( str::trim( *in ) );
01564           if ( ! line.empty() )
01565             return line;
01566         }
01567         return std::string();
01568       }
01569     }
01570 
01571     std::string TargetImpl::targetDistribution() const
01572     { return baseproductdata( _root ).registerTarget(); }
01573     // static version:
01574     std::string TargetImpl::targetDistribution( const Pathname & root_r )
01575     { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
01576 
01577     std::string TargetImpl::targetDistributionRelease() const
01578     { return baseproductdata( _root ).registerRelease(); }
01579     // static version:
01580     std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
01581     { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
01582 
01583     Target::DistributionLabel TargetImpl::distributionLabel() const
01584     {
01585       Target::DistributionLabel ret;
01586       parser::ProductFileData pdata( baseproductdata( _root ) );
01587       ret.shortName = pdata.shortName();
01588       ret.summary = pdata.summary();
01589       return ret;
01590     }
01591     // static version:
01592     Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
01593     {
01594       Target::DistributionLabel ret;
01595       parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
01596       ret.shortName = pdata.shortName();
01597       ret.summary = pdata.summary();
01598       return ret;
01599     }
01600 
01601     std::string TargetImpl::distributionVersion() const
01602     {
01603       if ( _distributionVersion.empty() )
01604       {
01605         _distributionVersion = TargetImpl::distributionVersion(root());
01606         if ( !_distributionVersion.empty() )
01607           MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
01608       }
01609       return _distributionVersion;
01610     }
01611     // static version
01612     std::string TargetImpl::distributionVersion( const Pathname & root_r )
01613     {
01614       std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
01615       if ( distributionVersion.empty() )
01616       {
01617         // ...But the baseproduct method is not expected to work on RedHat derivatives.
01618         // On RHEL, Fedora and others the "product version" is determined by the first package
01619         // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
01620         // with the $distroverpkg variable.
01621         scoped_ptr<rpm::RpmDb> tmprpmdb;
01622         if ( ZConfig::instance().systemRoot() == Pathname() )
01623         {
01624           try
01625           {
01626               tmprpmdb.reset( new rpm::RpmDb );
01627               tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
01628           }
01629           catch( ... )
01630           {
01631             return "";
01632           }
01633         }
01634         rpm::librpmDb::db_const_iterator it;
01635         if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
01636           distributionVersion = it->tag_version();
01637       }
01638       return distributionVersion;
01639     }
01640 
01641 
01642     std::string TargetImpl::distributionFlavor() const
01643     {
01644       return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
01645     }
01646     // static version:
01647     std::string TargetImpl::distributionFlavor( const Pathname & root_r )
01648     {
01649       return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
01650     }
01651 
01653 
01654     std::string TargetImpl::anonymousUniqueId() const
01655     {
01656       return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
01657     }
01658     // static version:
01659     std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
01660     {
01661       return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
01662     }
01663 
01665 
01666     void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
01667     {
01668       // provide on local disk
01669       repo::RepoMediaAccess access_r;
01670       repo::SrcPackageProvider prov( access_r );
01671       ManagedFile localfile = prov.provideSrcPackage( srcPackage_r );
01672       // install it
01673       rpm().installPackage ( localfile );
01674     }
01675 
01677   } // namespace target
01680 } // namespace zypp