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       // DownloadOnly implies dry-run.
00947       if ( policy_r.downloadMode() == DownloadOnly )
00948         policy_r.dryRun( true );
00949       // ----------------------------------------------------------------- //
00950 
00951       MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
00952 
00954       // Write out a testcase if we're in dist upgrade mode.
00956       if ( getZYpp()->resolver()->upgradeMode() )
00957       {
00958         if ( ! policy_r.dryRun() )
00959         {
00960           writeUpgradeTestcase();
00961         }
00962         else
00963         {
00964           DBG << "dryRun: Not writing upgrade testcase." << endl;
00965         }
00966       }
00967 
00969       // Store non-package data:
00971       if ( ! policy_r.dryRun() )
00972       {
00973         filesystem::assert_dir( home() );
00974         // requested locales
00975         _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
00976         // weak locks
00977         {
00978           SoftLocksFile::Data newdata;
00979           pool_r.getActiveSoftLocks( newdata );
00980           _softLocksFile.setData( newdata );
00981         }
00982         // hard locks
00983         if ( ZConfig::instance().apply_locks_file() )
00984         {
00985           HardLocksFile::Data newdata;
00986           pool_r.getHardLockQueries( newdata );
00987           _hardLocksFile.setData( newdata );
00988         }
00989       }
00990       else
00991       {
00992         DBG << "dryRun: Not stroring non-package data." << endl;
00993       }
00994 
00996       // Compute transaction:
00998 
00999       ZYppCommitResult result( root() );
01000       TargetImpl::PoolItemList to_uninstall;
01001       TargetImpl::PoolItemList to_install;
01002       TargetImpl::PoolItemList to_srcinstall;
01003 
01004       {
01005         pool::GetResolvablesToInsDel
01006         collect( pool_r, policy_r.restrictToMedia() ? pool::GetResolvablesToInsDel::ORDER_BY_MEDIANR
01007                  : pool::GetResolvablesToInsDel::ORDER_BY_SOURCE );
01008         MIL << "GetResolvablesToInsDel: " << endl << collect << endl;
01009         to_uninstall.swap ( collect._toDelete );
01010         to_install.swap   ( collect._toInstall );
01011         to_srcinstall.swap( collect._toSrcinstall );
01012       }
01013 
01014       if ( policy_r.restrictToMedia() )
01015       {
01016         MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
01017 
01018         TargetImpl::PoolItemList current_install;
01019         TargetImpl::PoolItemList current_srcinstall;
01020 
01021         // Collect until the 1st package from an unwanted media occurs.
01022         // Further collection could violate install order.
01023         bool hitUnwantedMedia = false;
01024         for ( TargetImpl::PoolItemList::iterator it = to_install.begin(); it != to_install.end(); ++it )
01025         {
01026           ResObject::constPtr res( it->resolvable() );
01027 
01028           if ( hitUnwantedMedia
01029                || ( res->mediaNr() && res->mediaNr() != policy_r.restrictToMedia() ) )
01030           {
01031             hitUnwantedMedia = true;
01032             result._remaining.push_back( *it );
01033           }
01034           else
01035           {
01036             current_install.push_back( *it );
01037           }
01038         }
01039 
01040         for (TargetImpl::PoolItemList::iterator it = to_srcinstall.begin(); it != to_srcinstall.end(); ++it)
01041         {
01042           Resolvable::constPtr res( it->resolvable() );
01043           Package::constPtr pkg( asKind<Package>(res) );
01044           if ( pkg && policy_r.restrictToMedia() != pkg->mediaNr() ) // check medianr for packages only
01045           {
01046             result._srcremaining.push_back( *it );
01047           }
01048           else
01049           {
01050             current_srcinstall.push_back( *it );
01051           }
01052         }
01053 
01054         to_install.swap   ( current_install );
01055         to_srcinstall.swap( current_srcinstall );
01056       }
01057 
01059       // First collect and display all messages
01060       // associated with patches to be installed.
01062       if ( ! policy_r.dryRun() )
01063       {
01064         for_( it, to_install.begin(), to_install.end() )
01065         {
01066           if ( ! isKind<Patch>(it->resolvable()) )
01067             continue;
01068           if ( ! it->status().isToBeInstalled() )
01069             continue;
01070 
01071           Patch::constPtr patch( asKind<Patch>(it->resolvable()) );
01072           if ( ! patch->message().empty() )
01073           {
01074             MIL << "Show message for " << patch << endl;
01075             callback::SendReport<target::PatchMessageReport> report;
01076             if ( ! report->show( patch ) )
01077             {
01078               WAR << "commit aborted by the user" << endl;
01079               ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
01080             }
01081           }
01082         }
01083       }
01084       else
01085       {
01086         DBG << "dryRun: Not checking patch messages." << endl;
01087       }
01088 
01090       // Remove/install packages.
01092 
01093       DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
01094       if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
01095       {
01096         // somewhat uggly constraint: The iterator passed to the CommitPackageCache
01097         // must match begin and end of the install PoolItemList passed to commit.
01098         // For the download policies it's the easiest, if we have just a single
01099         // toInstall list. So we unify to_install and to_srcinstall. In case
01100         // of errors we have to split it up again. This will be cleaned up when
01101         // we introduce the new install order.
01102         TargetImpl::PoolItemList items( to_install );
01103         items.insert( items.end(), to_srcinstall.begin(), to_srcinstall.end() );
01104 
01105         // prepare the package cache according to the download options:
01106         repo::RepoMediaAccess access;
01107         RepoProvidePackage repoProvidePackage( access, pool_r );
01108         CommitPackageCache packageCache( items.begin(), items.end(),
01109                                          root() / "tmp", repoProvidePackage );
01110 
01111         bool miss = false;
01112         if ( policy_r.downloadMode() != DownloadAsNeeded )
01113         {
01114           // Preload the cache. Until now this means pre-loading all packages.
01115           // Once DownloadInHeaps is fully implemented, this will change and
01116           // we may actually have more than one heap.
01117           for_( it, items.begin(), items.end() )
01118           {
01119             if ( (*it)->isKind<Package>() || (*it)->isKind<SrcPackage>() )
01120             {
01121               ManagedFile localfile;
01122               try
01123               {
01124                 if ( (*it)->isKind<Package>() )
01125                 {
01126                   localfile = packageCache.get( it );
01127                 }
01128                 else if ( (*it)->isKind<SrcPackage>() )
01129                 {
01130                   repo::RepoMediaAccess access;
01131                   repo::SrcPackageProvider prov( access );
01132                   localfile = prov.provideSrcPackage( (*it)->asKind<SrcPackage>() );
01133                 }
01134                 else
01135                 {
01136                   INT << "Don't know howto cache: Neither Package nor SrcPackage: " << *it << endl;
01137                   continue;
01138                 }
01139                 localfile.resetDispose(); // keep the package file in the cache
01140               }
01141               catch ( const AbortRequestException & exp )
01142               {
01143                 miss = true;
01144                 result._errors.push_back( *it );
01145                 WAR << "commit cache preload aborted by the user" << endl;
01146                 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
01147                 break;
01148               }
01149               catch ( const SkipRequestException & exp )
01150               {
01151                 ZYPP_CAUGHT( exp );
01152                 miss = true;
01153                 result._errors.push_back( *it );
01154                 WAR << "Skipping cache preload package " << (*it)->asKind<Package>() << " in commit" << endl;
01155                 continue;
01156               }
01157               catch ( const Exception & exp )
01158               {
01159                 // bnc #395704: missing catch causes abort.
01160                 // TODO see if packageCache fails to handle errors correctly.
01161                 ZYPP_CAUGHT( exp );
01162                 miss = true;
01163                 result._errors.push_back( *it );
01164                 INT << "Unexpected Error: Skipping cache preload package " << (*it)->asKind<Package>() << " in commit" << endl;
01165                 continue;
01166               }
01167             }
01168           }
01169         }
01170 
01171         if ( miss )
01172         {
01173           ERR << "Some packages could not be provided. Aborting commit."<< endl;
01174           result._remaining.insert( result._remaining.end(), to_install.begin(), to_install.end() );
01175           result._srcremaining.insert( result._srcremaining.end(), to_srcinstall.begin(), to_srcinstall.end() );
01176         }
01177         else if ( ! policy_r.dryRun() )
01178         {
01179           commit ( to_uninstall, policy_r, result, packageCache );
01180           TargetImpl::PoolItemList bad = commit( items, policy_r, result, packageCache );
01181           if ( ! bad.empty() )
01182           {
01183             for_( it, bad.begin(), bad.end() )
01184             {
01185               if ( isKind<SrcPackage>(it->resolvable()) )
01186                 result._srcremaining.push_back( *it );
01187               else
01188                 result._remaining.push_back( *it );
01189             }
01190           }
01191         }
01192         else
01193         {
01194           DBG << "dryRun: Not installing/deleting anything." << endl;
01195         }
01196       }
01197       else
01198       {
01199         DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
01200       }
01201 
01203       // Try to rebuild solv file while rpm database is still in cache
01205       if ( ! policy_r.dryRun() )
01206       {
01207         buildCache();
01208       }
01209 
01210       result._result = (to_install.size() - result._remaining.size());
01211       MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
01212       return result;
01213     }
01214 
01215 
01217     //
01218     // COMMIT internal
01219     //
01221     TargetImpl::PoolItemList
01222     TargetImpl::commit( const TargetImpl::PoolItemList & items_r,
01223                         const ZYppCommitPolicy & policy_r,
01224                         ZYppCommitResult & result_r,
01225                         CommitPackageCache & packageCache_r )
01226     {
01227       MIL << "TargetImpl::commit(<list>" << policy_r << ")" << items_r.size() << endl;
01228 
01229       bool abort = false;
01230       std::vector<sat::Solvable> successfullyInstalledPackages;
01231       TargetImpl::PoolItemList remaining;
01232 
01233       for ( TargetImpl::PoolItemList::const_iterator it = items_r.begin(); it != items_r.end(); it++ )
01234       {
01235         if ( (*it)->isKind<Package>() )
01236         {
01237           Package::constPtr p = (*it)->asKind<Package>();
01238           if (it->status().isToBeInstalled())
01239           {
01240             ManagedFile localfile;
01241             try
01242             {
01243               localfile = packageCache_r.get( it );
01244             }
01245             catch ( const AbortRequestException &e )
01246             {
01247               WAR << "commit aborted by the user" << endl;
01248               abort = true;
01249               result_r._errors.push_back( *it );
01250               remaining.insert( remaining.end(), it, items_r.end() );
01251               break;
01252             }
01253             catch ( const SkipRequestException &e )
01254             {
01255               ZYPP_CAUGHT( e );
01256               WAR << "Skipping package " << p << " in commit" << endl;
01257               result_r._errors.push_back( *it );
01258               remaining.push_back( *it );
01259               continue;
01260             }
01261             catch ( const Exception &e )
01262             {
01263               // bnc #395704: missing catch causes abort.
01264               // TODO see if packageCache fails to handle errors correctly.
01265               ZYPP_CAUGHT( e );
01266               INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
01267               result_r._errors.push_back( *it );
01268               remaining.push_back( *it );
01269               continue;
01270             }
01271 
01272 #warning Exception handling
01273             // create a installation progress report proxy
01274             RpmInstallPackageReceiver progress( it->resolvable() );
01275             progress.connect(); // disconnected on destruction.
01276 
01277             bool success = false;
01278             rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
01279             // Why force and nodeps?
01280             //
01281             // Because zypp builds the transaction and the resolver asserts that
01282             // everything is fine.
01283             // We use rpm just to unpack and register the package in the database.
01284             // We do this step by step, so rpm is not aware of the bigger context.
01285             // So we turn off rpms internal checks, because we do it inside zypp.
01286             flags |= rpm::RPMINST_NODEPS;
01287             flags |= rpm::RPMINST_FORCE;
01288             //
01289             if (p->multiversionInstall())  flags |= rpm::RPMINST_NOUPGRADE;
01290             if (policy_r.dryRun())         flags |= rpm::RPMINST_TEST;
01291             if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
01292             if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
01293 
01294             try
01295             {
01296               progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
01297               rpm().installPackage( localfile, flags );
01298               HistoryLog().install(*it);
01299 
01300               if ( progress.aborted() )
01301               {
01302                 WAR << "commit aborted by the user" << endl;
01303                 localfile.resetDispose(); // keep the package file in the cache
01304                 abort = true;
01305                 result_r._errors.push_back( *it );
01306                 remaining.insert( remaining.end(), it, items_r.end() );
01307                 break;
01308               }
01309               else
01310               {
01311                 success = true;
01312               }
01313             }
01314             catch ( Exception & excpt_r )
01315             {
01316               ZYPP_CAUGHT(excpt_r);
01317               localfile.resetDispose(); // keep the package file in the cache
01318 
01319               if ( policy_r.dryRun() )
01320               {
01321                 WAR << "dry run failed" << endl;
01322                 result_r._errors.push_back( *it );
01323                 remaining.insert( remaining.end(), it, items_r.end() );
01324                 break;
01325               }
01326               // else
01327               if ( progress.aborted() )
01328               {
01329                 WAR << "commit aborted by the user" << endl;
01330                 abort = true;
01331               }
01332               else
01333               {
01334                 WAR << "Install failed" << endl;
01335               }
01336               result_r._errors.push_back( *it );
01337               remaining.insert( remaining.end(), it, items_r.end() );
01338               break; // stop
01339             }
01340 
01341             if ( success && !policy_r.dryRun() )
01342             {
01343               it->status().resetTransact( ResStatus::USER );
01344               // Remember to check this package for presence of patch scripts.
01345               successfullyInstalledPackages.push_back( it->satSolvable() );
01346             }
01347           }
01348           else
01349           {
01350             RpmRemovePackageReceiver progress( it->resolvable() );
01351             progress.connect(); // disconnected on destruction.
01352 
01353             bool success = false;
01354             rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
01355             flags |= rpm::RPMINST_NODEPS;
01356             if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
01357             try
01358             {
01359               rpm().removePackage( p, flags );
01360               HistoryLog().remove(*it);
01361 
01362               if ( progress.aborted() )
01363               {
01364                 WAR << "commit aborted by the user" << endl;
01365                 abort = true;
01366                 result_r._errors.push_back( *it );
01367                 break;
01368               }
01369               else
01370               {
01371                 success = true;
01372               }
01373             }
01374             catch (Exception & excpt_r)
01375             {
01376               ZYPP_CAUGHT( excpt_r );
01377               if ( progress.aborted() )
01378               {
01379                 WAR << "commit aborted by the user" << endl;
01380                 abort = true;
01381                 result_r._errors.push_back( *it );
01382                 break;
01383               }
01384               // else
01385               WAR << "removal of " << p << " failed";
01386               result_r._errors.push_back( *it );
01387             }
01388             if ( success && !policy_r.dryRun() )
01389             {
01390               it->status().resetTransact( ResStatus::USER );
01391             }
01392           }
01393         }
01394         else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
01395         {
01396           // Status is changed as the buddy package buddy
01397           // gets installed/deleted. Handle non-buddies only.
01398           if ( ! it->buddy() )
01399           {
01400             if ( (*it)->isKind<Product>() )
01401             {
01402               Product::constPtr p = (*it)->asKind<Product>();
01403               if ( it->status().isToBeInstalled() )
01404               {
01405                 ERR << "Can't install orphan product without release-package! " << (*it) << endl;
01406               }
01407               else
01408               {
01409                 // Deleting the corresponding product entry is all we con do.
01410                 // So the product will no longer be visible as installed.
01411                 std::string referenceFilename( p->referenceFilename() );
01412                 if ( referenceFilename.empty() )
01413                 {
01414                   ERR << "Can't remove orphan product without 'referenceFilename'! " << (*it) << endl;
01415                 }
01416                 else
01417                 {
01418                   PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
01419                   if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
01420                   {
01421                     ERR << "Delete orphan product failed: " << referenceFile << endl;
01422                   }
01423                 }
01424               }
01425             }
01426             else if ( (*it)->isKind<SrcPackage>() && it->status().isToBeInstalled() )
01427             {
01428               // SrcPackage is install-only
01429               SrcPackage::constPtr p = (*it)->asKind<SrcPackage>();
01430               installSrcPackage( p );
01431             }
01432 
01433             it->status().resetTransact( ResStatus::USER );
01434           }
01435         }  // other resolvables
01436 
01437       } // for
01438 
01439       // Check presence of update scripts/messages. If aborting,
01440       // at least log omitted scripts.
01441       if ( ! successfullyInstalledPackages.empty() )
01442       {
01443         if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
01444                                  successfullyInstalledPackages, abort ) )
01445         {
01446           WAR << "Commit aborted by the user" << endl;
01447           abort = true;
01448         }
01449         // send messages after scripts in case some script generates output,
01450         // that should be kept in t %ghost message file.
01451         RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
01452                            successfullyInstalledPackages,
01453                            result_r );
01454       }
01455 
01456       if ( abort )
01457       {
01458         ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
01459       }
01460 
01461      return remaining;
01462     }
01463 
01464     rpm::RpmDb & TargetImpl::rpm()
01465     {
01466       return _rpm;
01467     }
01468 
01469     bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
01470     {
01471       return _rpm.hasFile(path_str, name_str);
01472     }
01473 
01474 
01475     Date TargetImpl::timestamp() const
01476     {
01477       return _rpm.timestamp();
01478     }
01479 
01481 
01482     Product::constPtr TargetImpl::baseProduct() const
01483     {
01484       ResPool pool(ResPool::instance());
01485       for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
01486       {
01487         Product::constPtr p = (*it)->asKind<Product>();
01488         if ( p->isTargetDistribution() )
01489           return p;
01490       }
01491       return 0L;
01492     }
01493 
01495 
01496     namespace
01497     {
01498       parser::ProductFileData baseproductdata( const Pathname & root_r )
01499       {
01500         PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
01501         if ( baseproduct.isFile() )
01502         {
01503           try
01504           {
01505             return parser::ProductFileReader::scanFile( baseproduct.path() );
01506           }
01507           catch ( const Exception & excpt )
01508           {
01509             ZYPP_CAUGHT( excpt );
01510           }
01511         }
01512         return parser::ProductFileData();
01513       }
01514 
01515       inline Pathname staticGuessRoot( const Pathname & root_r )
01516       {
01517         if ( root_r.empty() )
01518         {
01519           // empty root: use existing Target or assume "/"
01520           Pathname ret ( ZConfig::instance().systemRoot() );
01521           if ( ret.empty() )
01522             return Pathname("/");
01523           return ret;
01524         }
01525         return root_r;
01526       }
01527 
01528       inline std::string firstNonEmptyLineIn( const Pathname & file_r )
01529       {
01530         std::ifstream idfile( file_r.c_str() );
01531         for( iostr::EachLine in( idfile ); in; in.next() )
01532         {
01533           std::string line( str::trim( *in ) );
01534           if ( ! line.empty() )
01535             return line;
01536         }
01537         return std::string();
01538       }
01539     }
01540 
01541     std::string TargetImpl::targetDistribution() const
01542     { return baseproductdata( _root ).registerTarget(); }
01543     // static version:
01544     std::string TargetImpl::targetDistribution( const Pathname & root_r )
01545     { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
01546 
01547     std::string TargetImpl::targetDistributionRelease() const
01548     { return baseproductdata( _root ).registerRelease(); }
01549     // static version:
01550     std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
01551     { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
01552 
01553     Target::DistributionLabel TargetImpl::distributionLabel() const
01554     {
01555       Target::DistributionLabel ret;
01556       parser::ProductFileData pdata( baseproductdata( _root ) );
01557       ret.shortName = pdata.shortName();
01558       ret.summary = pdata.summary();
01559       return ret;
01560     }
01561     // static version:
01562     Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
01563     {
01564       Target::DistributionLabel ret;
01565       parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
01566       ret.shortName = pdata.shortName();
01567       ret.summary = pdata.summary();
01568       return ret;
01569     }
01570 
01571     std::string TargetImpl::distributionVersion() const
01572     {
01573       if ( _distributionVersion.empty() )
01574       {
01575         // By default ZYpp looks for /etc/product.d/baseproduct..
01576         _distributionVersion = baseproductdata( _root ).edition().version();
01577 
01578         if ( _distributionVersion.empty() )
01579         {
01580           // ...But the baseproduct method is not expected to work on RedHat derivatives.
01581           // On RHEL, Fedora and others the "product version" is determined by the first package
01582           // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
01583           // with the $distroverpkg variable.
01584           rpm::librpmDb::db_const_iterator it;
01585           if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
01586             _distributionVersion = it->tag_version();
01587         }
01588 
01589         if ( !_distributionVersion.empty() )
01590           MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
01591       }
01592       return _distributionVersion;
01593     }
01594     // static version: (no fallback to init and read rpm db here)
01595     std::string TargetImpl::distributionVersion( const Pathname & root_r )
01596     { return baseproductdata( staticGuessRoot(root_r) ).edition().version(); }
01597 
01598 
01599     std::string TargetImpl::distributionFlavor() const
01600     {
01601       return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
01602     }
01603     // static version:
01604     std::string TargetImpl::distributionFlavor( const Pathname & root_r )
01605     {
01606       return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
01607     }
01608 
01610 
01611     std::string TargetImpl::anonymousUniqueId() const
01612     {
01613       return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
01614     }
01615     // static version:
01616     std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
01617     {
01618       return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
01619     }
01620 
01622 
01623     void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
01624     {
01625       // provide on local disk
01626       repo::RepoMediaAccess access_r;
01627       repo::SrcPackageProvider prov( access_r );
01628       ManagedFile localfile = prov.provideSrcPackage( srcPackage_r );
01629       // install it
01630       rpm().installPackage ( localfile );
01631     }
01632 
01634   } // namespace target
01637 } // namespace zypp

doxygen