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