- Fixed lost user request to abort during commit.
[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          NULL
316       };
317
318       ExternalProgram prog( argv,
319                             ExternalProgram::Normal_Stderr,
320                             false, -1, true);
321       std::string line;
322       for(line = prog.receiveLine();
323           ! line.empty();
324           line = prog.receiveLine() )
325       {
326           MIL << line << endl;
327           id = line;
328           break;
329       }
330       prog.close();
331       return id;
332     }
333
334     /**
335      * updates the content of \p filename
336      * if \p condition is true, setting the content
337      * the the value returned by \p value
338      */
339     void updateFileContent( const Pathname &filename,
340                             boost::function<bool ()> condition,
341                             boost::function<string ()> value )
342     {
343         string val = value();
344         // if the value is empty, then just dont
345         // do anything, regardless of the condition
346         if ( val.empty() )
347             return;
348
349         if ( condition() )
350         {
351             MIL << "updating '" << filename << "' content." << endl;
352
353             // if the file does not exist we need to generate the uuid file
354
355             std::ofstream filestr;
356             // make sure the path exists
357             filesystem::assert_dir( filename.dirname() );
358             filestr.open( filename.c_str() );
359
360             if ( filestr.good() )
361             {
362                 filestr << val;
363                 filestr.close();
364             }
365             else
366             {
367                 // FIXME, should we ignore the error?
368                 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
369             }
370         }
371     }
372
373     /** helper functor */
374     static bool fileMissing( const Pathname &pathname )
375     {
376         return ! PathInfo(pathname).isExist();
377     }
378
379     void TargetImpl::createAnonymousId() const
380     {
381
382       // create the anonymous unique id
383       // this value is used for statistics
384       Pathname idpath( home() / "AnonymousUniqueId");
385
386       try
387       {
388         updateFileContent( idpath,
389                            boost::bind(fileMissing, idpath),
390                            generateRandomId );
391       }
392       catch ( const Exception &e )
393       {
394         WAR << "Can't create anonymous id file" << endl;
395       }
396
397     }
398
399     void TargetImpl::createLastDistributionFlavorCache() const
400     {
401       // create the anonymous unique id
402       // this value is used for statistics
403       Pathname flavorpath( home() / "LastDistributionFlavor");
404
405       // is there a product
406       Product::constPtr p = baseProduct();
407       if ( ! p )
408       {
409           WAR << "No base product, I won't create flavor cache" << endl;
410           return;
411       }
412
413       string flavor = p->flavor();
414
415       try
416       {
417
418         updateFileContent( flavorpath,
419                            // only if flavor is not empty
420                            functor::Constant<bool>( ! flavor.empty() ),
421                            functor::Constant<string>(flavor) );
422       }
423       catch ( const Exception &e )
424       {
425         WAR << "Can't create flavor cache" << endl;
426         return;
427       }
428     }
429
430     ///////////////////////////////////////////////////////////////////
431     //
432     //  METHOD NAME : TargetImpl::~TargetImpl
433     //  METHOD TYPE : Dtor
434     //
435     TargetImpl::~TargetImpl()
436     {
437       _rpm.closeDatabase();
438       MIL << "Targets closed" << endl;
439     }
440
441     void TargetImpl::clearCache()
442     {
443       Pathname base = Pathname::assertprefix( _root,
444                                               ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
445       filesystem::recursive_rmdir( base );
446     }
447
448     void TargetImpl::buildCache()
449     {
450       Pathname base = Pathname::assertprefix( _root,
451                                               ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
452       Pathname rpmsolv       = base/"solv";
453       Pathname rpmsolvcookie = base/"cookie";
454
455       bool build_rpm_solv = true;
456       // lets see if the rpm solv cache exists
457
458       RepoStatus rpmstatus( RepoStatus( _root/"/var/lib/rpm/Name" )
459                             && (_root/"/etc/products.d") );
460
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         SoftLocksFile::Data softLocks( _softLocksFile.data() );
594         if ( ! softLocks.empty() )
595         {
596           // Don't soft lock any installed item.
597           for_( it, system.solvablesBegin(), system.solvablesEnd() )
598           {
599             softLocks.erase( it->ident() );
600           }
601           ResPool::instance().setAutoSoftLocks( softLocks );
602         }
603       }
604       if ( ZConfig::instance().apply_locks_file() )
605       {
606         const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
607         if ( ! hardLocks.empty() )
608         {
609           ResPool::instance().setHardLockQueries( hardLocks );
610         }
611       }
612
613       // now that the target is loaded, we can cache the flavor
614       createLastDistributionFlavorCache();
615
616       MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
617     }
618
619     ///////////////////////////////////////////////////////////////////
620     //
621     // COMMIT
622     //
623     ///////////////////////////////////////////////////////////////////
624     ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
625     {
626       // ----------------------------------------------------------------- //
627       // Fake outstanding YCP fix: Honour restriction to media 1
628       // at installation, but install all remaining packages if post-boot.
629       ZYppCommitPolicy policy_r( policy_rX );
630       if ( policy_r.restrictToMedia() > 1 )
631         policy_r.allMedia();
632       // ----------------------------------------------------------------- //
633
634       MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
635
636       ///////////////////////////////////////////////////////////////////
637       // Store non-package data:
638       ///////////////////////////////////////////////////////////////////
639       filesystem::assert_dir( home() );
640       // requested locales
641       _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
642       // weak locks
643       {
644         SoftLocksFile::Data newdata;
645         pool_r.getActiveSoftLocks( newdata );
646         _softLocksFile.setData( newdata );
647       }
648       // hard locks
649       if ( ZConfig::instance().apply_locks_file() )
650       {
651         HardLocksFile::Data newdata;
652         pool_r.getHardLockQueries( newdata );
653         _hardLocksFile.setData( newdata );
654       }
655
656       ///////////////////////////////////////////////////////////////////
657       // Process packages:
658       ///////////////////////////////////////////////////////////////////
659
660       DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
661
662       ZYppCommitResult result;
663
664       TargetImpl::PoolItemList to_uninstall;
665       TargetImpl::PoolItemList to_install;
666       TargetImpl::PoolItemList to_srcinstall;
667       {
668
669         pool::GetResolvablesToInsDel
670         collect( pool_r, policy_r.restrictToMedia() ? pool::GetResolvablesToInsDel::ORDER_BY_MEDIANR
671                  : pool::GetResolvablesToInsDel::ORDER_BY_SOURCE );
672         MIL << "GetResolvablesToInsDel: " << endl << collect << endl;
673         to_uninstall.swap( collect._toDelete );
674         to_install.swap( collect._toInstall );
675         to_srcinstall.swap( collect._toSrcinstall );
676       }
677
678       if ( policy_r.restrictToMedia() )
679       {
680         MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
681       }
682
683       ///////////////////////////////////////////////////////////////////
684       // First collect and display all messages
685       // associated with patches to be installed.
686       ///////////////////////////////////////////////////////////////////
687       for_( it, to_install.begin(), to_install.end() )
688       {
689         if ( ! isKind<Patch>(it->resolvable()) )
690           continue;
691         if ( ! it->status().isToBeInstalled() )
692           continue;
693
694         Patch::constPtr patch( asKind<Patch>(it->resolvable()) );
695         if ( ! patch->message().empty() )
696         {
697           MIL << "Show message for " << patch << endl;
698           callback::SendReport<target::PatchMessageReport> report;
699           if ( ! report->show( patch ) )
700           {
701             WAR << "commit aborted by the user" << endl;
702             ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
703           }
704         }
705       }
706
707       ///////////////////////////////////////////////////////////////////
708       // Remove/install packages.
709       ///////////////////////////////////////////////////////////////////
710      commit ( to_uninstall, policy_r, pool_r );
711
712       if (policy_r.restrictToMedia() == 0)
713       {                 // commit all
714         result._remaining = commit( to_install, policy_r, pool_r );
715         result._srcremaining = commit( to_srcinstall, policy_r, pool_r );
716       }
717       else
718       {
719         TargetImpl::PoolItemList current_install;
720         TargetImpl::PoolItemList current_srcinstall;
721
722         // Collect until the 1st package from an unwanted media occurs.
723         // Further collection could violate install order.
724         bool hitUnwantedMedia = false;
725         for (TargetImpl::PoolItemList::iterator it = to_install.begin(); it != to_install.end(); ++it)
726         {
727           ResObject::constPtr res( it->resolvable() );
728
729           if ( hitUnwantedMedia
730                || ( res->mediaNr() && res->mediaNr() != policy_r.restrictToMedia() ) )
731           {
732             hitUnwantedMedia = true;
733             result._remaining.push_back( *it );
734           }
735           else
736           {
737             current_install.push_back( *it );
738           }
739         }
740
741         TargetImpl::PoolItemList bad = commit( current_install, policy_r, pool_r );
742         result._remaining.insert(result._remaining.end(), bad.begin(), bad.end());
743
744         for (TargetImpl::PoolItemList::iterator it = to_srcinstall.begin(); it != to_srcinstall.end(); ++it)
745         {
746           Resolvable::constPtr res( it->resolvable() );
747           Package::constPtr pkg( asKind<Package>(res) );
748           if (pkg && policy_r.restrictToMedia() != pkg->mediaNr()) // check medianr for packages only
749           {
750             XXX << "Package " << *pkg << ", wrong media " << pkg->mediaNr() << endl;
751             result._srcremaining.push_back( *it );
752           }
753           else
754           {
755             current_srcinstall.push_back( *it );
756           }
757         }
758         bad = commit( current_srcinstall, policy_r, pool_r );
759         result._srcremaining.insert(result._srcremaining.end(), bad.begin(), bad.end());
760       }
761
762       ///////////////////////////////////////////////////////////////////
763       // Try to rebuild solv file while rpm database is still in cache.
764       ///////////////////////////////////////////////////////////////////
765       buildCache();
766
767       result._result = (to_install.size() - result._remaining.size());
768       MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
769       return result;
770     }
771
772
773     ///////////////////////////////////////////////////////////////////
774     //
775     // COMMIT internal
776     //
777     ///////////////////////////////////////////////////////////////////
778     TargetImpl::PoolItemList
779     TargetImpl::commit( const TargetImpl::PoolItemList & items_r,
780                         const ZYppCommitPolicy & policy_r,
781                         const ResPool & pool_r )
782     {
783       TargetImpl::PoolItemList remaining;
784       repo::RepoMediaAccess access;
785       MIL << "TargetImpl::commit(<list>" << policy_r << ")" << items_r.size() << endl;
786
787       bool abort = false;
788       std::vector<sat::Solvable> successfullyInstalledPackages;
789
790       // prepare the package cache.
791       RepoProvidePackage repoProvidePackage( access, pool_r );
792       CommitPackageCache packageCache( items_r.begin(), items_r.end(),
793                                        root() / "tmp", repoProvidePackage );
794
795       for ( TargetImpl::PoolItemList::const_iterator it = items_r.begin(); it != items_r.end(); it++ )
796       {
797         if ( (*it)->isKind<Package>() )
798         {
799           Package::constPtr p = (*it)->asKind<Package>();
800           if (it->status().isToBeInstalled())
801           {
802             ManagedFile localfile;
803             try
804             {
805               localfile = packageCache.get( it );
806             }
807             catch ( const AbortRequestException &e )
808             {
809               WAR << "commit aborted by the user" << endl;
810               abort = true;
811               break;
812             }
813             catch ( const SkipRequestException &e )
814             {
815               ZYPP_CAUGHT( e );
816               WAR << "Skipping package " << p << " in commit" << endl;
817               continue;
818             }
819             catch ( const Exception &e )
820             {
821               // bnc #395704: missing catch causes abort.
822               // TODO see if packageCache fails to handle errors correctly.
823               ZYPP_CAUGHT( e );
824               INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
825               continue;
826             }
827
828 #warning Exception handling
829             // create a installation progress report proxy
830             RpmInstallPackageReceiver progress( it->resolvable() );
831             progress.connect(); // disconnected on destruction.
832
833             bool success = false;
834             rpm::RpmInstFlags flags;
835             // Why force and nodeps?
836             //
837             // Because zypp builds the transaction and the resolver asserts that
838             // everything is fine.
839             // We use rpm just to unpack and register the package in the database.
840             // We do this step by step, so rpm is not aware of the bigger context.
841             // So we turn off rpms internal checks, because we do it inside zypp.
842             flags |= rpm::RPMINST_NODEPS;
843             flags |= rpm::RPMINST_FORCE;
844             //
845             if (p->installOnly())          flags |= rpm::RPMINST_NOUPGRADE;
846             if (policy_r.dryRun())         flags |= rpm::RPMINST_TEST;
847             if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
848             if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
849
850             try
851             {
852               progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
853               rpm().installPackage( localfile, flags );
854               HistoryLog().install(*it);
855
856               if ( progress.aborted() )
857               {
858                 WAR << "commit aborted by the user" << endl;
859                 abort = true;
860                 break;
861               }
862               else
863               {
864                 success = true;
865               }
866             }
867             catch ( Exception & excpt_r )
868             {
869               ZYPP_CAUGHT(excpt_r);
870               if ( policy_r.dryRun() )
871               {
872                 WAR << "dry run failed" << endl;
873                 break;
874               }
875               // else
876               if ( progress.aborted() )
877               {
878                 WAR << "commit aborted by the user" << endl;
879                 abort = true;
880               }
881               else
882               {
883                 WAR << "Install failed" << endl;
884               }
885               remaining.push_back( *it );
886               break; // stop
887             }
888
889             if ( success && !policy_r.dryRun() )
890             {
891               it->status().resetTransact( ResStatus::USER );
892               // Remember to check this package for presence of patch scripts.
893               successfullyInstalledPackages.push_back( it->satSolvable() );
894             }
895           }
896           else
897           {
898             RpmRemovePackageReceiver progress( it->resolvable() );
899             progress.connect(); // disconnected on destruction.
900
901             bool success = false;
902             rpm::RpmInstFlags flags( rpm::RPMINST_NODEPS );
903             if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
904             try
905             {
906               rpm().removePackage( p, flags );
907               HistoryLog().remove(*it);
908
909               if ( progress.aborted() )
910               {
911                 WAR << "commit aborted by the user" << endl;
912                 abort = true;
913                 break;
914               }
915               else
916               {
917                 success = true;
918               }
919             }
920             catch (Exception & excpt_r)
921             {
922               ZYPP_CAUGHT( excpt_r );
923               if ( progress.aborted() )
924               {
925                 WAR << "commit aborted by the user" << endl;
926                 abort = true;
927                 break;
928               }
929               // else
930               WAR << "removal of " << p << " failed";
931             }
932             if ( success && !policy_r.dryRun() )
933             {
934               it->status().resetTransact( ResStatus::USER );
935             }
936           }
937         }
938         else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
939         {
940           // Status is changed as the buddy package buddy
941           // gets installed/deleted. Handle non-buddies only.
942           if ( ! it->buddy() )
943           {
944             if ( (*it)->isKind<Product>() )
945             {
946               Product::constPtr p = (*it)->asKind<Product>();
947               if ( it->status().isToBeInstalled() )
948               {
949                 ERR << "Can't install orphan product without release-package! " << (*it) << endl;
950               }
951               else
952               {
953                 // Deleting the corresponding product entry is all we con do.
954                 // So the product will no longer be visible as installed.
955                 std::string referenceFilename( p->referenceFilename() );
956                 if ( referenceFilename.empty() )
957                 {
958                   ERR << "Can't remove orphan product without 'referenceFilename'! " << (*it) << endl;
959                 }
960                 else
961                 {
962                   PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
963                   if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
964                   {
965                     ERR << "Delete orphan product failed: " << referenceFile << endl;
966                   }
967                 }
968               }
969             }
970             else if ( (*it)->isKind<SrcPackage>() && it->status().isToBeInstalled() )
971             {
972               // SrcPackage is install-only
973               SrcPackage::constPtr p = (*it)->asKind<SrcPackage>();
974               installSrcPackage( p );
975             }
976
977             it->status().resetTransact( ResStatus::USER );
978           }
979         }  // other resolvables
980
981       } // for
982
983       // Check presence of patch scripts. If aborting, at least log
984       // omitted scripts.
985       if ( ! successfullyInstalledPackages.empty() )
986       {
987         if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
988                                  successfullyInstalledPackages, abort ) )
989         {
990           WAR << "Commit aborted by the user" << endl;
991           abort = true;
992         }
993       }
994
995       if ( abort )
996       {
997         ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
998       }
999
1000      return remaining;
1001     }
1002
1003     rpm::RpmDb & TargetImpl::rpm()
1004     {
1005       return _rpm;
1006     }
1007
1008     bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1009     {
1010       return _rpm.hasFile(path_str, name_str);
1011     }
1012
1013
1014     Date TargetImpl::timestamp() const
1015     {
1016       return _rpm.timestamp();
1017     }
1018
1019     ///////////////////////////////////////////////////////////////////
1020
1021     std::string TargetImpl::release() const
1022     {
1023       std::ifstream suseRelease( (_root / "/etc/SuSE-release").c_str() );
1024       for( iostr::EachLine in( suseRelease ); in; in.next() )
1025       {
1026         std::string line( str::trim( *in ) );
1027         if ( ! line.empty() )
1028           return line;
1029       }
1030
1031       return _("Unknown Distribution");
1032     }
1033
1034     ///////////////////////////////////////////////////////////////////
1035
1036     Product::constPtr TargetImpl::baseProduct() const
1037     {
1038       ResPool pool(ResPool::instance());
1039       for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1040       {
1041         Product::constPtr p = (*it)->asKind<Product>();
1042         if ( p->isTargetDistribution() )
1043           return p;
1044       }
1045       return 0L;
1046     }
1047
1048     namespace
1049     {
1050       parser::ProductFileData baseproductdata( const Pathname & root_r )
1051       {
1052         PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1053         if ( baseproduct.isFile() )
1054         {
1055           try
1056           {
1057             return parser::ProductFileReader::scanFile( baseproduct.path() );
1058           }
1059           catch ( const Exception & excpt )
1060           {
1061             ZYPP_CAUGHT( excpt );
1062           }
1063         }
1064         return parser::ProductFileData();
1065       }
1066
1067     }
1068
1069     std::string TargetImpl::targetDistribution() const
1070     { return baseproductdata( _root ).registerTarget(); }
1071
1072     std::string TargetImpl::targetDistributionRelease() const
1073     { return baseproductdata( _root ).registerRelease(); }
1074
1075     std::string TargetImpl::distributionVersion() const
1076     {
1077       if ( _distributionVersion.empty() )
1078       {
1079         _distributionVersion = baseproductdata( _root ).edition().version();
1080         if ( !_distributionVersion.empty() )
1081           MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1082       }
1083       return _distributionVersion;
1084     }
1085
1086     std::string TargetImpl::distributionFlavor() const
1087     {
1088         std::ifstream idfile( ( home() / "LastDistributionFlavor" ).c_str() );
1089         for( iostr::EachLine in( idfile ); in; in.next() )
1090         {
1091             std::string line( str::trim( *in ) );
1092             if ( ! line.empty() )
1093                 return line;
1094         }
1095         return std::string();
1096     }
1097
1098     ///////////////////////////////////////////////////////////////////
1099
1100     std::string TargetImpl::anonymousUniqueId() const
1101     {
1102         std::ifstream idfile( ( home() / "AnonymousUniqueId" ).c_str() );
1103         for( iostr::EachLine in( idfile ); in; in.next() )
1104         {
1105             std::string line( str::trim( *in ) );
1106             if ( ! line.empty() )
1107                 return line;
1108         }
1109         return std::string();
1110     }
1111
1112     ///////////////////////////////////////////////////////////////////
1113
1114     void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1115     {
1116       // provide on local disk
1117       repo::RepoMediaAccess access_r;
1118       repo::SrcPackageProvider prov( access_r );
1119       ManagedFile localfile = prov.provideSrcPackage( srcPackage_r );
1120       // install it
1121       rpm().installPackage ( localfile );
1122     }
1123
1124     /////////////////////////////////////////////////////////////////
1125   } // namespace target
1126   ///////////////////////////////////////////////////////////////////
1127   /////////////////////////////////////////////////////////////////
1128 } // namespace zypp
1129 ///////////////////////////////////////////////////////////////////