remove Target::targetDistributionFlavor
[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       RepoProvidePackage repoProvidePackage( access, pool_r);
687       // prepare the package cache.
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 (isKind<Package>(it->resolvable()))
694         {
695           Package::constPtr p = asKind<Package>(it->resolvable());
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 #if 0
710             // bnc #395704: missing catch causes abort. see if packageCache fails to handle
711             // errors correctly.
712             catch ( const Exception &e )
713             {
714               ZYPP_CAUGHT( e );
715               SEC << e << endl;
716             }
717 #endif
718
719 #warning Exception handling
720             // create a installation progress report proxy
721             RpmInstallPackageReceiver progress( it->resolvable() );
722             progress.connect();
723             bool success = true;
724             rpm::RpmInstFlags flags;
725             // Why force and nodeps?
726             //
727             // Because zypp builds the transaction and the resolver asserts that
728             // everything is fine.
729             // We use rpm just to unpack and register the package in the database.
730             // We do this step by step, so rpm is not aware of the bigger context.
731             // So we turn off rpms internal checks, because we do it inside zypp.
732             flags |= rpm::RPMINST_NODEPS;
733             flags |= rpm::RPMINST_FORCE;
734             //
735             if (p->installOnly())          flags |= rpm::RPMINST_NOUPGRADE;
736             if (policy_r.dryRun())         flags |= rpm::RPMINST_TEST;
737             if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
738             if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
739
740             try
741             {
742               progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
743               rpm().installPackage( localfile, flags );
744               HistoryLog().install(*it);
745
746               if ( progress.aborted() )
747               {
748                 WAR << "commit aborted by the user" << endl;
749                 progress.disconnect();
750                 success = false;
751                 abort = true;
752                 break;
753               }
754             }
755             catch (Exception & excpt_r)
756             {
757               ZYPP_CAUGHT(excpt_r);
758               if ( policy_r.dryRun() )
759               {
760                 WAR << "dry run failed" << endl;
761                 progress.disconnect();
762                 break;
763               }
764               // else
765               WAR << "Install failed" << endl;
766               remaining.push_back( *it );
767               progress.disconnect();
768               success = false;
769               break;
770             }
771
772             if ( success && !policy_r.dryRun() )
773             {
774               it->status().resetTransact( ResStatus::USER );
775               // Remember to check this package for presence of patch scripts.
776               successfullyInstalledPackages.push_back( it->satSolvable() );
777             }
778             progress.disconnect();
779           }
780           else
781           {
782             bool success = true;
783
784             RpmRemovePackageReceiver progress( it->resolvable() );
785             progress.connect();
786             rpm::RpmInstFlags flags( rpm::RPMINST_NODEPS );
787             if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
788             try
789             {
790               rpm().removePackage( p, flags );
791               HistoryLog().remove(*it);
792
793               if ( progress.aborted() )
794               {
795                 WAR << "commit aborted by the user" << endl;
796                 progress.disconnect();
797                 success = false;
798                 abort = true;
799                 break;
800               }
801             }
802             catch (Exception & excpt_r)
803             {
804               WAR << "removal of " << p << " failed";
805               success = false;
806               ZYPP_CAUGHT( excpt_r );
807             }
808             if (success
809                 && !policy_r.dryRun())
810             {
811               it->status().resetTransact( ResStatus::USER );
812             }
813             progress.disconnect();
814           }
815         }
816         else if (!policy_r.dryRun()) // other resolvables (non-Package)
817         {
818             if (it->buddy() == sat::Solvable())
819             {
820                 // Reset transaction only if this solvable has no buddy (Bug #417799)
821                 // e.g. do not reset Products cause the concerning release package
822                 // could not already be installed.
823                 it->status().resetTransact( ResStatus::USER );
824             }
825         }  // other resolvables
826
827       } // for
828
829       // Check presence of patch scripts. If aborting, at least log
830       // omitted scripts.
831       if ( ! successfullyInstalledPackages.empty() )
832       {
833         if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
834                                  successfullyInstalledPackages, abort ) )
835         {
836           WAR << "Commit aborted by the user" << endl;
837           abort = true;
838         }
839       }
840
841       if ( abort )
842       {
843         ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
844       }
845
846      return remaining;
847     }
848
849     rpm::RpmDb & TargetImpl::rpm()
850     {
851       return _rpm;
852     }
853
854     bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
855     {
856       return _rpm.hasFile(path_str, name_str);
857     }
858
859
860     Date TargetImpl::timestamp() const
861     {
862       return _rpm.timestamp();
863     }
864
865     ///////////////////////////////////////////////////////////////////
866
867     std::string TargetImpl::release() const
868     {
869       std::ifstream suseRelease( (_root / "/etc/SuSE-release").c_str() );
870       for( iostr::EachLine in( suseRelease ); in; in.next() )
871       {
872         std::string line( str::trim( *in ) );
873         if ( ! line.empty() )
874           return line;
875       }
876
877       return _("Unknown Distribution");
878     }
879
880     ///////////////////////////////////////////////////////////////////
881
882     namespace
883     {
884       std::string rpmdb2solvAttr( const std::string & attr_r, const Pathname & root_r )
885       {
886         std::ostringstream cmd;
887         cmd << "rpmdb2solv";
888         cmd << " -n";
889         if ( ! root_r.empty() )
890           cmd << " -r '" << root_r << "'";
891         cmd << " -p '" << Pathname::assertprefix( root_r, "/etc/products.d" ) << "'";
892         cmd << " -a " << attr_r;
893
894         MIL << "Executing: " << cmd << endl;
895         ExternalProgram prog( cmd.str(), ExternalProgram::Discard_Stderr );
896         for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() )
897         {
898           return str::trim(output);
899         }
900
901         int ret = prog.close();
902         WAR << "Got no output from rpmdb2solv (returned " << ret << ")." << endl;
903
904         return std::string();
905       }
906     }
907
908     std::string TargetImpl::targetDistribution() const
909     { return rpmdb2solvAttr( "register.target", _root ); }
910
911     std::string TargetImpl::targetDistributionRelease() const
912     { return rpmdb2solvAttr( "register.release", _root ); }
913
914     ///////////////////////////////////////////////////////////////////
915
916     std::string TargetImpl::anonymousUniqueId() const
917     {
918         std::ifstream idfile( ( home() / "AnonymousUniqueId" ).c_str() );
919         for( iostr::EachLine in( idfile ); in; in.next() )
920         {
921             std::string line( str::trim( *in ) );
922             if ( ! line.empty() )
923                 return line;
924         }
925         return std::string();
926     }
927
928     ///////////////////////////////////////////////////////////////////
929
930     void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
931     {
932       // provide on local disk
933       repo::RepoMediaAccess access_r;
934       repo::SrcPackageProvider prov( access_r );
935       ManagedFile localfile = prov.provideSrcPackage( srcPackage_r );
936       // install it
937       rpm().installPackage ( localfile );
938     }
939
940     /////////////////////////////////////////////////////////////////
941   } // namespace target
942   ///////////////////////////////////////////////////////////////////
943   /////////////////////////////////////////////////////////////////
944 } // namespace zypp
945 ///////////////////////////////////////////////////////////////////