dont throw if we can't create those files
[platform/upstream/libzypp.git] / zypp / target / TargetImpl.cc
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file       zypp/target/TargetImpl.cc
10  *
11 */
12 #include <iostream>
13 #include <fstream>
14 #include <sstream>
15 #include <string>
16 #include <list>
17 #include <set>
18
19 #include <sys/types.h>
20 #include <dirent.h>
21
22 #include "zypp/base/LogTools.h"
23 #include "zypp/base/Exception.h"
24 #include "zypp/base/Iterator.h"
25 #include "zypp/base/Gettext.h"
26 #include "zypp/base/IOStream.h"
27 #include "zypp/base/Functional.h"
28 #include "zypp/base/UserRequestException.h"
29
30 #include "zypp/ZConfig.h"
31
32 #include "zypp/PoolItem.h"
33 #include "zypp/ResObjects.h"
34 #include "zypp/Url.h"
35 #include "zypp/TmpPath.h"
36 #include "zypp/RepoStatus.h"
37 #include "zypp/ExternalProgram.h"
38 #include "zypp/Repository.h"
39
40 #include "zypp/ResFilters.h"
41 #include "zypp/HistoryLog.h"
42 #include "zypp/target/TargetImpl.h"
43 #include "zypp/target/TargetCallbackReceiver.h"
44 #include "zypp/target/rpm/librpmDb.h"
45 #include "zypp/target/CommitPackageCache.h"
46
47 #include "zypp/parser/ProductFileReader.h"
48
49 #include "zypp/pool/GetResolvablesToInsDel.h"
50 #include "zypp/solver/detail/Helper.h"
51
52 #include "zypp/repo/DeltaCandidates.h"
53 #include "zypp/repo/PackageProvider.h"
54 #include "zypp/repo/SrcPackageProvider.h"
55
56 #include "zypp/sat/Pool.h"
57
58 using namespace std;
59
60 ///////////////////////////////////////////////////////////////////
61 namespace zypp
62 { /////////////////////////////////////////////////////////////////
63   ///////////////////////////////////////////////////////////////////
64   namespace target
65   { /////////////////////////////////////////////////////////////////
66
67     ///////////////////////////////////////////////////////////////////
68     namespace
69     { /////////////////////////////////////////////////////////////////
70
71       /** Execute script and report against report_r.
72        * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
73        * execution was successfull (<tt>first = true</tt>), or the desired
74        * \c PatchScriptReport::Action in case execution failed
75        * (<tt>first = false</tt>).
76        *
77        * \note The packager is responsible for setting the correct permissions
78        * of the script. If the script is not executable it is reported as an
79        * error. We must not modify the permessions.
80        */
81       std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
82                                                                  const Pathname & script_r,
83                                                                  callback::SendReport<PatchScriptReport> & report_r )
84       {
85         MIL << "Execute script " << PathInfo(script_r) << endl;
86
87         HistoryLog historylog;
88         historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
89         ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true /*, root_r*/ );
90
91         for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
92         {
93           historylog.comment(output);
94           if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
95           {
96             WAR << "User request to abort script " << script_r << endl;
97             prog.kill();
98             // the rest is handled by exit code evaluation
99             // in case the script has meanwhile finished.
100           }
101         }
102
103         std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
104
105         if ( prog.close() != 0 )
106         {
107           ret.second = report_r->problem( prog.execError() );
108           WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
109           std::ostringstream sstr;
110           sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
111           historylog.comment(sstr.str(), /*timestamp*/true);
112           return ret;
113         }
114
115         report_r->finish();
116         ret.first = true;
117         return ret;
118       }
119
120       /** Execute script and report against report_r.
121        * Return \c false if user requested \c ABORT.
122        */
123       bool executeScript( const Pathname & root_r,
124                           const Pathname & script_r,
125                           callback::SendReport<PatchScriptReport> & report_r )
126       {
127         std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
128
129         do {
130           action = doExecuteScript( root_r, script_r, report_r );
131           if ( action.first )
132             return true; // success
133
134           switch ( action.second )
135           {
136             case PatchScriptReport::ABORT:
137               WAR << "User request to abort at script " << script_r << endl;
138               return false; // requested abort.
139               break;
140
141             case PatchScriptReport::IGNORE:
142               WAR << "User request to skip script " << script_r << endl;
143               return true; // requested skip.
144               break;
145
146             case PatchScriptReport::RETRY:
147               break; // again
148           }
149         } while ( action.second == PatchScriptReport::RETRY );
150
151         // THIS is not intended to be reached:
152         INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
153         return false; // abort.
154       }
155
156       /** Look for patch scripts named 'name-version-release-*' and
157        *  execute them. Return \c false if \c ABORT was requested.
158        */
159       bool RunUpdateScripts( const Pathname & root_r,
160                              const Pathname & scriptsPath_r,
161                              const std::vector<sat::Solvable> & checkPackages_r,
162                              bool aborting_r )
163       {
164         if ( checkPackages_r.empty() )
165           return true; // no installed packages to check
166
167         MIL << "Looking for new patch scripts in (" <<  root_r << ")" << scriptsPath_r << endl;
168         Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
169         if ( ! PathInfo( scriptsDir ).isDir() )
170           return true; // no script dir
171
172         std::list<std::string> scripts;
173         filesystem::readdir( scripts, scriptsDir, /*dots*/false );
174         if ( scripts.empty() )
175           return true; // no scripts in script dir
176
177         // Now collect and execute all matching scripts.
178         // On ABORT: at least log all outstanding scripts.
179         bool abort = false;
180         for_( it, checkPackages_r.begin(), checkPackages_r.end() )
181         {
182           std::string prefix( str::form( "%s-%s-", it->name().c_str(), it->edition().c_str() ) );
183           for_( sit, scripts.begin(), scripts.end() )
184           {
185             if ( ! str::hasPrefix( *sit, prefix ) )
186               continue;
187
188             PathInfo script( scriptsDir / *sit );
189             if ( ! script.isFile() )
190               continue;
191
192             if ( abort || aborting_r )
193             {
194               WAR << "Aborting: Skip patch script " << *sit << endl;
195               HistoryLog().comment(
196                   script.path().asString() + _(" execution skipped while aborting"),
197                   /*timestamp*/true);
198             }
199             else
200             {
201               MIL << "Found patch script " << *sit << endl;
202               callback::SendReport<PatchScriptReport> report;
203               report->start( make<Package>( *it ), script.path() );
204
205               if ( ! executeScript( root_r, script.path(), report ) )
206                 abort = true; // requested abort.
207             }
208           }
209         }
210         return !abort;
211       }
212
213       /////////////////////////////////////////////////////////////////
214     } // namespace
215     ///////////////////////////////////////////////////////////////////
216
217     /** Helper for PackageProvider queries during commit. */
218     struct QueryInstalledEditionHelper
219     {
220       bool operator()( const std::string & name_r,
221                        const Edition &     ed_r,
222                        const Arch &        arch_r ) const
223       {
224         rpm::librpmDb::db_const_iterator it;
225         for ( it.findByName( name_r ); *it; ++it )
226           {
227             if ( arch_r == it->tag_arch()
228                  && ( ed_r == Edition::noedition || ed_r == it->tag_edition() ) )
229               {
230                 return true;
231               }
232           }
233         return false;
234       }
235     };
236
237     /**
238      * \short Let the Source provide the package.
239      * \p pool_r \ref ResPool used to get candidates
240      * \p pi item to be commited
241     */
242     struct RepoProvidePackage
243     {
244       ResPool _pool;
245       repo::RepoMediaAccess &_access;
246
247       RepoProvidePackage( repo::RepoMediaAccess &access, ResPool pool_r )
248         : _pool(pool_r), _access(access)
249       {
250
251       }
252
253       ManagedFile operator()( const PoolItem & pi )
254       {
255         // Redirect PackageProvider queries for installed editions
256         // (in case of patch/delta rpm processing) to rpmDb.
257         repo::PackageProviderPolicy packageProviderPolicy;
258         packageProviderPolicy.queryInstalledCB( QueryInstalledEditionHelper() );
259
260         Package::constPtr p = asKind<Package>(pi.resolvable());
261
262
263         // Build a repository list for repos
264         // contributing to the pool
265         std::list<Repository> repos( _pool.knownRepositoriesBegin(), _pool.knownRepositoriesEnd() );
266         repo::DeltaCandidates deltas(repos, p->name());
267         repo::PackageProvider pkgProvider( _access, p, deltas, packageProviderPolicy );
268         return pkgProvider.providePackage();
269       }
270     };
271     ///////////////////////////////////////////////////////////////////
272
273     IMPL_PTR_TYPE(TargetImpl);
274
275     TargetImpl_Ptr TargetImpl::_nullimpl;
276
277     /** Null implementation */
278     TargetImpl_Ptr TargetImpl::nullimpl()
279     {
280       if (_nullimpl == 0)
281         _nullimpl = new TargetImpl;
282       return _nullimpl;
283     }
284
285     ///////////////////////////////////////////////////////////////////
286     //
287     //  METHOD NAME : TargetImpl::TargetImpl
288     //  METHOD TYPE : Ctor
289     //
290     TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
291     : _root( root_r )
292     , _requestedLocalesFile( home() / "RequestedLocales" )
293     , _softLocksFile( home() / "SoftLocks" )
294     , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
295     {
296       _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
297
298       HistoryLog::setRoot(_root);
299
300       createAnonymousId();
301
302
303       MIL << "Initialized target on " << _root << endl;
304     }
305
306     /**
307      * generates a random id using uuidgen
308      */
309     static string generateRandomId()
310     {
311       string id;
312       const char* argv[] =
313       {
314          "/usr/bin/uuidgen",
315          "-r",
316          "-t",
317          NULL
318       };
319
320       ExternalProgram prog( argv,
321                             ExternalProgram::Normal_Stderr,
322                             false, -1, true);
323       std::string line;
324       for(line = prog.receiveLine();
325           ! line.empty();
326           line = prog.receiveLine() )
327       {
328           MIL << line << endl;
329           id = line;
330           break;
331       }
332       prog.close();
333       return id;
334     }
335
336     /**
337      * updates the content of \p filename
338      * if \p condition is true, setting the content
339      * the the value returned by \p value
340      */
341     void updateFileContent( const Pathname &filename,
342                             boost::function<bool ()> condition,
343                             boost::function<string ()> value )
344     {
345         string val = value();
346         // if the value is empty, then just dont
347         // do anything, regardless of the condition
348         if ( val.empty() )
349             return;
350
351         if ( condition() )
352         {
353             MIL << "updating '" << filename << "' content." << endl;
354
355             // if the file does not exist we need to generate the uuid file
356
357             std::ofstream filestr;
358             // make sure the path exists
359             filesystem::assert_dir( filename.dirname() );
360             filestr.open( filename.c_str() );
361
362             if ( filestr.good() )
363             {
364                 filestr << val;
365                 filestr.close();
366             }
367             else
368             {
369                 // FIXME, should we ignore the error?
370                 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
371             }
372         }
373     }
374
375     /** helper functor */
376     static bool fileMissing( const Pathname &pathname )
377     {
378         return ! PathInfo(pathname).isExist();
379     }
380
381     void TargetImpl::createAnonymousId() const
382     {
383
384       // create the anonymous unique id
385       // this value is used for statistics
386       Pathname idpath( home() / "AnonymousUniqueId");
387
388       try
389       {   
390         updateFileContent( idpath,
391                            boost::bind(fileMissing, idpath),
392                            generateRandomId );
393       }
394       catch ( const Exception &e )
395       {
396         WAR << "Can't create anonymous id file" << endl;
397       }
398       
399     }
400
401     void TargetImpl::createLastDistributionFlavorCache() const
402     {
403       // create the anonymous unique id
404       // this value is used for statistics
405       Pathname flavorpath( home() / "LastDistributionFlavor");
406
407       // is there a product
408       Product::constPtr p = baseProduct();
409       if ( ! p )
410       {
411           WAR << "No base product, I won't create flavor cache" << endl;
412           return;
413       }
414
415       string flavor = p->flavor();
416       
417       try
418       {
419           
420         updateFileContent( flavorpath,
421                            // only if flavor is not empty
422                            functor::Constant<bool>( ! flavor.empty() ),
423                            functor::Constant<string>(flavor) );
424       }
425       catch ( const Exception &e )
426       {
427         WAR << "Can't create flavor cache" << endl;
428         return;
429       }
430     }
431
432     ///////////////////////////////////////////////////////////////////
433     //
434     //  METHOD NAME : TargetImpl::~TargetImpl
435     //  METHOD TYPE : Dtor
436     //
437     TargetImpl::~TargetImpl()
438     {
439       _rpm.closeDatabase();
440       MIL << "Targets closed" << endl;
441     }
442
443     void TargetImpl::clearCache()
444     {
445       Pathname base = Pathname::assertprefix( _root,
446                                               ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
447       filesystem::recursive_rmdir( base );
448     }
449
450     void TargetImpl::buildCache()
451     {
452       Pathname base = Pathname::assertprefix( _root,
453                                               ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
454       Pathname rpmsolv       = base/"solv";
455       Pathname rpmsolvcookie = base/"cookie";
456
457       bool build_rpm_solv = true;
458       // lets see if the rpm solv cache exists
459
460       RepoStatus rpmstatus(_root + "/var/lib/rpm/Name");
461       bool solvexisted = PathInfo(rpmsolv).isExist();
462       if ( solvexisted )
463       {
464         // see the status of the cache
465         PathInfo cookie( rpmsolvcookie );
466         MIL << "Read cookie: " << cookie << endl;
467         if ( cookie.isExist() )
468         {
469           RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
470           // now compare it with the rpm database
471           if ( status.checksum() == rpmstatus.checksum() )
472             build_rpm_solv = false;
473           MIL << "Read cookie: " << rpmsolvcookie << " says: "
474               << (build_rpm_solv ? "outdated" : "uptodate") << endl;
475         }
476       }
477
478       if ( build_rpm_solv )
479       {
480         // Take care we unlink the solvfile on exception
481         ManagedFile guard( base, filesystem::recursive_rmdir );
482
483         // if it does not exist yet, we better create it
484         filesystem::assert_dir( base );
485
486         filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
487         if (!tmpsolv)
488         {
489           Exception ex("Failed to cache rpm database.");
490           ex.remember(str::form(
491               "Cannot create temporary file under %s.", base.c_str()));
492           ZYPP_THROW(ex);
493         }
494
495         std::ostringstream cmd;
496         cmd << "rpmdb2solv";
497         if ( ! _root.empty() )
498           cmd << " -r '" << _root << "'";
499
500         cmd << " -p '" << Pathname::assertprefix( _root, "/etc/products.d" ) << "'";
501
502         if ( solvexisted )
503           cmd << " '" << rpmsolv << "'";
504
505         cmd << "  > '" << tmpsolv.path() << "'";
506
507         MIL << "Executing: " << cmd << endl;
508         ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
509
510         cmd << endl;
511         for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
512           WAR << "  " << output;
513           cmd << "     " << output;
514         }
515
516         int ret = prog.close();
517         if ( ret != 0 )
518         {
519           Exception ex(str::form("Failed to cache rpm database (%d).", ret));
520           ex.remember( cmd.str() );
521           ZYPP_THROW(ex);
522         }
523
524         ret = filesystem::rename( tmpsolv, rpmsolv );
525         if ( ret != 0 )
526           ZYPP_THROW(Exception("Failed to move cache to final destination"));
527         // if this fails, don't bother throwing exceptions
528         filesystem::chmod( rpmsolv, 0644 );
529
530         rpmstatus.saveToCookieFile(rpmsolvcookie);
531
532         // We keep it.
533         guard.resetDispose();
534       }
535     }
536
537     void TargetImpl::unload()
538     {
539       Repository system( sat::Pool::instance().findSystemRepo() );
540       if ( system )
541         system.eraseFromPool();
542     }
543
544
545     void TargetImpl::load()
546     {
547       buildCache();
548
549       // now add the repos to the pool
550       sat::Pool satpool( sat::Pool::instance() );
551       Pathname rpmsolv( Pathname::assertprefix( _root,
552                         ZConfig::instance().repoSolvfilesPath() / satpool.systemRepoAlias() / "solv" ) );
553       MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
554
555       // Providing an empty system repo, unload any old content
556       Repository system( sat::Pool::instance().findSystemRepo() );
557       if ( system && ! system.solvablesEmpty() )
558       {
559         system.eraseFromPool(); // invalidates system
560       }
561       if ( ! system )
562       {
563         system = satpool.systemRepo();
564       }
565
566       try
567       {
568         system.addSolv( rpmsolv );
569       }
570       catch ( const Exception & exp )
571       {
572         ZYPP_CAUGHT( exp );
573         MIL << "Try to handle exception by rebuilding the solv-file" << endl;
574         clearCache();
575         buildCache();
576
577         system.addSolv( rpmsolv );
578       }
579
580       // (Re)Load the requested locales et al.
581       // If the requested locales are empty, we leave the pool untouched
582       // to avoid undoing changes the application applied. We expect this
583       // to happen on a bare metal installation only. An already existing
584       // target should be loaded before its settings are changed.
585       {
586         const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
587         if ( ! requestedLocales.empty() )
588         {
589           satpool.setRequestedLocales( requestedLocales );
590         }
591       }
592       {
593         const SoftLocksFile::Data & softLocks( _softLocksFile.data() );
594         if ( ! softLocks.empty() )
595         {
596           ResPool::instance().setAutoSoftLocks( softLocks );
597         }
598       }
599       if ( ZConfig::instance().apply_locks_file() )
600       {
601         const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
602         if ( ! hardLocks.empty() )
603         {
604           ResPool::instance().setHardLockQueries( hardLocks );
605         }
606       }
607       
608       // now that the target is loaded, we can cache the flavor
609       createLastDistributionFlavorCache();
610
611       MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
612     }
613
614     ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
615     {
616       // ----------------------------------------------------------------- //
617       // Fake outstanding YCP fix: Honour restriction to media 1
618       // at installation, but install all remaining packages if post-boot.
619       ZYppCommitPolicy policy_r( policy_rX );
620       if ( policy_r.restrictToMedia() > 1 )
621         policy_r.allMedia();
622       // ----------------------------------------------------------------- //
623
624       MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
625
626       ///////////////////////////////////////////////////////////////////
627       // Store non-package data:
628       ///////////////////////////////////////////////////////////////////
629       filesystem::assert_dir( home() );
630       // requested locales
631       _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
632       // weak locks
633       {
634         SoftLocksFile::Data newdata;
635         pool_r.getActiveSoftLocks( newdata );
636         _softLocksFile.setData( newdata );
637       }
638       // hard locks
639       if ( ZConfig::instance().apply_locks_file() )
640       {
641         HardLocksFile::Data newdata;
642         pool_r.getHardLockQueries( newdata );
643         _hardLocksFile.setData( newdata );
644       }
645
646       ///////////////////////////////////////////////////////////////////
647       // Process packages:
648       ///////////////////////////////////////////////////////////////////
649
650       DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
651
652       ZYppCommitResult result;
653
654       TargetImpl::PoolItemList to_uninstall;
655       TargetImpl::PoolItemList to_install;
656       TargetImpl::PoolItemList to_srcinstall;
657       {
658
659         pool::GetResolvablesToInsDel
660         collect( pool_r, policy_r.restrictToMedia() ? pool::GetResolvablesToInsDel::ORDER_BY_MEDIANR
661                  : pool::GetResolvablesToInsDel::ORDER_BY_SOURCE );
662         MIL << "GetResolvablesToInsDel: " << endl << collect << endl;
663         to_uninstall.swap( collect._toDelete );
664         to_install.swap( collect._toInstall );
665         to_srcinstall.swap( collect._toSrcinstall );
666       }
667
668       if ( policy_r.restrictToMedia() )
669       {
670         MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
671       }
672
673       ///////////////////////////////////////////////////////////////////
674       // First collect and display all messages
675       // associated with patches to be installed.
676       ///////////////////////////////////////////////////////////////////
677       for_( it, to_install.begin(), to_install.end() )
678       {
679         if ( ! isKind<Patch>(it->resolvable()) )
680           continue;
681         if ( ! it->status().isToBeInstalled() )
682           continue;
683
684         Patch::constPtr patch( asKind<Patch>(it->resolvable()) );
685         if ( ! patch->message().empty() )
686         {
687           MIL << "Show message for " << patch << endl;
688           callback::SendReport<target::PatchMessageReport> report;
689           if ( ! report->show( patch ) )
690           {
691             WAR << "commit aborted by the user" << endl;
692             ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
693           }
694         }
695       }
696
697       ///////////////////////////////////////////////////////////////////
698       // Remove/install packages.
699       ///////////////////////////////////////////////////////////////////
700      commit (to_uninstall, policy_r, pool_r );
701
702       if (policy_r.restrictToMedia() == 0)
703       {                 // commit all
704         result._remaining = commit( to_install, policy_r, pool_r );
705         result._srcremaining = commit( to_srcinstall, policy_r, pool_r );
706       }
707       else
708       {
709         TargetImpl::PoolItemList current_install;
710         TargetImpl::PoolItemList current_srcinstall;
711
712         // Collect until the 1st package from an unwanted media occurs.
713         // Further collection could violate install order.
714         bool hitUnwantedMedia = false;
715         for (TargetImpl::PoolItemList::iterator it = to_install.begin(); it != to_install.end(); ++it)
716         {
717           ResObject::constPtr res( it->resolvable() );
718
719           if ( hitUnwantedMedia
720                || ( res->mediaNr() && res->mediaNr() != policy_r.restrictToMedia() ) )
721           {
722             hitUnwantedMedia = true;
723             result._remaining.push_back( *it );
724           }
725           else
726           {
727             current_install.push_back( *it );
728           }
729         }
730
731         TargetImpl::PoolItemList bad = commit( current_install, policy_r, pool_r );
732         result._remaining.insert(result._remaining.end(), bad.begin(), bad.end());
733
734         for (TargetImpl::PoolItemList::iterator it = to_srcinstall.begin(); it != to_srcinstall.end(); ++it)
735         {
736           Resolvable::constPtr res( it->resolvable() );
737           Package::constPtr pkg( asKind<Package>(res) );
738           if (pkg && policy_r.restrictToMedia() != pkg->mediaNr()) // check medianr for packages only
739           {
740             XXX << "Package " << *pkg << ", wrong media " << pkg->mediaNr() << endl;
741             result._srcremaining.push_back( *it );
742           }
743           else
744           {
745             current_srcinstall.push_back( *it );
746           }
747         }
748         bad = commit( current_srcinstall, policy_r, pool_r );
749         result._srcremaining.insert(result._srcremaining.end(), bad.begin(), bad.end());
750       }
751
752       ///////////////////////////////////////////////////////////////////
753       // Try to rebuild solv file while rpm database is still in cache.
754       ///////////////////////////////////////////////////////////////////
755       buildCache();
756
757       result._result = (to_install.size() - result._remaining.size());
758       MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
759       return result;
760     }
761
762
763     TargetImpl::PoolItemList
764     TargetImpl::commit( const TargetImpl::PoolItemList & items_r,
765                         const ZYppCommitPolicy & policy_r,
766                         const ResPool & pool_r )
767     {
768       TargetImpl::PoolItemList remaining;
769       repo::RepoMediaAccess access;
770       MIL << "TargetImpl::commit(<list>" << policy_r << ")" << items_r.size() << endl;
771
772       bool abort = false;
773       std::vector<sat::Solvable> successfullyInstalledPackages;
774
775       // prepare the package cache.
776       RepoProvidePackage repoProvidePackage( access, pool_r );
777       CommitPackageCache packageCache( items_r.begin(), items_r.end(),
778                                        root() / "tmp", repoProvidePackage );
779
780       for ( TargetImpl::PoolItemList::const_iterator it = items_r.begin(); it != items_r.end(); it++ )
781       {
782         if ( (*it)->isKind<Package>() )
783         {
784           Package::constPtr p = (*it)->asKind<Package>();
785           if (it->status().isToBeInstalled())
786           {
787             ManagedFile localfile;
788             try
789             {
790               localfile = packageCache.get( it );
791             }
792             catch ( const SkipRequestException &e )
793             {
794               ZYPP_CAUGHT( e );
795               WAR << "Skipping package " << p << " in commit" << endl;
796               continue;
797             }
798             catch ( const Exception &e )
799             {
800               // bnc #395704: missing catch causes abort.
801               // TODO see if packageCache fails to handle errors correctly.
802               ZYPP_CAUGHT( e );
803               INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
804               continue;
805             }
806
807 #warning Exception handling
808             // create a installation progress report proxy
809             RpmInstallPackageReceiver progress( it->resolvable() );
810             progress.connect();
811             bool success = true;
812             rpm::RpmInstFlags flags;
813             // Why force and nodeps?
814             //
815             // Because zypp builds the transaction and the resolver asserts that
816             // everything is fine.
817             // We use rpm just to unpack and register the package in the database.
818             // We do this step by step, so rpm is not aware of the bigger context.
819             // So we turn off rpms internal checks, because we do it inside zypp.
820             flags |= rpm::RPMINST_NODEPS;
821             flags |= rpm::RPMINST_FORCE;
822             //
823             if (p->installOnly())          flags |= rpm::RPMINST_NOUPGRADE;
824             if (policy_r.dryRun())         flags |= rpm::RPMINST_TEST;
825             if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
826             if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
827
828             try
829             {
830               progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
831               rpm().installPackage( localfile, flags );
832               HistoryLog().install(*it);
833
834               if ( progress.aborted() )
835               {
836                 WAR << "commit aborted by the user" << endl;
837                 progress.disconnect();
838                 success = false;
839                 abort = true;
840                 break;
841               }
842             }
843             catch (Exception & excpt_r)
844             {
845               ZYPP_CAUGHT(excpt_r);
846               if ( policy_r.dryRun() )
847               {
848                 WAR << "dry run failed" << endl;
849                 progress.disconnect();
850                 break;
851               }
852               // else
853               WAR << "Install failed" << endl;
854               remaining.push_back( *it );
855               progress.disconnect();
856               success = false;
857               break;
858             }
859
860             if ( success && !policy_r.dryRun() )
861             {
862               it->status().resetTransact( ResStatus::USER );
863               // Remember to check this package for presence of patch scripts.
864               successfullyInstalledPackages.push_back( it->satSolvable() );
865             }
866             progress.disconnect();
867           }
868           else
869           {
870             bool success = true;
871
872             RpmRemovePackageReceiver progress( it->resolvable() );
873             progress.connect();
874             rpm::RpmInstFlags flags( rpm::RPMINST_NODEPS );
875             if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
876             try
877             {
878               rpm().removePackage( p, flags );
879               HistoryLog().remove(*it);
880
881               if ( progress.aborted() )
882               {
883                 WAR << "commit aborted by the user" << endl;
884                 progress.disconnect();
885                 success = false;
886                 abort = true;
887                 break;
888               }
889             }
890             catch (Exception & excpt_r)
891             {
892               WAR << "removal of " << p << " failed";
893               success = false;
894               ZYPP_CAUGHT( excpt_r );
895             }
896             if (success
897                 && !policy_r.dryRun())
898             {
899               it->status().resetTransact( ResStatus::USER );
900             }
901             progress.disconnect();
902           }
903         }
904         else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
905         {
906           // Status is changed as the buddy package buddy
907           // gets installed/deleted. Handle non-buddies only.
908           if ( ! it->buddy() )
909           {
910             if ( (*it)->isKind<Product>() )
911             {
912               Product::constPtr p = (*it)->asKind<Product>();
913               if ( it->status().isToBeInstalled() )
914               {
915                 ERR << "Can't install orphan product without release-package! " << (*it) << endl;
916               }
917               else
918               {
919                 // Deleting the corresponding product entry is all we con do.
920                 // So the product will no longer be visible as installed.
921                 std::string referenceFilename( p->referenceFilename() );
922                 if ( referenceFilename.empty() )
923                 {
924                   ERR << "Can't remove orphan product without 'referenceFilename'! " << (*it) << endl;
925                 }
926                 else
927                 {
928                   PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
929                   if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
930                   {
931                     ERR << "Delete orphan product failed: " << referenceFile << endl;
932                   }
933                 }
934               }
935             }
936             else if ( (*it)->isKind<SrcPackage>() && it->status().isToBeInstalled() )
937             {
938               // SrcPackage is install-only
939               SrcPackage::constPtr p = (*it)->asKind<SrcPackage>();
940               installSrcPackage( p );
941             }
942
943             it->status().resetTransact( ResStatus::USER );
944           }
945         }  // other resolvables
946
947       } // for
948
949       // Check presence of patch scripts. If aborting, at least log
950       // omitted scripts.
951       if ( ! successfullyInstalledPackages.empty() )
952       {
953         if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
954                                  successfullyInstalledPackages, abort ) )
955         {
956           WAR << "Commit aborted by the user" << endl;
957           abort = true;
958         }
959       }
960
961       if ( abort )
962       {
963         ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
964       }
965
966      return remaining;
967     }
968
969     rpm::RpmDb & TargetImpl::rpm()
970     {
971       return _rpm;
972     }
973
974     bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
975     {
976       return _rpm.hasFile(path_str, name_str);
977     }
978
979
980     Date TargetImpl::timestamp() const
981     {
982       return _rpm.timestamp();
983     }
984
985     ///////////////////////////////////////////////////////////////////
986
987     std::string TargetImpl::release() const
988     {
989       std::ifstream suseRelease( (_root / "/etc/SuSE-release").c_str() );
990       for( iostr::EachLine in( suseRelease ); in; in.next() )
991       {
992         std::string line( str::trim( *in ) );
993         if ( ! line.empty() )
994           return line;
995       }
996
997       return _("Unknown Distribution");
998     }
999
1000     ///////////////////////////////////////////////////////////////////
1001
1002     Product::constPtr TargetImpl::baseProduct() const
1003     {
1004       ResPool pool(ResPool::instance());
1005       for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1006       {
1007         Product::constPtr p = (*it)->asKind<Product>();
1008         if ( p->isTargetDistribution() )
1009           return p;
1010       }
1011       return 0L;
1012     }
1013
1014     namespace
1015     {
1016       parser::ProductFileData baseproductdata( const Pathname & root_r )
1017       {
1018         PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1019         if ( baseproduct.isFile() )
1020         {
1021           try
1022           {
1023             return parser::ProductFileReader::scanFile( baseproduct.path() );
1024           }
1025           catch ( const Exception & excpt )
1026           {
1027             ZYPP_CAUGHT( excpt );
1028           }
1029         }
1030         return parser::ProductFileData();
1031       }
1032
1033     }
1034
1035     std::string TargetImpl::targetDistribution() const
1036     { return baseproductdata( _root ).registerTarget(); }
1037
1038     std::string TargetImpl::targetDistributionRelease() const
1039     { return baseproductdata( _root ).registerRelease(); }
1040
1041     std::string TargetImpl::distributionVersion() const
1042     {
1043       if ( _distributionVersion.empty() )
1044       {
1045         _distributionVersion = baseproductdata( _root ).edition().version();
1046         if ( !_distributionVersion.empty() )
1047           MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1048       }
1049       return _distributionVersion;
1050     }
1051
1052     std::string TargetImpl::distributionFlavor() const
1053     {
1054         std::ifstream idfile( ( home() / "LastDistributionFlavor" ).c_str() );
1055         for( iostr::EachLine in( idfile ); in; in.next() )
1056         {
1057             std::string line( str::trim( *in ) );
1058             if ( ! line.empty() )
1059                 return line;
1060         }
1061         return std::string();
1062     }
1063
1064     ///////////////////////////////////////////////////////////////////
1065
1066     std::string TargetImpl::anonymousUniqueId() const
1067     {
1068         std::ifstream idfile( ( home() / "AnonymousUniqueId" ).c_str() );
1069         for( iostr::EachLine in( idfile ); in; in.next() )
1070         {
1071             std::string line( str::trim( *in ) );
1072             if ( ! line.empty() )
1073                 return line;
1074         }
1075         return std::string();
1076     }
1077
1078     ///////////////////////////////////////////////////////////////////
1079
1080     void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1081     {
1082       // provide on local disk
1083       repo::RepoMediaAccess access_r;
1084       repo::SrcPackageProvider prov( access_r );
1085       ManagedFile localfile = prov.provideSrcPackage( srcPackage_r );
1086       // install it
1087       rpm().installPackage ( localfile );
1088     }
1089
1090     /////////////////////////////////////////////////////////////////
1091   } // namespace target
1092   ///////////////////////////////////////////////////////////////////
1093   /////////////////////////////////////////////////////////////////
1094 } // namespace zypp
1095 ///////////////////////////////////////////////////////////////////