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