libzypp  11.13.5
TargetImpl.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
12 #include <iostream>
13 #include <fstream>
14 #include <sstream>
15 #include <string>
16 #include <list>
17 #include <set>
18 
19 #include <sys/types.h>
20 #include <dirent.h>
21 
22 #include "zypp/base/LogTools.h"
23 #include "zypp/base/Exception.h"
24 #include "zypp/base/Iterator.h"
25 #include "zypp/base/Gettext.h"
26 #include "zypp/base/IOStream.h"
27 #include "zypp/base/Functional.h"
29 
30 #include "zypp/ZConfig.h"
31 #include "zypp/ZYppFactory.h"
32 
33 #include "zypp/PoolItem.h"
34 #include "zypp/ResObjects.h"
35 #include "zypp/Url.h"
36 #include "zypp/TmpPath.h"
37 #include "zypp/RepoStatus.h"
38 #include "zypp/ExternalProgram.h"
39 #include "zypp/Repository.h"
40 
41 #include "zypp/ResFilters.h"
42 #include "zypp/HistoryLog.h"
43 #include "zypp/target/TargetImpl.h"
47 
49 
52 
56 
57 #include "zypp/sat/Pool.h"
58 #include "zypp/sat/Transaction.h"
59 
60 #include "zypp/PluginScript.h"
61 
62 using namespace std;
63 
65 namespace zypp
66 {
67 
68  namespace target
69  {
70 
75  {
76  public:
77 
78  public:
81  {}
82 
85  {
86  for_( it, _scripts.begin(), _scripts.end() )
87  {
88  MIL << "Unload plugin: " << *it << endl;
89  try {
90  it->send( PluginFrame( "PLUGINEND" ) );
91  PluginFrame ret( it->receive() );
92  if ( ! ret.isAckCommand() )
93  {
94  WAR << "Failed to unload plugin: Bad plugin response." << endl;
95  }
96  it->close();
97  }
98  catch( const zypp::Exception & )
99  {
100  WAR << "Failed to unload plugin." << endl;
101  }
102  }
103  // _scripts dtor will disconnect all remaining plugins!
104  }
105 
112  void load( const Pathname & path_r )
113  {
114  PathInfo pi( path_r );
115  if ( pi.isDir() )
116  {
117  std::list<Pathname> entries;
118  if ( filesystem::readdir( entries, pi.path(), false ) != 0 )
119  {
120  WAR << "Plugin dir is not readable: " << pi << endl;
121  return;
122  }
123  for_( it, entries.begin(), entries.end() )
124  {
125  PathInfo pii( *it );
126  if ( pii.isFile() && pii.userMayRX() )
127  doLoad( pii );
128  }
129  }
130  else if ( pi.isFile() )
131  {
132  if ( pi.userMayRX() )
133  doLoad( pi );
134  else
135  WAR << "Plugin file is not executable: " << pi << endl;
136  }
137  else
138  {
139  WAR << "Plugin path is neither dir nor file: " << pi << endl;
140  }
141  }
142 
143  private:
144  void doLoad( const PathInfo & pi_r )
145  {
146  MIL << "Load plugin: " << pi_r << endl;
147  try {
148  PluginScript plugin( pi_r.path() );
149  plugin.open();
150  plugin.send( PluginFrame( "PLUGINBEGIN" ) );
151  PluginFrame ret( plugin.receive() );
152  if ( ret.isAckCommand() )
153  {
154  _scripts.push_back( plugin );
155  }
156  else
157  {
158  WAR << "Failed to load plugin: Bad plugin response." << endl;
159  }
160  }
161  catch( const zypp::Exception & )
162  {
163  WAR << "Failed to load plugin." << endl;
164  }
165  }
166 
167  private:
168  std::list<PluginScript> _scripts;
169  };
170 
171  void testCommitPlugins( const Pathname & path_r ) // for testing only
172  {
173  USR << "+++++" << endl;
174  {
175  CommitPlugins pl;
176  pl.load( path_r );
177  USR << "=====" << endl;
178  }
179  USR << "-----" << endl;
180  }
181 
183 
186  {
187  unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
188  MIL << "Testcases to keep: " << toKeep << endl;
189  if ( !toKeep )
190  return;
191  Target_Ptr target( getZYpp()->getTarget() );
192  if ( ! target )
193  {
194  WAR << "No Target no Testcase!" << endl;
195  return;
196  }
197 
198  std::string stem( "updateTestcase" );
199  Pathname dir( target->assertRootPrefix("/var/log/") );
200  Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
201 
202  {
203  std::list<std::string> content;
204  filesystem::readdir( content, dir, /*dots*/false );
205  std::set<std::string> cases;
206  for_( c, content.begin(), content.end() )
207  {
208  if ( str::startsWith( *c, stem ) )
209  cases.insert( *c );
210  }
211  if ( cases.size() >= toKeep )
212  {
213  unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
214  for_( c, cases.begin(), cases.end() )
215  {
216  filesystem::recursive_rmdir( dir/(*c) );
217  if ( ! --toDel )
218  break;
219  }
220  }
221  }
222 
223  MIL << "Write new testcase " << next << endl;
224  getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
225  }
226 
228  namespace
229  {
230 
241  std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
242  const Pathname & script_r,
244  {
245  MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
246 
247  HistoryLog historylog;
248  historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
249  ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
250 
251  for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
252  {
253  historylog.comment(output);
254  if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
255  {
256  WAR << "User request to abort script " << script_r << endl;
257  prog.kill();
258  // the rest is handled by exit code evaluation
259  // in case the script has meanwhile finished.
260  }
261  }
262 
263  std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
264 
265  if ( prog.close() != 0 )
266  {
267  ret.second = report_r->problem( prog.execError() );
268  WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
269  std::ostringstream sstr;
270  sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
271  historylog.comment(sstr.str(), /*timestamp*/true);
272  return ret;
273  }
274 
275  report_r->finish();
276  ret.first = true;
277  return ret;
278  }
279 
283  bool executeScript( const Pathname & root_r,
284  const Pathname & script_r,
285  callback::SendReport<PatchScriptReport> & report_r )
286  {
287  std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
288 
289  do {
290  action = doExecuteScript( root_r, script_r, report_r );
291  if ( action.first )
292  return true; // success
293 
294  switch ( action.second )
295  {
296  case PatchScriptReport::ABORT:
297  WAR << "User request to abort at script " << script_r << endl;
298  return false; // requested abort.
299  break;
300 
301  case PatchScriptReport::IGNORE:
302  WAR << "User request to skip script " << script_r << endl;
303  return true; // requested skip.
304  break;
305 
306  case PatchScriptReport::RETRY:
307  break; // again
308  }
309  } while ( action.second == PatchScriptReport::RETRY );
310 
311  // THIS is not intended to be reached:
312  INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
313  return false; // abort.
314  }
315 
321  bool RunUpdateScripts( const Pathname & root_r,
322  const Pathname & scriptsPath_r,
323  const std::vector<sat::Solvable> & checkPackages_r,
324  bool aborting_r )
325  {
326  if ( checkPackages_r.empty() )
327  return true; // no installed packages to check
328 
329  MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
330  Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
331  if ( ! PathInfo( scriptsDir ).isDir() )
332  return true; // no script dir
333 
334  std::list<std::string> scripts;
335  filesystem::readdir( scripts, scriptsDir, /*dots*/false );
336  if ( scripts.empty() )
337  return true; // no scripts in script dir
338 
339  // Now collect and execute all matching scripts.
340  // On ABORT: at least log all outstanding scripts.
341  // - "name-version-release"
342  // - "name-version-release-*"
343  bool abort = false;
344  for_( it, checkPackages_r.begin(), checkPackages_r.end() )
345  {
346  std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
347  for_( sit, scripts.begin(), scripts.end() )
348  {
349  if ( ! str::hasPrefix( *sit, prefix ) )
350  continue;
351 
352  if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
353  continue; // if not exact match it had to continue with '-'
354 
355  PathInfo script( scriptsDir / *sit );
356  if ( ! script.isFile() )
357  continue;
358 
359  // Assert it's set executable
360  filesystem::addmod( script.path(), 0500 );
361 
362  Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
363  if ( abort || aborting_r )
364  {
365  WAR << "Aborting: Skip update script " << *sit << endl;
366  HistoryLog().comment(
367  localPath.asString() + _(" execution skipped while aborting"),
368  /*timestamp*/true);
369  }
370  else
371  {
372  MIL << "Found update script " << *sit << endl;
373  callback::SendReport<PatchScriptReport> report;
374  report->start( make<Package>( *it ), script.path() );
375 
376  if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
377  abort = true; // requested abort.
378  }
379  }
380  }
381  return !abort;
382  }
383 
385  //
387 
388  inline void copyTo( std::ostream & out_r, const Pathname & file_r )
389  {
390  std::ifstream infile( file_r.c_str() );
391  for( iostr::EachLine in( infile ); in; in.next() )
392  {
393  out_r << *in << endl;
394  }
395  }
396 
397  inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
398  {
399  std::string ret( cmd_r );
400 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
401  SUBST_IF( "%p", notification_r.solvable().asString() );
402  SUBST_IF( "%P", notification_r.file().asString() );
403 #undef SUBST_IF
404  return ret;
405  }
406 
407  void sendNotification( const Pathname & root_r,
408  const UpdateNotifications & notifications_r )
409  {
410  if ( notifications_r.empty() )
411  return;
412 
413  std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
414  MIL << "Notification command is '" << cmdspec << "'" << endl;
415  if ( cmdspec.empty() )
416  return;
417 
418  std::string::size_type pos( cmdspec.find( '|' ) );
419  if ( pos == std::string::npos )
420  {
421  ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
422  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
423  return;
424  }
425 
426  std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
427  std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
428 
429  enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
430  Format format = UNKNOWN;
431  if ( formatStr == "none" )
432  format = NONE;
433  else if ( formatStr == "single" )
434  format = SINGLE;
435  else if ( formatStr == "digest" )
436  format = DIGEST;
437  else if ( formatStr == "bulk" )
438  format = BULK;
439  else
440  {
441  ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
442  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
443  return;
444  }
445 
446  // Take care: commands are ececuted chroot(root_r). The message file
447  // pathnames in notifications_r are local to root_r. For physical access
448  // to the file they need to be prefixed.
449 
450  if ( format == NONE || format == SINGLE )
451  {
452  for_( it, notifications_r.begin(), notifications_r.end() )
453  {
454  std::vector<std::string> command;
455  if ( format == SINGLE )
456  command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
457  str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
458 
459  ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
460  if ( true ) // Wait for feedback
461  {
462  for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
463  {
464  DBG << line;
465  }
466  int ret = prog.close();
467  if ( ret != 0 )
468  {
469  ERR << "Notification command returned with error (" << ret << ")." << endl;
470  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
471  return;
472  }
473  }
474  }
475  }
476  else if ( format == DIGEST || format == BULK )
477  {
478  filesystem::TmpFile tmpfile;
479  ofstream out( tmpfile.path().c_str() );
480  for_( it, notifications_r.begin(), notifications_r.end() )
481  {
482  if ( format == DIGEST )
483  {
484  out << it->file() << endl;
485  }
486  else if ( format == BULK )
487  {
488  copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
489  }
490  }
491 
492  std::vector<std::string> command;
493  command.push_back( "<"+tmpfile.path().asString() ); // redirect input
494  str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
495 
496  ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
497  if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
498  {
499  for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
500  {
501  DBG << line;
502  }
503  int ret = prog.close();
504  if ( ret != 0 )
505  {
506  ERR << "Notification command returned with error (" << ret << ")." << endl;
507  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
508  return;
509  }
510  }
511  }
512  else
513  {
514  INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
515  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
516  return;
517  }
518  }
519 
520 
526  void RunUpdateMessages( const Pathname & root_r,
527  const Pathname & messagesPath_r,
528  const std::vector<sat::Solvable> & checkPackages_r,
529  ZYppCommitResult & result_r )
530  {
531  if ( checkPackages_r.empty() )
532  return; // no installed packages to check
533 
534  MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
535  Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
536  if ( ! PathInfo( messagesDir ).isDir() )
537  return; // no messages dir
538 
539  std::list<std::string> messages;
540  filesystem::readdir( messages, messagesDir, /*dots*/false );
541  if ( messages.empty() )
542  return; // no messages in message dir
543 
544  // Now collect all matching messages in result and send them
545  // - "name-version-release"
546  // - "name-version-release-*"
547  HistoryLog historylog;
548  for_( it, checkPackages_r.begin(), checkPackages_r.end() )
549  {
550  std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
551  for_( sit, messages.begin(), messages.end() )
552  {
553  if ( ! str::hasPrefix( *sit, prefix ) )
554  continue;
555 
556  if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
557  continue; // if not exact match it had to continue with '-'
558 
559  PathInfo message( messagesDir / *sit );
560  if ( ! message.isFile() || message.size() == 0 )
561  continue;
562 
563  MIL << "Found update message " << *sit << endl;
564  Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
565  result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
566  historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
567  }
568  }
569  sendNotification( root_r, result_r.updateMessages() );
570  }
571 
573  } // namespace
575 
576  void XRunUpdateMessages( const Pathname & root_r,
577  const Pathname & messagesPath_r,
578  const std::vector<sat::Solvable> & checkPackages_r,
579  ZYppCommitResult & result_r )
580  { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
581 
584  {
585  bool operator()( const std::string & name_r,
586  const Edition & ed_r,
587  const Arch & arch_r ) const
588  {
590  for ( it.findByName( name_r ); *it; ++it )
591  {
592  if ( arch_r == it->tag_arch()
593  && ( ed_r == Edition::noedition || ed_r == it->tag_edition() ) )
594  {
595  return true;
596  }
597  }
598  return false;
599  }
600  };
601 
608  {
611 
613  : _pool(pool_r), _access(access)
614  {}
615 
616  ManagedFile operator()( const PoolItem & pi )
617  {
618  // Redirect PackageProvider queries for installed editions
619  // (in case of patch/delta rpm processing) to rpmDb.
620  repo::PackageProviderPolicy packageProviderPolicy;
621  packageProviderPolicy.queryInstalledCB( QueryInstalledEditionHelper() );
622 
623  Package::constPtr p = asKind<Package>(pi.resolvable());
624 
625  // Build a repository list for repos
626  // contributing to the pool
627  std::list<Repository> repos( _pool.knownRepositoriesBegin(), _pool.knownRepositoriesEnd() );
628  repo::DeltaCandidates deltas(repos, p->name());
629  repo::PackageProvider pkgProvider( _access, p, deltas, packageProviderPolicy );
630 
631  ManagedFile ret( pkgProvider.providePackage() );
632  return ret;
633  }
634  };
636 
637  IMPL_PTR_TYPE(TargetImpl);
638 
639  TargetImpl_Ptr TargetImpl::_nullimpl;
640 
642  TargetImpl_Ptr TargetImpl::nullimpl()
643  {
644  if (_nullimpl == 0)
645  _nullimpl = new TargetImpl;
646  return _nullimpl;
647  }
648 
650  //
651  // METHOD NAME : TargetImpl::TargetImpl
652  // METHOD TYPE : Ctor
653  //
654  TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
655  : _root( root_r )
656  , _requestedLocalesFile( home() / "RequestedLocales" )
657  , _softLocksFile( home() / "SoftLocks" )
658  , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
659  {
660  _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
661 
663 
665 
666  MIL << "Initialized target on " << _root << endl;
667  }
668 
672  static std::string generateRandomId()
673  {
674  std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
675  return iostr::getline( uuidprovider );
676  }
677 
683  void updateFileContent( const Pathname &filename,
684  boost::function<bool ()> condition,
685  boost::function<string ()> value )
686  {
687  string val = value();
688  // if the value is empty, then just dont
689  // do anything, regardless of the condition
690  if ( val.empty() )
691  return;
692 
693  if ( condition() )
694  {
695  MIL << "updating '" << filename << "' content." << endl;
696 
697  // if the file does not exist we need to generate the uuid file
698 
699  std::ofstream filestr;
700  // make sure the path exists
701  filesystem::assert_dir( filename.dirname() );
702  filestr.open( filename.c_str() );
703 
704  if ( filestr.good() )
705  {
706  filestr << val;
707  filestr.close();
708  }
709  else
710  {
711  // FIXME, should we ignore the error?
712  ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
713  }
714  }
715  }
716 
718  static bool fileMissing( const Pathname &pathname )
719  {
720  return ! PathInfo(pathname).isExist();
721  }
722 
724  {
725 
726  // create the anonymous unique id
727  // this value is used for statistics
728  Pathname idpath( home() / "AnonymousUniqueId");
729 
730  try
731  {
732  updateFileContent( idpath,
733  boost::bind(fileMissing, idpath),
735  }
736  catch ( const Exception &e )
737  {
738  WAR << "Can't create anonymous id file" << endl;
739  }
740 
741  }
742 
744  {
745  // create the anonymous unique id
746  // this value is used for statistics
747  Pathname flavorpath( home() / "LastDistributionFlavor");
748 
749  // is there a product
751  if ( ! p )
752  {
753  WAR << "No base product, I won't create flavor cache" << endl;
754  return;
755  }
756 
757  string flavor = p->flavor();
758 
759  try
760  {
761 
762  updateFileContent( flavorpath,
763  // only if flavor is not empty
764  functor::Constant<bool>( ! flavor.empty() ),
765  functor::Constant<string>(flavor) );
766  }
767  catch ( const Exception &e )
768  {
769  WAR << "Can't create flavor cache" << endl;
770  return;
771  }
772  }
773 
775  //
776  // METHOD NAME : TargetImpl::~TargetImpl
777  // METHOD TYPE : Dtor
778  //
780  {
782  MIL << "Targets closed" << endl;
783  }
784 
786  //
787  // solv file handling
788  //
790 
792  {
793  return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
794  }
795 
797  {
798  Pathname base = solvfilesPath();
800  }
801 
803  {
804  Pathname base = solvfilesPath();
805  Pathname rpmsolv = base/"solv";
806  Pathname rpmsolvcookie = base/"cookie";
807 
808  bool build_rpm_solv = true;
809  // lets see if the rpm solv cache exists
810 
811  RepoStatus rpmstatus( RepoStatus( _root/"/var/lib/rpm/Name" )
812  && (_root/"/etc/products.d") );
813 
814  bool solvexisted = PathInfo(rpmsolv).isExist();
815  if ( solvexisted )
816  {
817  // see the status of the cache
818  PathInfo cookie( rpmsolvcookie );
819  MIL << "Read cookie: " << cookie << endl;
820  if ( cookie.isExist() )
821  {
822  RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
823  // now compare it with the rpm database
824  if ( status.checksum() == rpmstatus.checksum() )
825  build_rpm_solv = false;
826  MIL << "Read cookie: " << rpmsolvcookie << " says: "
827  << (build_rpm_solv ? "outdated" : "uptodate") << endl;
828  }
829  }
830 
831  if ( build_rpm_solv )
832  {
833  // if the solvfile dir does not exist yet, we better create it
834  filesystem::assert_dir( base );
835 
836  Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
837 
839  if ( !tmpsolv )
840  {
841  // Can't create temporary solv file, usually due to insufficient permission
842  // (user query while @System solv needs refresh). If so, try switching
843  // to a location within zypps temp. space (will be cleaned at application end).
844 
845  bool switchingToTmpSolvfile = false;
846  Exception ex("Failed to cache rpm database.");
847  ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
848 
849  if ( ! solvfilesPathIsTemp() )
850  {
851  base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
852  rpmsolv = base/"solv";
853  rpmsolvcookie = base/"cookie";
854 
855  filesystem::assert_dir( base );
856  tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
857 
858  if ( tmpsolv )
859  {
860  WAR << "Using a temporary solv file at " << base << endl;
861  switchingToTmpSolvfile = true;
862  _tmpSolvfilesPath = base;
863  }
864  else
865  {
866  ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
867  }
868  }
869 
870  if ( ! switchingToTmpSolvfile )
871  {
872  ZYPP_THROW(ex);
873  }
874  }
875 
876  // Take care we unlink the solvfile on exception
878 
879  std::ostringstream cmd;
880  cmd << "rpmdb2solv";
881  if ( ! _root.empty() )
882  cmd << " -r '" << _root << "'";
883 
884  cmd << " -p '" << Pathname::assertprefix( _root, "/etc/products.d" ) << "'";
885 
886  if ( ! oldSolvFile.empty() )
887  cmd << " '" << oldSolvFile << "'";
888 
889  cmd << " > '" << tmpsolv.path() << "'";
890 
891  MIL << "Executing: " << cmd << endl;
893 
894  cmd << endl;
895  for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
896  WAR << " " << output;
897  cmd << " " << output;
898  }
899 
900  int ret = prog.close();
901  if ( ret != 0 )
902  {
903  Exception ex(str::form("Failed to cache rpm database (%d).", ret));
904  ex.remember( cmd.str() );
905  ZYPP_THROW(ex);
906  }
907 
908  ret = filesystem::rename( tmpsolv, rpmsolv );
909  if ( ret != 0 )
910  ZYPP_THROW(Exception("Failed to move cache to final destination"));
911  // if this fails, don't bother throwing exceptions
912  filesystem::chmod( rpmsolv, 0644 );
913 
914  rpmstatus.saveToCookieFile(rpmsolvcookie);
915 
916  // We keep it.
917  guard.resetDispose();
918 
919  // Finally send notification to plugins
920  // NOTE: quick hack looking for spacewalk plugin only
921  {
922  Pathname script( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"system/spacewalk" ) );
923  if ( PathInfo( script ).isX() )
924  try {
925  PluginScript spacewalk( script );
926  spacewalk.open();
927 
928  PluginFrame notify( "PACKAGESETCHANGED" );
929  spacewalk.send( notify );
930 
931  PluginFrame ret( spacewalk.receive() );
932  MIL << ret << endl;
933  if ( ret.command() == "ERROR" )
934  ret.writeTo( WAR ) << endl;
935  }
936  catch ( const Exception & excpt )
937  {
938  WAR << excpt.asUserHistory() << endl;
939  }
940  }
941  }
942  }
943 
945  {
946  Repository system( sat::Pool::instance().findSystemRepo() );
947  if ( system )
948  system.eraseFromPool();
949  }
950 
951 
953  {
954  buildCache();
955 
956  // now add the repos to the pool
957  sat::Pool satpool( sat::Pool::instance() );
958  Pathname rpmsolv( solvfilesPath() / "solv" );
959  MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
960 
961  // Providing an empty system repo, unload any old content
962  Repository system( sat::Pool::instance().findSystemRepo() );
963  if ( system && ! system.solvablesEmpty() )
964  {
965  system.eraseFromPool(); // invalidates system
966  }
967  if ( ! system )
968  {
969  system = satpool.systemRepo();
970  }
971 
972  try
973  {
974  system.addSolv( rpmsolv );
975  }
976  catch ( const Exception & exp )
977  {
978  ZYPP_CAUGHT( exp );
979  MIL << "Try to handle exception by rebuilding the solv-file" << endl;
980  clearCache();
981  buildCache();
982 
983  system.addSolv( rpmsolv );
984  }
985 
986  // (Re)Load the requested locales et al.
987  // If the requested locales are empty, we leave the pool untouched
988  // to avoid undoing changes the application applied. We expect this
989  // to happen on a bare metal installation only. An already existing
990  // target should be loaded before its settings are changed.
991  {
993  if ( ! requestedLocales.empty() )
994  {
996  }
997  }
998  {
999  SoftLocksFile::Data softLocks( _softLocksFile.data() );
1000  if ( ! softLocks.empty() )
1001  {
1002  // Don't soft lock any installed item.
1003  for_( it, system.solvablesBegin(), system.solvablesEnd() )
1004  {
1005  softLocks.erase( it->ident() );
1006  }
1007  ResPool::instance().setAutoSoftLocks( softLocks );
1008  }
1009  }
1010  if ( ZConfig::instance().apply_locks_file() )
1011  {
1012  const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1013  if ( ! hardLocks.empty() )
1014  {
1015  ResPool::instance().setHardLockQueries( hardLocks );
1016  }
1017  }
1018 
1019  // now that the target is loaded, we can cache the flavor
1021 
1022  MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1023  }
1024 
1026  //
1027  // COMMIT
1028  //
1031  {
1032  // ----------------------------------------------------------------- //
1033  ZYppCommitPolicy policy_r( policy_rX );
1034 
1035  // Fake outstanding YCP fix: Honour restriction to media 1
1036  // at installation, but install all remaining packages if post-boot.
1037  if ( policy_r.restrictToMedia() > 1 )
1038  policy_r.allMedia();
1039 
1040  if ( policy_r.downloadMode() == DownloadDefault ) {
1041  if ( root() == "/" )
1042  policy_r.downloadMode(DownloadInHeaps);
1043  else
1044  policy_r.downloadMode(DownloadAsNeeded);
1045  }
1046  // DownloadOnly implies dry-run.
1047  else if ( policy_r.downloadMode() == DownloadOnly )
1048  policy_r.dryRun( true );
1049  // ----------------------------------------------------------------- //
1050 
1051  MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1052 
1054  // Prepare execution of commit plugins:
1056  CommitPlugins commitPlugins;
1057  if ( root() == "/" && ! policy_r.dryRun() )
1058  {
1059  Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
1060  commitPlugins.load( plugindir );
1061  }
1062 
1064  // Write out a testcase if we're in dist upgrade mode.
1066  if ( getZYpp()->resolver()->upgradeMode() )
1067  {
1068  if ( ! policy_r.dryRun() )
1069  {
1071  }
1072  else
1073  {
1074  DBG << "dryRun: Not writing upgrade testcase." << endl;
1075  }
1076  }
1077 
1079  // Store non-package data:
1081  if ( ! policy_r.dryRun() )
1082  {
1084  // requested locales
1086  // weak locks
1087  {
1088  SoftLocksFile::Data newdata;
1089  pool_r.getActiveSoftLocks( newdata );
1090  _softLocksFile.setData( newdata );
1091  }
1092  // hard locks
1093  if ( ZConfig::instance().apply_locks_file() )
1094  {
1095  HardLocksFile::Data newdata;
1096  pool_r.getHardLockQueries( newdata );
1097  _hardLocksFile.setData( newdata );
1098  }
1099  }
1100  else
1101  {
1102  DBG << "dryRun: Not stroring non-package data." << endl;
1103  }
1104 
1106  // Compute transaction:
1108  ZYppCommitResult result( root() );
1109  result.rTransaction() = pool_r.resolver().getTransaction();
1110  result.rTransaction().order();
1111  // steps: this is our todo-list
1113  if ( policy_r.restrictToMedia() )
1114  {
1115  // Collect until the 1st package from an unwanted media occurs.
1116  // Further collection could violate install order.
1117  MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1118  for_( it, result.transaction().begin(), result.transaction().end() )
1119  {
1120  if ( makeResObject( *it )->mediaNr() > 1 )
1121  break;
1122  steps.push_back( *it );
1123  }
1124  }
1125  else
1126  {
1127  result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1128  }
1129  MIL << "Todo: " << result << endl;
1130 
1132  // First collect and display all messages
1133  // associated with patches to be installed.
1135  if ( ! policy_r.dryRun() )
1136  {
1137  for_( it, steps.begin(), steps.end() )
1138  {
1139  if ( ! it->satSolvable().isKind<Patch>() )
1140  continue;
1141 
1142  PoolItem pi( *it );
1143  if ( ! pi.status().isToBeInstalled() )
1144  continue;
1145 
1146  Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1147  if ( ! patch ||patch->message().empty() )
1148  continue;
1149 
1150  MIL << "Show message for " << patch << endl;
1152  if ( ! report->show( patch ) )
1153  {
1154  WAR << "commit aborted by the user" << endl;
1155  ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1156  }
1157  }
1158  }
1159  else
1160  {
1161  DBG << "dryRun: Not checking patch messages." << endl;
1162  }
1163 
1165  // Remove/install packages.
1167  DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1168  if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1169  {
1170  // Prepare the package cache. Pass all items requiring download.
1171  repo::RepoMediaAccess access;
1172  RepoProvidePackage repoProvidePackage( access, pool_r );
1173  CommitPackageCache packageCache( root() / "tmp", repoProvidePackage );
1174  packageCache.setCommitList( steps.begin(), steps.end() );
1175 
1176  bool miss = false;
1177  if ( policy_r.downloadMode() != DownloadAsNeeded )
1178  {
1179  // Preload the cache. Until now this means pre-loading all packages.
1180  // Once DownloadInHeaps is fully implemented, this will change and
1181  // we may actually have more than one heap.
1182  for_( it, steps.begin(), steps.end() )
1183  {
1184  switch ( it->stepType() )
1185  {
1188  // proceed: only install actionas may require download.
1189  break;
1190 
1191  default:
1192  // next: no download for or non-packages and delete actions.
1193  continue;
1194  break;
1195  }
1196 
1197  PoolItem pi( *it );
1198  if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1199  {
1200  ManagedFile localfile;
1201  try
1202  {
1203  // TODO: unify packageCache.get for Package and SrcPackage
1204  if ( pi->isKind<Package>() )
1205  {
1206  localfile = packageCache.get( pi );
1207  }
1208  else if ( pi->isKind<SrcPackage>() )
1209  {
1210  repo::RepoMediaAccess access;
1211  repo::SrcPackageProvider prov( access );
1212  localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1213  }
1214  else
1215  {
1216  INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1217  continue;
1218  }
1219  localfile.resetDispose(); // keep the package file in the cache
1220  }
1221  catch ( const AbortRequestException & exp )
1222  {
1223  it->stepStage( sat::Transaction::STEP_ERROR );
1224  miss = true;
1225  WAR << "commit cache preload aborted by the user" << endl;
1226  ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1227  break;
1228  }
1229  catch ( const SkipRequestException & exp )
1230  {
1231  ZYPP_CAUGHT( exp );
1232  it->stepStage( sat::Transaction::STEP_ERROR );
1233  miss = true;
1234  WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1235  continue;
1236  }
1237  catch ( const Exception & exp )
1238  {
1239  // bnc #395704: missing catch causes abort.
1240  // TODO see if packageCache fails to handle errors correctly.
1241  ZYPP_CAUGHT( exp );
1242  it->stepStage( sat::Transaction::STEP_ERROR );
1243  miss = true;
1244  INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1245  continue;
1246  }
1247  }
1248  }
1249  }
1250 
1251  if ( miss )
1252  {
1253  ERR << "Some packages could not be provided. Aborting commit."<< endl;
1254  }
1255  else if ( ! policy_r.dryRun() )
1256  {
1257  commit( policy_r, packageCache, result );
1258  }
1259  else
1260  {
1261  DBG << "dryRun: Not installing/deleting anything." << endl;
1262  }
1263  }
1264  else
1265  {
1266  DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1267  }
1268 
1270  // Try to rebuild solv file while rpm database is still in cache
1272  if ( ! policy_r.dryRun() )
1273  {
1274  buildCache();
1275  }
1276 
1277  // for DEPRECATED old ZyppCommitResult results:
1279  // build return statistics
1281  result._errors.clear();
1282  result._remaining.clear();
1283  result._srcremaining.clear();
1284  unsigned toInstall = 0;
1285  for_( step, steps.begin(), steps.end() )
1286  {
1287  if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1288  {
1289  // For non-packages only products might have beed installed.
1290  // All the rest is ignored.
1291  if ( step->satSolvable().isSystem() || ! step->satSolvable().isKind<Product>() )
1292  continue;
1293  }
1294  else if ( step->stepType() == sat::Transaction::TRANSACTION_ERASE )
1295  {
1296  continue;
1297  }
1298  // to be installed:
1299  ++toInstall;
1300  switch ( step->stepStage() )
1301  {
1303  if ( step->satSolvable().isKind<Package>() )
1304  result._remaining.push_back( PoolItem( *step ) );
1305  else if ( step->satSolvable().isKind<SrcPackage>() )
1306  result._srcremaining.push_back( PoolItem( *step ) );
1307  break;
1309  // NOOP
1310  break;
1312  result._errors.push_back( PoolItem( *step ) );
1313  break;
1314  }
1315  }
1316  result._result = (toInstall - result._remaining.size());
1318 
1319  MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1320  return result;
1321  }
1322 
1324  //
1325  // COMMIT internal
1326  //
1328  void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1329  CommitPackageCache & packageCache_r,
1330  ZYppCommitResult & result_r )
1331  {
1332  // steps: this is our todo-list
1334  MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1335 
1336  bool abort = false;
1337  std::vector<sat::Solvable> successfullyInstalledPackages;
1338  TargetImpl::PoolItemList remaining;
1339 
1340  for_( step, steps.begin(), steps.end() )
1341  {
1342  PoolItem citem( *step );
1343  if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1344  {
1345  if ( citem->isKind<Package>() )
1346  {
1347  // for packages this means being obsoleted (by rpm)
1348  // thius no additional action is needed.
1349  step->stepStage( sat::Transaction::STEP_DONE );
1350  continue;
1351  }
1352  }
1353 
1354  if ( citem->isKind<Package>() )
1355  {
1356  Package::constPtr p = citem->asKind<Package>();
1357  if ( citem.status().isToBeInstalled() )
1358  {
1359  ManagedFile localfile;
1360  try
1361  {
1362  localfile = packageCache_r.get( citem );
1363  }
1364  catch ( const AbortRequestException &e )
1365  {
1366  WAR << "commit aborted by the user" << endl;
1367  abort = true;
1368  step->stepStage( sat::Transaction::STEP_ERROR );
1369  break;
1370  }
1371  catch ( const SkipRequestException &e )
1372  {
1373  ZYPP_CAUGHT( e );
1374  WAR << "Skipping package " << p << " in commit" << endl;
1375  step->stepStage( sat::Transaction::STEP_ERROR );
1376  continue;
1377  }
1378  catch ( const Exception &e )
1379  {
1380  // bnc #395704: missing catch causes abort.
1381  // TODO see if packageCache fails to handle errors correctly.
1382  ZYPP_CAUGHT( e );
1383  INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1384  step->stepStage( sat::Transaction::STEP_ERROR );
1385  continue;
1386  }
1387 
1388 #warning Exception handling
1389  // create a installation progress report proxy
1390  RpmInstallPackageReceiver progress( citem.resolvable() );
1391  progress.connect(); // disconnected on destruction.
1392 
1393  bool success = false;
1394  rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1395  // Why force and nodeps?
1396  //
1397  // Because zypp builds the transaction and the resolver asserts that
1398  // everything is fine.
1399  // We use rpm just to unpack and register the package in the database.
1400  // We do this step by step, so rpm is not aware of the bigger context.
1401  // So we turn off rpms internal checks, because we do it inside zypp.
1402  flags |= rpm::RPMINST_NODEPS;
1403  flags |= rpm::RPMINST_FORCE;
1404  //
1405  if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1406  if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1407  if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1408  if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1409 
1410  try
1411  {
1413  rpm().installPackage( localfile, flags );
1414  HistoryLog().install(citem);
1415 
1416  if ( progress.aborted() )
1417  {
1418  WAR << "commit aborted by the user" << endl;
1419  localfile.resetDispose(); // keep the package file in the cache
1420  abort = true;
1421  step->stepStage( sat::Transaction::STEP_ERROR );
1422  break;
1423  }
1424  else
1425  {
1426  success = true;
1427  step->stepStage( sat::Transaction::STEP_DONE );
1428  }
1429  }
1430  catch ( Exception & excpt_r )
1431  {
1432  ZYPP_CAUGHT(excpt_r);
1433  localfile.resetDispose(); // keep the package file in the cache
1434 
1435  if ( policy_r.dryRun() )
1436  {
1437  WAR << "dry run failed" << endl;
1438  step->stepStage( sat::Transaction::STEP_ERROR );
1439  break;
1440  }
1441  // else
1442  if ( progress.aborted() )
1443  {
1444  WAR << "commit aborted by the user" << endl;
1445  abort = true;
1446  }
1447  else
1448  {
1449  WAR << "Install failed" << endl;
1450  }
1451  step->stepStage( sat::Transaction::STEP_ERROR );
1452  break; // stop
1453  }
1454 
1455  if ( success && !policy_r.dryRun() )
1456  {
1458  successfullyInstalledPackages.push_back( citem.satSolvable() );
1459  step->stepStage( sat::Transaction::STEP_DONE );
1460  }
1461  }
1462  else
1463  {
1464  RpmRemovePackageReceiver progress( citem.resolvable() );
1465  progress.connect(); // disconnected on destruction.
1466 
1467  bool success = false;
1468  rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1469  flags |= rpm::RPMINST_NODEPS;
1470  if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1471  try
1472  {
1473  rpm().removePackage( p, flags );
1474  HistoryLog().remove(citem);
1475 
1476  if ( progress.aborted() )
1477  {
1478  WAR << "commit aborted by the user" << endl;
1479  abort = true;
1480  step->stepStage( sat::Transaction::STEP_ERROR );
1481  break;
1482  }
1483  else
1484  {
1485  success = true;
1486  step->stepStage( sat::Transaction::STEP_DONE );
1487  }
1488  }
1489  catch (Exception & excpt_r)
1490  {
1491  ZYPP_CAUGHT( excpt_r );
1492  if ( progress.aborted() )
1493  {
1494  WAR << "commit aborted by the user" << endl;
1495  abort = true;
1496  step->stepStage( sat::Transaction::STEP_ERROR );
1497  break;
1498  }
1499  // else
1500  WAR << "removal of " << p << " failed";
1501  step->stepStage( sat::Transaction::STEP_ERROR );
1502  }
1503  if ( success && !policy_r.dryRun() )
1504  {
1506  step->stepStage( sat::Transaction::STEP_DONE );
1507  }
1508  }
1509  }
1510  else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1511  {
1512  // Status is changed as the buddy package buddy
1513  // gets installed/deleted. Handle non-buddies only.
1514  if ( ! citem.buddy() )
1515  {
1516  if ( citem->isKind<Product>() )
1517  {
1518  Product::constPtr p = citem->asKind<Product>();
1519  if ( citem.status().isToBeInstalled() )
1520  {
1521  ERR << "Can't install orphan product without release-package! " << citem << endl;
1522  }
1523  else
1524  {
1525  // Deleting the corresponding product entry is all we con do.
1526  // So the product will no longer be visible as installed.
1527  std::string referenceFilename( p->referenceFilename() );
1528  if ( referenceFilename.empty() )
1529  {
1530  ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1531  }
1532  else
1533  {
1534  PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1535  if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1536  {
1537  ERR << "Delete orphan product failed: " << referenceFile << endl;
1538  }
1539  }
1540  }
1541  }
1542  else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1543  {
1544  // SrcPackage is install-only
1545  SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1546  installSrcPackage( p );
1547  }
1548 
1550  step->stepStage( sat::Transaction::STEP_DONE );
1551  }
1552 
1553  } // other resolvables
1554 
1555  } // for
1556 
1557  // Check presence of update scripts/messages. If aborting,
1558  // at least log omitted scripts.
1559  if ( ! successfullyInstalledPackages.empty() )
1560  {
1561  if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1562  successfullyInstalledPackages, abort ) )
1563  {
1564  WAR << "Commit aborted by the user" << endl;
1565  abort = true;
1566  }
1567  // send messages after scripts in case some script generates output,
1568  // that should be kept in t %ghost message file.
1569  RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1570  successfullyInstalledPackages,
1571  result_r );
1572  }
1573 
1574  if ( abort )
1575  {
1576  ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1577  }
1578  }
1579 
1581 
1583  {
1584  return _rpm;
1585  }
1586 
1587  bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1588  {
1589  return _rpm.hasFile(path_str, name_str);
1590  }
1591 
1592 
1594  {
1595  return _rpm.timestamp();
1596  }
1597 
1599  namespace
1600  {
1601  parser::ProductFileData baseproductdata( const Pathname & root_r )
1602  {
1603  PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1604  if ( baseproduct.isFile() )
1605  {
1606  try
1607  {
1608  return parser::ProductFileReader::scanFile( baseproduct.path() );
1609  }
1610  catch ( const Exception & excpt )
1611  {
1612  ZYPP_CAUGHT( excpt );
1613  }
1614  }
1615  return parser::ProductFileData();
1616  }
1617 
1618  inline Pathname staticGuessRoot( const Pathname & root_r )
1619  {
1620  if ( root_r.empty() )
1621  {
1622  // empty root: use existing Target or assume "/"
1623  Pathname ret ( ZConfig::instance().systemRoot() );
1624  if ( ret.empty() )
1625  return Pathname("/");
1626  return ret;
1627  }
1628  return root_r;
1629  }
1630 
1631  inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1632  {
1633  std::ifstream idfile( file_r.c_str() );
1634  for( iostr::EachLine in( idfile ); in; in.next() )
1635  {
1636  std::string line( str::trim( *in ) );
1637  if ( ! line.empty() )
1638  return line;
1639  }
1640  return std::string();
1641  }
1642  } // namescpace
1644 
1646  {
1647  ResPool pool(ResPool::instance());
1648  for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1649  {
1650  Product::constPtr p = (*it)->asKind<Product>();
1651  if ( p->isTargetDistribution() )
1652  return p;
1653  }
1654  return nullptr;
1655  }
1656 
1657  LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1658  {
1659  const Pathname needroot( staticGuessRoot(root_r) );
1660  const Target_constPtr target( getZYpp()->getTarget() );
1661  if ( target && target->root() == needroot )
1662  return target->requestedLocales();
1663  return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1664  }
1665 
1667  { return baseproductdata( _root ).registerTarget(); }
1668  // static version:
1669  std::string TargetImpl::targetDistribution( const Pathname & root_r )
1670  { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1671 
1673  { return baseproductdata( _root ).registerRelease(); }
1674  // static version:
1675  std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1676  { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1677 
1679  {
1681  parser::ProductFileData pdata( baseproductdata( _root ) );
1682  ret.shortName = pdata.shortName();
1683  ret.summary = pdata.summary();
1684  return ret;
1685  }
1686  // static version:
1688  {
1690  parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1691  ret.shortName = pdata.shortName();
1692  ret.summary = pdata.summary();
1693  return ret;
1694  }
1695 
1697  {
1698  if ( _distributionVersion.empty() )
1699  {
1701  if ( !_distributionVersion.empty() )
1702  MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1703  }
1704  return _distributionVersion;
1705  }
1706  // static version
1707  std::string TargetImpl::distributionVersion( const Pathname & root_r )
1708  {
1709  std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1710  if ( distributionVersion.empty() )
1711  {
1712  // ...But the baseproduct method is not expected to work on RedHat derivatives.
1713  // On RHEL, Fedora and others the "product version" is determined by the first package
1714  // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1715  // with the $distroverpkg variable.
1716  scoped_ptr<rpm::RpmDb> tmprpmdb;
1717  if ( ZConfig::instance().systemRoot() == Pathname() )
1718  {
1719  try
1720  {
1721  tmprpmdb.reset( new rpm::RpmDb );
1722  tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1723  }
1724  catch( ... )
1725  {
1726  return "";
1727  }
1728  }
1731  distributionVersion = it->tag_version();
1732  }
1733  return distributionVersion;
1734  }
1735 
1736 
1738  {
1739  return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1740  }
1741  // static version:
1742  std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1743  {
1744  return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1745  }
1746 
1748 
1749  std::string TargetImpl::anonymousUniqueId() const
1750  {
1751  return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1752  }
1753  // static version:
1754  std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1755  {
1756  return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1757  }
1758 
1760 
1761  void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1762  {
1763  // provide on local disk
1764  repo::RepoMediaAccess access_r;
1765  repo::SrcPackageProvider prov( access_r );
1766  ManagedFile localfile = prov.provideSrcPackage( srcPackage_r );
1767  // install it
1768  rpm().installPackage ( localfile );
1769  }
1770 
1772  } // namespace target
1775 } // namespace zypp