1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/target/TargetImpl.cc
19 #include <sys/types.h>
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"
30 #include "zypp/ZConfig.h"
31 #include "zypp/ZYppFactory.h"
33 #include "zypp/PoolItem.h"
34 #include "zypp/ResObjects.h"
36 #include "zypp/TmpPath.h"
37 #include "zypp/RepoStatus.h"
38 #include "zypp/ExternalProgram.h"
39 #include "zypp/Repository.h"
41 #include "zypp/ResFilters.h"
42 #include "zypp/HistoryLog.h"
43 #include "zypp/target/TargetImpl.h"
44 #include "zypp/target/TargetCallbackReceiver.h"
45 #include "zypp/target/rpm/librpmDb.h"
46 #include "zypp/target/CommitPackageCache.h"
48 #include "zypp/parser/ProductFileReader.h"
50 #include "zypp/pool/GetResolvablesToInsDel.h"
51 #include "zypp/solver/detail/Helper.h"
53 #include "zypp/repo/DeltaCandidates.h"
54 #include "zypp/repo/PackageProvider.h"
55 #include "zypp/repo/SrcPackageProvider.h"
57 #include "zypp/sat/Pool.h"
61 ///////////////////////////////////////////////////////////////////
63 { /////////////////////////////////////////////////////////////////
64 ///////////////////////////////////////////////////////////////////
66 { /////////////////////////////////////////////////////////////////
68 ///////////////////////////////////////////////////////////////////
70 { /////////////////////////////////////////////////////////////////
72 /** Execute script and report against report_r.
73 * Return \c std::pair<bool,PatchScriptReport::Action> to indicate if
74 * execution was successfull (<tt>first = true</tt>), or the desired
75 * \c PatchScriptReport::Action in case execution failed
76 * (<tt>first = false</tt>).
78 * \note The packager is responsible for setting the correct permissions
79 * of the script. If the script is not executable it is reported as an
80 * error. We must not modify the permessions.
82 std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
83 const Pathname & script_r,
84 callback::SendReport<PatchScriptReport> & report_r )
86 MIL << "Execute script " << PathInfo(script_r) << endl;
88 HistoryLog historylog;
89 historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
90 ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
92 for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
94 historylog.comment(output);
95 if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
97 WAR << "User request to abort script " << script_r << endl;
99 // the rest is handled by exit code evaluation
100 // in case the script has meanwhile finished.
104 std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
106 if ( prog.close() != 0 )
108 ret.second = report_r->problem( prog.execError() );
109 WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
110 std::ostringstream sstr;
111 sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
112 historylog.comment(sstr.str(), /*timestamp*/true);
121 /** Execute script and report against report_r.
122 * Return \c false if user requested \c ABORT.
124 bool executeScript( const Pathname & root_r,
125 const Pathname & script_r,
126 callback::SendReport<PatchScriptReport> & report_r )
128 std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
131 action = doExecuteScript( root_r, script_r, report_r );
133 return true; // success
135 switch ( action.second )
137 case PatchScriptReport::ABORT:
138 WAR << "User request to abort at script " << script_r << endl;
139 return false; // requested abort.
142 case PatchScriptReport::IGNORE:
143 WAR << "User request to skip script " << script_r << endl;
144 return true; // requested skip.
147 case PatchScriptReport::RETRY:
150 } while ( action.second == PatchScriptReport::RETRY );
152 // THIS is not intended to be reached:
153 INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
154 return false; // abort.
157 /** Look for patch scripts named 'name-version-release-*' and
158 * execute them. Return \c false if \c ABORT was requested.
160 bool RunUpdateScripts( const Pathname & root_r,
161 const Pathname & scriptsPath_r,
162 const std::vector<sat::Solvable> & checkPackages_r,
165 if ( checkPackages_r.empty() )
166 return true; // no installed packages to check
168 MIL << "Looking for new patch scripts in (" << root_r << ")" << scriptsPath_r << endl;
169 Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
170 if ( ! PathInfo( scriptsDir ).isDir() )
171 return true; // no script dir
173 std::list<std::string> scripts;
174 filesystem::readdir( scripts, scriptsDir, /*dots*/false );
175 if ( scripts.empty() )
176 return true; // no scripts in script dir
178 // Now collect and execute all matching scripts.
179 // On ABORT: at least log all outstanding scripts.
181 for_( it, checkPackages_r.begin(), checkPackages_r.end() )
183 std::string prefix( str::form( "%s-%s-", it->name().c_str(), it->edition().c_str() ) );
184 for_( sit, scripts.begin(), scripts.end() )
186 if ( ! str::hasPrefix( *sit, prefix ) )
189 PathInfo script( scriptsDir / *sit );
190 if ( ! script.isFile() )
193 if ( abort || aborting_r )
195 WAR << "Aborting: Skip patch script " << *sit << endl;
196 HistoryLog().comment(
197 script.path().asString() + _(" execution skipped while aborting"),
202 MIL << "Found patch script " << *sit << endl;
203 callback::SendReport<PatchScriptReport> report;
204 report->start( make<Package>( *it ), script.path() );
206 if ( ! executeScript( root_r, script.path(), report ) )
207 abort = true; // requested abort.
214 /////////////////////////////////////////////////////////////////
216 ///////////////////////////////////////////////////////////////////
218 /** Helper for PackageProvider queries during commit. */
219 struct QueryInstalledEditionHelper
221 bool operator()( const std::string & name_r,
222 const Edition & ed_r,
223 const Arch & arch_r ) const
225 rpm::librpmDb::db_const_iterator it;
226 for ( it.findByName( name_r ); *it; ++it )
228 if ( arch_r == it->tag_arch()
229 && ( ed_r == Edition::noedition || ed_r == it->tag_edition() ) )
239 * \short Let the Source provide the package.
240 * \p pool_r \ref ResPool used to get candidates
241 * \p pi item to be commited
243 struct RepoProvidePackage
246 repo::RepoMediaAccess &_access;
248 RepoProvidePackage( repo::RepoMediaAccess &access, ResPool pool_r )
249 : _pool(pool_r), _access(access)
254 ManagedFile operator()( const PoolItem & pi )
256 // Redirect PackageProvider queries for installed editions
257 // (in case of patch/delta rpm processing) to rpmDb.
258 repo::PackageProviderPolicy packageProviderPolicy;
259 packageProviderPolicy.queryInstalledCB( QueryInstalledEditionHelper() );
261 Package::constPtr p = asKind<Package>(pi.resolvable());
264 // Build a repository list for repos
265 // contributing to the pool
266 std::list<Repository> repos( _pool.knownRepositoriesBegin(), _pool.knownRepositoriesEnd() );
267 repo::DeltaCandidates deltas(repos, p->name());
268 repo::PackageProvider pkgProvider( _access, p, deltas, packageProviderPolicy );
269 return pkgProvider.providePackage();
272 ///////////////////////////////////////////////////////////////////
274 IMPL_PTR_TYPE(TargetImpl);
276 TargetImpl_Ptr TargetImpl::_nullimpl;
278 /** Null implementation */
279 TargetImpl_Ptr TargetImpl::nullimpl()
282 _nullimpl = new TargetImpl;
286 ///////////////////////////////////////////////////////////////////
288 // METHOD NAME : TargetImpl::TargetImpl
289 // METHOD TYPE : Ctor
291 TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
293 , _requestedLocalesFile( home() / "RequestedLocales" )
294 , _softLocksFile( home() / "SoftLocks" )
295 , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
297 _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
299 HistoryLog::setRoot(_root);
303 MIL << "Initialized target on " << _root << endl;
307 * generates a random id using uuidgen
309 static string generateRandomId()
318 ExternalProgram prog( argv,
319 ExternalProgram::Normal_Stderr,
322 for(line = prog.receiveLine();
324 line = prog.receiveLine() )
335 * updates the content of \p filename
336 * if \p condition is true, setting the content
337 * the the value returned by \p value
339 void updateFileContent( const Pathname &filename,
340 boost::function<bool ()> condition,
341 boost::function<string ()> value )
343 string val = value();
344 // if the value is empty, then just dont
345 // do anything, regardless of the condition
351 MIL << "updating '" << filename << "' content." << endl;
353 // if the file does not exist we need to generate the uuid file
355 std::ofstream filestr;
356 // make sure the path exists
357 filesystem::assert_dir( filename.dirname() );
358 filestr.open( filename.c_str() );
360 if ( filestr.good() )
367 // FIXME, should we ignore the error?
368 ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
373 /** helper functor */
374 static bool fileMissing( const Pathname &pathname )
376 return ! PathInfo(pathname).isExist();
379 void TargetImpl::createAnonymousId() const
382 // create the anonymous unique id
383 // this value is used for statistics
384 Pathname idpath( home() / "AnonymousUniqueId");
388 updateFileContent( idpath,
389 boost::bind(fileMissing, idpath),
392 catch ( const Exception &e )
394 WAR << "Can't create anonymous id file" << endl;
399 void TargetImpl::createLastDistributionFlavorCache() const
401 // create the anonymous unique id
402 // this value is used for statistics
403 Pathname flavorpath( home() / "LastDistributionFlavor");
405 // is there a product
406 Product::constPtr p = baseProduct();
409 WAR << "No base product, I won't create flavor cache" << endl;
413 string flavor = p->flavor();
418 updateFileContent( flavorpath,
419 // only if flavor is not empty
420 functor::Constant<bool>( ! flavor.empty() ),
421 functor::Constant<string>(flavor) );
423 catch ( const Exception &e )
425 WAR << "Can't create flavor cache" << endl;
430 ///////////////////////////////////////////////////////////////////
432 // METHOD NAME : TargetImpl::~TargetImpl
433 // METHOD TYPE : Dtor
435 TargetImpl::~TargetImpl()
437 _rpm.closeDatabase();
438 MIL << "Targets closed" << endl;
441 ///////////////////////////////////////////////////////////////////
443 // solv file handling
445 ///////////////////////////////////////////////////////////////////
447 Pathname TargetImpl::defaultSolvfilesPath() const
449 return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
452 void TargetImpl::clearCache()
454 Pathname base = solvfilesPath();
455 filesystem::recursive_rmdir( base );
458 void TargetImpl::buildCache()
460 Pathname base = solvfilesPath();
461 Pathname rpmsolv = base/"solv";
462 Pathname rpmsolvcookie = base/"cookie";
464 bool build_rpm_solv = true;
465 // lets see if the rpm solv cache exists
467 RepoStatus rpmstatus( RepoStatus( _root/"/var/lib/rpm/Name" )
468 && (_root/"/etc/products.d") );
470 bool solvexisted = PathInfo(rpmsolv).isExist();
473 // see the status of the cache
474 PathInfo cookie( rpmsolvcookie );
475 MIL << "Read cookie: " << cookie << endl;
476 if ( cookie.isExist() )
478 RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
479 // now compare it with the rpm database
480 if ( status.checksum() == rpmstatus.checksum() )
481 build_rpm_solv = false;
482 MIL << "Read cookie: " << rpmsolvcookie << " says: "
483 << (build_rpm_solv ? "outdated" : "uptodate") << endl;
487 if ( build_rpm_solv )
489 // if the solvfile dir does not exist yet, we better create it
490 filesystem::assert_dir( base );
492 Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
494 filesystem::TmpFile tmpsolv( filesystem::TmpFile::makeSibling( rpmsolv ) );
497 // Can't create temporary solv file, usually due to insufficient permission
498 // (user query while @System solv needs refresh). If so, try switching
499 // to a location within zypps temp. space (will be cleaned at application end).
501 bool switchingToTmpSolvfile = false;
502 Exception ex("Failed to cache rpm database.");
503 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
505 if ( ! solvfilesPathIsTemp() )
507 base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
508 rpmsolv = base/"solv";
509 rpmsolvcookie = base/"cookie";
511 filesystem::assert_dir( base );
512 tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
516 WAR << "Using a temporary solv file at " << base << endl;
517 switchingToTmpSolvfile = true;
518 _tmpSolvfilesPath = base;
522 ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
526 if ( ! switchingToTmpSolvfile )
532 // Take care we unlink the solvfile on exception
533 ManagedFile guard( base, filesystem::recursive_rmdir );
535 std::ostringstream cmd;
537 if ( ! _root.empty() )
538 cmd << " -r '" << _root << "'";
540 cmd << " -p '" << Pathname::assertprefix( _root, "/etc/products.d" ) << "'";
542 if ( ! oldSolvFile.empty() )
543 cmd << " '" << oldSolvFile << "'";
545 cmd << " > '" << tmpsolv.path() << "'";
547 MIL << "Executing: " << cmd << endl;
548 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
551 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
552 WAR << " " << output;
553 cmd << " " << output;
556 int ret = prog.close();
559 Exception ex(str::form("Failed to cache rpm database (%d).", ret));
560 ex.remember( cmd.str() );
564 ret = filesystem::rename( tmpsolv, rpmsolv );
566 ZYPP_THROW(Exception("Failed to move cache to final destination"));
567 // if this fails, don't bother throwing exceptions
568 filesystem::chmod( rpmsolv, 0644 );
570 rpmstatus.saveToCookieFile(rpmsolvcookie);
573 guard.resetDispose();
577 void TargetImpl::unload()
579 Repository system( sat::Pool::instance().findSystemRepo() );
581 system.eraseFromPool();
585 void TargetImpl::load()
589 // now add the repos to the pool
590 sat::Pool satpool( sat::Pool::instance() );
591 Pathname rpmsolv( solvfilesPath() / "solv" );
592 MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
594 // Providing an empty system repo, unload any old content
595 Repository system( sat::Pool::instance().findSystemRepo() );
596 if ( system && ! system.solvablesEmpty() )
598 system.eraseFromPool(); // invalidates system
602 system = satpool.systemRepo();
607 system.addSolv( rpmsolv );
609 catch ( const Exception & exp )
612 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
616 system.addSolv( rpmsolv );
619 // (Re)Load the requested locales et al.
620 // If the requested locales are empty, we leave the pool untouched
621 // to avoid undoing changes the application applied. We expect this
622 // to happen on a bare metal installation only. An already existing
623 // target should be loaded before its settings are changed.
625 const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
626 if ( ! requestedLocales.empty() )
628 satpool.setRequestedLocales( requestedLocales );
632 SoftLocksFile::Data softLocks( _softLocksFile.data() );
633 if ( ! softLocks.empty() )
635 // Don't soft lock any installed item.
636 for_( it, system.solvablesBegin(), system.solvablesEnd() )
638 softLocks.erase( it->ident() );
640 ResPool::instance().setAutoSoftLocks( softLocks );
643 if ( ZConfig::instance().apply_locks_file() )
645 const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
646 if ( ! hardLocks.empty() )
648 ResPool::instance().setHardLockQueries( hardLocks );
652 // now that the target is loaded, we can cache the flavor
653 createLastDistributionFlavorCache();
655 MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
658 ///////////////////////////////////////////////////////////////////
662 ///////////////////////////////////////////////////////////////////
663 ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
665 // ----------------------------------------------------------------- //
666 // Fake outstanding YCP fix: Honour restriction to media 1
667 // at installation, but install all remaining packages if post-boot.
668 ZYppCommitPolicy policy_r( policy_rX );
669 if ( policy_r.restrictToMedia() > 1 )
671 // ----------------------------------------------------------------- //
673 MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
675 ///////////////////////////////////////////////////////////////////
676 // Store non-package data:
677 ///////////////////////////////////////////////////////////////////
678 filesystem::assert_dir( home() );
680 _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
683 SoftLocksFile::Data newdata;
684 pool_r.getActiveSoftLocks( newdata );
685 _softLocksFile.setData( newdata );
688 if ( ZConfig::instance().apply_locks_file() )
690 HardLocksFile::Data newdata;
691 pool_r.getHardLockQueries( newdata );
692 _hardLocksFile.setData( newdata );
695 ///////////////////////////////////////////////////////////////////
697 ///////////////////////////////////////////////////////////////////
699 DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
701 ZYppCommitResult result;
703 TargetImpl::PoolItemList to_uninstall;
704 TargetImpl::PoolItemList to_install;
705 TargetImpl::PoolItemList to_srcinstall;
708 pool::GetResolvablesToInsDel
709 collect( pool_r, policy_r.restrictToMedia() ? pool::GetResolvablesToInsDel::ORDER_BY_MEDIANR
710 : pool::GetResolvablesToInsDel::ORDER_BY_SOURCE );
711 MIL << "GetResolvablesToInsDel: " << endl << collect << endl;
712 to_uninstall.swap( collect._toDelete );
713 to_install.swap( collect._toInstall );
714 to_srcinstall.swap( collect._toSrcinstall );
717 if ( policy_r.restrictToMedia() )
719 MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
722 ///////////////////////////////////////////////////////////////////
723 // First collect and display all messages
724 // associated with patches to be installed.
725 ///////////////////////////////////////////////////////////////////
726 for_( it, to_install.begin(), to_install.end() )
728 if ( ! isKind<Patch>(it->resolvable()) )
730 if ( ! it->status().isToBeInstalled() )
733 Patch::constPtr patch( asKind<Patch>(it->resolvable()) );
734 if ( ! patch->message().empty() )
736 MIL << "Show message for " << patch << endl;
737 callback::SendReport<target::PatchMessageReport> report;
738 if ( ! report->show( patch ) )
740 WAR << "commit aborted by the user" << endl;
741 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
746 ///////////////////////////////////////////////////////////////////
747 // Remove/install packages.
748 ///////////////////////////////////////////////////////////////////
749 commit ( to_uninstall, policy_r, pool_r );
751 if (policy_r.restrictToMedia() == 0)
753 result._remaining = commit( to_install, policy_r, pool_r );
754 result._srcremaining = commit( to_srcinstall, policy_r, pool_r );
758 TargetImpl::PoolItemList current_install;
759 TargetImpl::PoolItemList current_srcinstall;
761 // Collect until the 1st package from an unwanted media occurs.
762 // Further collection could violate install order.
763 bool hitUnwantedMedia = false;
764 for (TargetImpl::PoolItemList::iterator it = to_install.begin(); it != to_install.end(); ++it)
766 ResObject::constPtr res( it->resolvable() );
768 if ( hitUnwantedMedia
769 || ( res->mediaNr() && res->mediaNr() != policy_r.restrictToMedia() ) )
771 hitUnwantedMedia = true;
772 result._remaining.push_back( *it );
776 current_install.push_back( *it );
780 TargetImpl::PoolItemList bad = commit( current_install, policy_r, pool_r );
781 result._remaining.insert(result._remaining.end(), bad.begin(), bad.end());
783 for (TargetImpl::PoolItemList::iterator it = to_srcinstall.begin(); it != to_srcinstall.end(); ++it)
785 Resolvable::constPtr res( it->resolvable() );
786 Package::constPtr pkg( asKind<Package>(res) );
787 if (pkg && policy_r.restrictToMedia() != pkg->mediaNr()) // check medianr for packages only
789 XXX << "Package " << *pkg << ", wrong media " << pkg->mediaNr() << endl;
790 result._srcremaining.push_back( *it );
794 current_srcinstall.push_back( *it );
797 bad = commit( current_srcinstall, policy_r, pool_r );
798 result._srcremaining.insert(result._srcremaining.end(), bad.begin(), bad.end());
801 ///////////////////////////////////////////////////////////////////
802 // Try to rebuild solv file while rpm database is still in cache.
803 ///////////////////////////////////////////////////////////////////
806 result._result = (to_install.size() - result._remaining.size());
807 MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
812 ///////////////////////////////////////////////////////////////////
816 ///////////////////////////////////////////////////////////////////
817 TargetImpl::PoolItemList
818 TargetImpl::commit( const TargetImpl::PoolItemList & items_r,
819 const ZYppCommitPolicy & policy_r,
820 const ResPool & pool_r )
822 TargetImpl::PoolItemList remaining;
823 repo::RepoMediaAccess access;
824 MIL << "TargetImpl::commit(<list>" << policy_r << ")" << items_r.size() << endl;
827 std::vector<sat::Solvable> successfullyInstalledPackages;
829 // prepare the package cache.
830 RepoProvidePackage repoProvidePackage( access, pool_r );
831 CommitPackageCache packageCache( items_r.begin(), items_r.end(),
832 root() / "tmp", repoProvidePackage );
834 for ( TargetImpl::PoolItemList::const_iterator it = items_r.begin(); it != items_r.end(); it++ )
836 if ( (*it)->isKind<Package>() )
838 Package::constPtr p = (*it)->asKind<Package>();
839 if (it->status().isToBeInstalled())
841 ManagedFile localfile;
844 localfile = packageCache.get( it );
846 catch ( const AbortRequestException &e )
848 WAR << "commit aborted by the user" << endl;
852 catch ( const SkipRequestException &e )
855 WAR << "Skipping package " << p << " in commit" << endl;
858 catch ( const Exception &e )
860 // bnc #395704: missing catch causes abort.
861 // TODO see if packageCache fails to handle errors correctly.
863 INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
867 #warning Exception handling
868 // create a installation progress report proxy
869 RpmInstallPackageReceiver progress( it->resolvable() );
870 progress.connect(); // disconnected on destruction.
872 bool success = false;
873 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
874 // Why force and nodeps?
876 // Because zypp builds the transaction and the resolver asserts that
877 // everything is fine.
878 // We use rpm just to unpack and register the package in the database.
879 // We do this step by step, so rpm is not aware of the bigger context.
880 // So we turn off rpms internal checks, because we do it inside zypp.
881 flags |= rpm::RPMINST_NODEPS;
882 flags |= rpm::RPMINST_FORCE;
884 if (p->installOnly()) flags |= rpm::RPMINST_NOUPGRADE;
885 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
886 if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
887 if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
891 progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
892 rpm().installPackage( localfile, flags );
893 HistoryLog().install(*it);
895 if ( progress.aborted() )
897 WAR << "commit aborted by the user" << endl;
906 catch ( Exception & excpt_r )
908 ZYPP_CAUGHT(excpt_r);
909 if ( policy_r.dryRun() )
911 WAR << "dry run failed" << endl;
915 if ( progress.aborted() )
917 WAR << "commit aborted by the user" << endl;
922 WAR << "Install failed" << endl;
924 remaining.push_back( *it );
928 if ( success && !policy_r.dryRun() )
930 it->status().resetTransact( ResStatus::USER );
931 // Remember to check this package for presence of patch scripts.
932 successfullyInstalledPackages.push_back( it->satSolvable() );
937 RpmRemovePackageReceiver progress( it->resolvable() );
938 progress.connect(); // disconnected on destruction.
940 bool success = false;
941 rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
942 flags |= rpm::RPMINST_NODEPS;
943 if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
946 rpm().removePackage( p, flags );
947 HistoryLog().remove(*it);
949 if ( progress.aborted() )
951 WAR << "commit aborted by the user" << endl;
960 catch (Exception & excpt_r)
962 ZYPP_CAUGHT( excpt_r );
963 if ( progress.aborted() )
965 WAR << "commit aborted by the user" << endl;
970 WAR << "removal of " << p << " failed";
972 if ( success && !policy_r.dryRun() )
974 it->status().resetTransact( ResStatus::USER );
978 else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
980 // Status is changed as the buddy package buddy
981 // gets installed/deleted. Handle non-buddies only.
984 if ( (*it)->isKind<Product>() )
986 Product::constPtr p = (*it)->asKind<Product>();
987 if ( it->status().isToBeInstalled() )
989 ERR << "Can't install orphan product without release-package! " << (*it) << endl;
993 // Deleting the corresponding product entry is all we con do.
994 // So the product will no longer be visible as installed.
995 std::string referenceFilename( p->referenceFilename() );
996 if ( referenceFilename.empty() )
998 ERR << "Can't remove orphan product without 'referenceFilename'! " << (*it) << endl;
1002 PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1003 if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1005 ERR << "Delete orphan product failed: " << referenceFile << endl;
1010 else if ( (*it)->isKind<SrcPackage>() && it->status().isToBeInstalled() )
1012 // SrcPackage is install-only
1013 SrcPackage::constPtr p = (*it)->asKind<SrcPackage>();
1014 installSrcPackage( p );
1017 it->status().resetTransact( ResStatus::USER );
1019 } // other resolvables
1023 // Check presence of patch scripts. If aborting, at least log
1025 if ( ! successfullyInstalledPackages.empty() )
1027 if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1028 successfullyInstalledPackages, abort ) )
1030 WAR << "Commit aborted by the user" << endl;
1037 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1043 rpm::RpmDb & TargetImpl::rpm()
1048 bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1050 return _rpm.hasFile(path_str, name_str);
1054 Date TargetImpl::timestamp() const
1056 return _rpm.timestamp();
1059 ///////////////////////////////////////////////////////////////////
1061 Product::constPtr TargetImpl::baseProduct() const
1063 ResPool pool(ResPool::instance());
1064 for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1066 Product::constPtr p = (*it)->asKind<Product>();
1067 if ( p->isTargetDistribution() )
1075 parser::ProductFileData baseproductdata( const Pathname & root_r )
1077 PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1078 if ( baseproduct.isFile() )
1082 return parser::ProductFileReader::scanFile( baseproduct.path() );
1084 catch ( const Exception & excpt )
1086 ZYPP_CAUGHT( excpt );
1089 return parser::ProductFileData();
1094 std::string TargetImpl::targetDistribution() const
1095 { return baseproductdata( _root ).registerTarget(); }
1097 std::string TargetImpl::targetDistributionRelease() const
1098 { return baseproductdata( _root ).registerRelease(); }
1100 std::string TargetImpl::distributionVersion() const
1102 if ( _distributionVersion.empty() )
1104 // By default ZYpp looks for /etc/product.d/baseproduct..
1105 //_distributionVersion = baseproductdata( _root ).edition().version();
1107 if ( _distributionVersion.empty() )
1109 // ...But the baseproduct method is not expected to work on RedHat derivatives.
1110 // On RHEL, Fedora and others the "product version" is determined by the first package
1111 // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1112 // with the $distroverpkg variable.
1113 rpm::librpmDb::db_const_iterator it;
1114 if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1115 _distributionVersion = it->tag_version();
1118 if ( !_distributionVersion.empty() )
1119 MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1121 return _distributionVersion;
1124 std::string TargetImpl::distributionFlavor() const
1126 std::ifstream idfile( ( home() / "LastDistributionFlavor" ).c_str() );
1127 for( iostr::EachLine in( idfile ); in; in.next() )
1129 std::string line( str::trim( *in ) );
1130 if ( ! line.empty() )
1133 return std::string();
1136 ///////////////////////////////////////////////////////////////////
1138 std::string TargetImpl::anonymousUniqueId() const
1140 std::ifstream idfile( ( home() / "AnonymousUniqueId" ).c_str() );
1141 for( iostr::EachLine in( idfile ); in; in.next() )
1143 std::string line( str::trim( *in ) );
1144 if ( ! line.empty() )
1147 return std::string();
1150 ///////////////////////////////////////////////////////////////////
1152 void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1154 // provide on local disk
1155 repo::RepoMediaAccess access_r;
1156 repo::SrcPackageProvider prov( access_r );
1157 ManagedFile localfile = prov.provideSrcPackage( srcPackage_r );
1159 rpm().installPackage ( localfile );
1162 /////////////////////////////////////////////////////////////////
1163 } // namespace target
1164 ///////////////////////////////////////////////////////////////////
1165 /////////////////////////////////////////////////////////////////
1167 ///////////////////////////////////////////////////////////////////