libzypp 8.13.6

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