libzypp  13.10.6
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 
51 
53 
54 #include "zypp/sat/Pool.h"
55 #include "zypp/sat/Transaction.h"
56 
57 #include "zypp/PluginScript.h"
58 
59 using namespace std;
60 
62 namespace zypp
63 {
64  namespace target
66  {
67 
72  {
73  public:
74 
75  public:
78  {}
79 
82  {
83  for_( it, _scripts.begin(), _scripts.end() )
84  {
85  MIL << "Unload plugin: " << *it << endl;
86  try {
87  it->send( PluginFrame( "PLUGINEND" ) );
88  PluginFrame ret( it->receive() );
89  if ( ! ret.isAckCommand() )
90  {
91  WAR << "Failed to unload plugin: Bad plugin response." << endl;
92  }
93  it->close();
94  }
95  catch( const zypp::Exception & )
96  {
97  WAR << "Failed to unload plugin." << endl;
98  }
99  }
100  // _scripts dtor will disconnect all remaining plugins!
101  }
102 
109  void load( const Pathname & path_r )
110  {
111  PathInfo pi( path_r );
112  if ( pi.isDir() )
113  {
114  std::list<Pathname> entries;
115  if ( filesystem::readdir( entries, pi.path(), false ) != 0 )
116  {
117  WAR << "Plugin dir is not readable: " << pi << endl;
118  return;
119  }
120  for_( it, entries.begin(), entries.end() )
121  {
122  PathInfo pii( *it );
123  if ( pii.isFile() && pii.userMayRX() )
124  doLoad( pii );
125  }
126  }
127  else if ( pi.isFile() )
128  {
129  if ( pi.userMayRX() )
130  doLoad( pi );
131  else
132  WAR << "Plugin file is not executable: " << pi << endl;
133  }
134  else
135  {
136  WAR << "Plugin path is neither dir nor file: " << pi << endl;
137  }
138  }
139 
140  private:
141  void doLoad( const PathInfo & pi_r )
142  {
143  MIL << "Load plugin: " << pi_r << endl;
144  try {
145  PluginFrame frame( "PLUGINBEGIN" );
146  if ( ZConfig::instance().hasUserData() )
147  frame.setHeader( "userdata", ZConfig::instance().userData() );
148 
149  PluginScript plugin( pi_r.path() );
150  plugin.open();
151  plugin.send( frame );
152  PluginFrame ret( plugin.receive() );
153  if ( ret.isAckCommand() )
154  {
155  _scripts.push_back( plugin );
156  }
157  else
158  {
159  WAR << "Failed to load plugin: Bad plugin response." << endl;
160  }
161  }
162  catch( const zypp::Exception & )
163  {
164  WAR << "Failed to load plugin." << endl;
165  }
166  }
167 
168  private:
169  std::list<PluginScript> _scripts;
170  };
171 
172  void testCommitPlugins( const Pathname & path_r ) // for testing only
173  {
174  USR << "+++++" << endl;
175  {
176  CommitPlugins pl;
177  pl.load( path_r );
178  USR << "=====" << endl;
179  }
180  USR << "-----" << endl;
181  }
182 
184 
187  {
188  unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
189  MIL << "Testcases to keep: " << toKeep << endl;
190  if ( !toKeep )
191  return;
192  Target_Ptr target( getZYpp()->getTarget() );
193  if ( ! target )
194  {
195  WAR << "No Target no Testcase!" << endl;
196  return;
197  }
198 
199  std::string stem( "updateTestcase" );
200  Pathname dir( target->assertRootPrefix("/var/log/") );
201  Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
202 
203  {
204  std::list<std::string> content;
205  filesystem::readdir( content, dir, /*dots*/false );
206  std::set<std::string> cases;
207  for_( c, content.begin(), content.end() )
208  {
209  if ( str::startsWith( *c, stem ) )
210  cases.insert( *c );
211  }
212  if ( cases.size() >= toKeep )
213  {
214  unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
215  for_( c, cases.begin(), cases.end() )
216  {
217  filesystem::recursive_rmdir( dir/(*c) );
218  if ( ! --toDel )
219  break;
220  }
221  }
222  }
223 
224  MIL << "Write new testcase " << next << endl;
225  getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
226  }
227 
229  namespace
230  {
231 
242  std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
243  const Pathname & script_r,
245  {
246  MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
247 
248  HistoryLog historylog;
249  historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
250  ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
251 
252  for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
253  {
254  historylog.comment(output);
255  if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
256  {
257  WAR << "User request to abort script " << script_r << endl;
258  prog.kill();
259  // the rest is handled by exit code evaluation
260  // in case the script has meanwhile finished.
261  }
262  }
263 
264  std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
265 
266  if ( prog.close() != 0 )
267  {
268  ret.second = report_r->problem( prog.execError() );
269  WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
270  std::ostringstream sstr;
271  sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
272  historylog.comment(sstr.str(), /*timestamp*/true);
273  return ret;
274  }
275 
276  report_r->finish();
277  ret.first = true;
278  return ret;
279  }
280 
284  bool executeScript( const Pathname & root_r,
285  const Pathname & script_r,
286  callback::SendReport<PatchScriptReport> & report_r )
287  {
288  std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
289 
290  do {
291  action = doExecuteScript( root_r, script_r, report_r );
292  if ( action.first )
293  return true; // success
294 
295  switch ( action.second )
296  {
297  case PatchScriptReport::ABORT:
298  WAR << "User request to abort at script " << script_r << endl;
299  return false; // requested abort.
300  break;
301 
302  case PatchScriptReport::IGNORE:
303  WAR << "User request to skip script " << script_r << endl;
304  return true; // requested skip.
305  break;
306 
307  case PatchScriptReport::RETRY:
308  break; // again
309  }
310  } while ( action.second == PatchScriptReport::RETRY );
311 
312  // THIS is not intended to be reached:
313  INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
314  return false; // abort.
315  }
316 
322  bool RunUpdateScripts( const Pathname & root_r,
323  const Pathname & scriptsPath_r,
324  const std::vector<sat::Solvable> & checkPackages_r,
325  bool aborting_r )
326  {
327  if ( checkPackages_r.empty() )
328  return true; // no installed packages to check
329 
330  MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
331  Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
332  if ( ! PathInfo( scriptsDir ).isDir() )
333  return true; // no script dir
334 
335  std::list<std::string> scripts;
336  filesystem::readdir( scripts, scriptsDir, /*dots*/false );
337  if ( scripts.empty() )
338  return true; // no scripts in script dir
339 
340  // Now collect and execute all matching scripts.
341  // On ABORT: at least log all outstanding scripts.
342  // - "name-version-release"
343  // - "name-version-release-*"
344  bool abort = false;
345  std::map<std::string, Pathname> unify; // scripts <md5,path>
346  for_( it, checkPackages_r.begin(), checkPackages_r.end() )
347  {
348  std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
349  for_( sit, scripts.begin(), scripts.end() )
350  {
351  if ( ! str::hasPrefix( *sit, prefix ) )
352  continue;
353 
354  if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
355  continue; // if not exact match it had to continue with '-'
356 
357  PathInfo script( scriptsDir / *sit );
358  Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
359  std::string unifytag; // must not stay empty
360 
361  if ( script.isFile() )
362  {
363  // Assert it's set executable, unify by md5sum.
364  filesystem::addmod( script.path(), 0500 );
365  unifytag = filesystem::md5sum( script.path() );
366  }
367  else if ( ! script.isExist() )
368  {
369  // Might be a dangling symlink, might be ok if we are in
370  // instsys (absolute symlink within the system below /mnt).
371  // readlink will tell....
372  unifytag = filesystem::readlink( script.path() ).asString();
373  }
374 
375  if ( unifytag.empty() )
376  continue;
377 
378  // Unify scripts
379  if ( unify[unifytag].empty() )
380  {
381  unify[unifytag] = localPath;
382  }
383  else
384  {
385  // translators: We may find the same script content in files with different names.
386  // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
387  // message for a log file. Preferably start translation with "%s"
388  std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
389  MIL << "Skip update script: " << msg << endl;
390  HistoryLog().comment( msg, /*timestamp*/true );
391  continue;
392  }
393 
394  if ( abort || aborting_r )
395  {
396  WAR << "Aborting: Skip update script " << *sit << endl;
397  HistoryLog().comment(
398  localPath.asString() + _(" execution skipped while aborting"),
399  /*timestamp*/true);
400  }
401  else
402  {
403  MIL << "Found update script " << *sit << endl;
404  callback::SendReport<PatchScriptReport> report;
405  report->start( make<Package>( *it ), script.path() );
406 
407  if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
408  abort = true; // requested abort.
409  }
410  }
411  }
412  return !abort;
413  }
414 
416  //
418 
419  inline void copyTo( std::ostream & out_r, const Pathname & file_r )
420  {
421  std::ifstream infile( file_r.c_str() );
422  for( iostr::EachLine in( infile ); in; in.next() )
423  {
424  out_r << *in << endl;
425  }
426  }
427 
428  inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
429  {
430  std::string ret( cmd_r );
431 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
432  SUBST_IF( "%p", notification_r.solvable().asString() );
433  SUBST_IF( "%P", notification_r.file().asString() );
434 #undef SUBST_IF
435  return ret;
436  }
437 
438  void sendNotification( const Pathname & root_r,
439  const UpdateNotifications & notifications_r )
440  {
441  if ( notifications_r.empty() )
442  return;
443 
444  std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
445  MIL << "Notification command is '" << cmdspec << "'" << endl;
446  if ( cmdspec.empty() )
447  return;
448 
449  std::string::size_type pos( cmdspec.find( '|' ) );
450  if ( pos == std::string::npos )
451  {
452  ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
453  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
454  return;
455  }
456 
457  std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
458  std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
459 
460  enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
461  Format format = UNKNOWN;
462  if ( formatStr == "none" )
463  format = NONE;
464  else if ( formatStr == "single" )
465  format = SINGLE;
466  else if ( formatStr == "digest" )
467  format = DIGEST;
468  else if ( formatStr == "bulk" )
469  format = BULK;
470  else
471  {
472  ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
473  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
474  return;
475  }
476 
477  // Take care: commands are ececuted chroot(root_r). The message file
478  // pathnames in notifications_r are local to root_r. For physical access
479  // to the file they need to be prefixed.
480 
481  if ( format == NONE || format == SINGLE )
482  {
483  for_( it, notifications_r.begin(), notifications_r.end() )
484  {
485  std::vector<std::string> command;
486  if ( format == SINGLE )
487  command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
488  str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
489 
490  ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
491  if ( true ) // Wait for feedback
492  {
493  for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
494  {
495  DBG << line;
496  }
497  int ret = prog.close();
498  if ( ret != 0 )
499  {
500  ERR << "Notification command returned with error (" << ret << ")." << endl;
501  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
502  return;
503  }
504  }
505  }
506  }
507  else if ( format == DIGEST || format == BULK )
508  {
509  filesystem::TmpFile tmpfile;
510  ofstream out( tmpfile.path().c_str() );
511  for_( it, notifications_r.begin(), notifications_r.end() )
512  {
513  if ( format == DIGEST )
514  {
515  out << it->file() << endl;
516  }
517  else if ( format == BULK )
518  {
519  copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
520  }
521  }
522 
523  std::vector<std::string> command;
524  command.push_back( "<"+tmpfile.path().asString() ); // redirect input
525  str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
526 
527  ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
528  if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
529  {
530  for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
531  {
532  DBG << line;
533  }
534  int ret = prog.close();
535  if ( ret != 0 )
536  {
537  ERR << "Notification command returned with error (" << ret << ")." << endl;
538  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
539  return;
540  }
541  }
542  }
543  else
544  {
545  INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
546  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
547  return;
548  }
549  }
550 
551 
557  void RunUpdateMessages( const Pathname & root_r,
558  const Pathname & messagesPath_r,
559  const std::vector<sat::Solvable> & checkPackages_r,
560  ZYppCommitResult & result_r )
561  {
562  if ( checkPackages_r.empty() )
563  return; // no installed packages to check
564 
565  MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
566  Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
567  if ( ! PathInfo( messagesDir ).isDir() )
568  return; // no messages dir
569 
570  std::list<std::string> messages;
571  filesystem::readdir( messages, messagesDir, /*dots*/false );
572  if ( messages.empty() )
573  return; // no messages in message dir
574 
575  // Now collect all matching messages in result and send them
576  // - "name-version-release"
577  // - "name-version-release-*"
578  HistoryLog historylog;
579  for_( it, checkPackages_r.begin(), checkPackages_r.end() )
580  {
581  std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
582  for_( sit, messages.begin(), messages.end() )
583  {
584  if ( ! str::hasPrefix( *sit, prefix ) )
585  continue;
586 
587  if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
588  continue; // if not exact match it had to continue with '-'
589 
590  PathInfo message( messagesDir / *sit );
591  if ( ! message.isFile() || message.size() == 0 )
592  continue;
593 
594  MIL << "Found update message " << *sit << endl;
595  Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
596  result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
597  historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
598  }
599  }
600  sendNotification( root_r, result_r.updateMessages() );
601  }
602 
604  } // namespace
606 
607  void XRunUpdateMessages( const Pathname & root_r,
608  const Pathname & messagesPath_r,
609  const std::vector<sat::Solvable> & checkPackages_r,
610  ZYppCommitResult & result_r )
611  { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
612 
614 
615  IMPL_PTR_TYPE(TargetImpl);
616 
617  TargetImpl_Ptr TargetImpl::_nullimpl;
618 
620  TargetImpl_Ptr TargetImpl::nullimpl()
621  {
622  if (_nullimpl == 0)
623  _nullimpl = new TargetImpl;
624  return _nullimpl;
625  }
626 
628  //
629  // METHOD NAME : TargetImpl::TargetImpl
630  // METHOD TYPE : Ctor
631  //
632  TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
633  : _root( root_r )
634  , _requestedLocalesFile( home() / "RequestedLocales" )
635  , _softLocksFile( home() / "SoftLocks" )
636  , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
637  {
638  _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
639 
641 
643 
644  MIL << "Initialized target on " << _root << endl;
645  }
646 
650  static std::string generateRandomId()
651  {
652  std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
653  return iostr::getline( uuidprovider );
654  }
655 
661  void updateFileContent( const Pathname &filename,
662  boost::function<bool ()> condition,
663  boost::function<string ()> value )
664  {
665  string val = value();
666  // if the value is empty, then just dont
667  // do anything, regardless of the condition
668  if ( val.empty() )
669  return;
670 
671  if ( condition() )
672  {
673  MIL << "updating '" << filename << "' content." << endl;
674 
675  // if the file does not exist we need to generate the uuid file
676 
677  std::ofstream filestr;
678  // make sure the path exists
679  filesystem::assert_dir( filename.dirname() );
680  filestr.open( filename.c_str() );
681 
682  if ( filestr.good() )
683  {
684  filestr << val;
685  filestr.close();
686  }
687  else
688  {
689  // FIXME, should we ignore the error?
690  ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
691  }
692  }
693  }
694 
696  static bool fileMissing( const Pathname &pathname )
697  {
698  return ! PathInfo(pathname).isExist();
699  }
700 
702  {
703 
704  // create the anonymous unique id
705  // this value is used for statistics
706  Pathname idpath( home() / "AnonymousUniqueId");
707 
708  try
709  {
710  updateFileContent( idpath,
711  boost::bind(fileMissing, idpath),
713  }
714  catch ( const Exception &e )
715  {
716  WAR << "Can't create anonymous id file" << endl;
717  }
718 
719  }
720 
722  {
723  // create the anonymous unique id
724  // this value is used for statistics
725  Pathname flavorpath( home() / "LastDistributionFlavor");
726 
727  // is there a product
729  if ( ! p )
730  {
731  WAR << "No base product, I won't create flavor cache" << endl;
732  return;
733  }
734 
735  string flavor = p->flavor();
736 
737  try
738  {
739 
740  updateFileContent( flavorpath,
741  // only if flavor is not empty
742  functor::Constant<bool>( ! flavor.empty() ),
743  functor::Constant<string>(flavor) );
744  }
745  catch ( const Exception &e )
746  {
747  WAR << "Can't create flavor cache" << endl;
748  return;
749  }
750  }
751 
753  //
754  // METHOD NAME : TargetImpl::~TargetImpl
755  // METHOD TYPE : Dtor
756  //
758  {
760  MIL << "Targets closed" << endl;
761  }
762 
764  //
765  // solv file handling
766  //
768 
770  {
771  return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
772  }
773 
775  {
776  Pathname base = solvfilesPath();
778  }
779 
781  {
782  Pathname base = solvfilesPath();
783  Pathname rpmsolv = base/"solv";
784  Pathname rpmsolvcookie = base/"cookie";
785 
786  bool build_rpm_solv = true;
787  // lets see if the rpm solv cache exists
788 
789  RepoStatus rpmstatus( RepoStatus( _root/"/var/lib/rpm/Name" )
790  && (_root/"/etc/products.d") );
791 
792  bool solvexisted = PathInfo(rpmsolv).isExist();
793  if ( solvexisted )
794  {
795  // see the status of the cache
796  PathInfo cookie( rpmsolvcookie );
797  MIL << "Read cookie: " << cookie << endl;
798  if ( cookie.isExist() )
799  {
800  RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
801  // now compare it with the rpm database
802  if ( status.checksum() == rpmstatus.checksum() )
803  build_rpm_solv = false;
804  MIL << "Read cookie: " << rpmsolvcookie << " says: "
805  << (build_rpm_solv ? "outdated" : "uptodate") << endl;
806  }
807  }
808 
809  if ( build_rpm_solv )
810  {
811  // if the solvfile dir does not exist yet, we better create it
812  filesystem::assert_dir( base );
813 
814  Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
815 
817  if ( !tmpsolv )
818  {
819  // Can't create temporary solv file, usually due to insufficient permission
820  // (user query while @System solv needs refresh). If so, try switching
821  // to a location within zypps temp. space (will be cleaned at application end).
822 
823  bool switchingToTmpSolvfile = false;
824  Exception ex("Failed to cache rpm database.");
825  ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
826 
827  if ( ! solvfilesPathIsTemp() )
828  {
829  base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
830  rpmsolv = base/"solv";
831  rpmsolvcookie = base/"cookie";
832 
833  filesystem::assert_dir( base );
834  tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
835 
836  if ( tmpsolv )
837  {
838  WAR << "Using a temporary solv file at " << base << endl;
839  switchingToTmpSolvfile = true;
840  _tmpSolvfilesPath = base;
841  }
842  else
843  {
844  ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
845  }
846  }
847 
848  if ( ! switchingToTmpSolvfile )
849  {
850  ZYPP_THROW(ex);
851  }
852  }
853 
854  // Take care we unlink the solvfile on exception
856 
857  std::ostringstream cmd;
858  cmd << "rpmdb2solv";
859  if ( ! _root.empty() )
860  cmd << " -r '" << _root << "'";
861 
862  cmd << " -p '" << Pathname::assertprefix( _root, "/etc/products.d" ) << "'";
863 
864  if ( ! oldSolvFile.empty() )
865  cmd << " '" << oldSolvFile << "'";
866 
867  cmd << " > '" << tmpsolv.path() << "'";
868 
869  MIL << "Executing: " << cmd << endl;
871 
872  cmd << endl;
873  for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
874  WAR << " " << output;
875  cmd << " " << output;
876  }
877 
878  int ret = prog.close();
879  if ( ret != 0 )
880  {
881  Exception ex(str::form("Failed to cache rpm database (%d).", ret));
882  ex.remember( cmd.str() );
883  ZYPP_THROW(ex);
884  }
885 
886  ret = filesystem::rename( tmpsolv, rpmsolv );
887  if ( ret != 0 )
888  ZYPP_THROW(Exception("Failed to move cache to final destination"));
889  // if this fails, don't bother throwing exceptions
890  filesystem::chmod( rpmsolv, 0644 );
891 
892  rpmstatus.saveToCookieFile(rpmsolvcookie);
893 
894  // We keep it.
895  guard.resetDispose();
896 
897  // Finally send notification to plugins
898  // NOTE: quick hack looking for spacewalk plugin only
899  {
900  Pathname script( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"system/spacewalk" ) );
901  if ( PathInfo( script ).isX() )
902  try {
903  PluginScript spacewalk( script );
904  spacewalk.open();
905 
906  PluginFrame notify( "PACKAGESETCHANGED" );
907  spacewalk.send( notify );
908 
909  PluginFrame ret( spacewalk.receive() );
910  MIL << ret << endl;
911  if ( ret.command() == "ERROR" )
912  ret.writeTo( WAR ) << endl;
913  }
914  catch ( const Exception & excpt )
915  {
916  WAR << excpt.asUserHistory() << endl;
917  }
918  }
919  }
920  return build_rpm_solv;
921  }
922 
924  {
925  load( false );
926  }
927 
929  {
930  Repository system( sat::Pool::instance().findSystemRepo() );
931  if ( system )
932  system.eraseFromPool();
933  }
934 
935  void TargetImpl::load( bool force )
936  {
937  bool newCache = buildCache();
938  MIL << "New cache built: " << (newCache?"true":"false") <<
939  ", force loading: " << (force?"true":"false") << endl;
940 
941  // now add the repos to the pool
942  sat::Pool satpool( sat::Pool::instance() );
943  Pathname rpmsolv( solvfilesPath() / "solv" );
944  MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
945 
946  // Providing an empty system repo, unload any old content
947  Repository system( sat::Pool::instance().findSystemRepo() );
948 
949  if ( system && ! system.solvablesEmpty() )
950  {
951  if ( newCache || force )
952  {
953  system.eraseFromPool(); // invalidates system
954  }
955  else
956  {
957  return; // nothing to do
958  }
959  }
960 
961  if ( ! system )
962  {
963  system = satpool.systemRepo();
964  }
965 
966  try
967  {
968  MIL << "adding " << rpmsolv << " to system" << endl;
969  system.addSolv( rpmsolv );
970  }
971  catch ( const Exception & exp )
972  {
973  ZYPP_CAUGHT( exp );
974  MIL << "Try to handle exception by rebuilding the solv-file" << endl;
975  clearCache();
976  buildCache();
977 
978  system.addSolv( rpmsolv );
979  }
980 
981  // (Re)Load the requested locales et al.
982  // If the requested locales are empty, we leave the pool untouched
983  // to avoid undoing changes the application applied. We expect this
984  // to happen on a bare metal installation only. An already existing
985  // target should be loaded before its settings are changed.
986  {
988  if ( ! requestedLocales.empty() )
989  {
991  }
992  }
993  {
994  SoftLocksFile::Data softLocks( _softLocksFile.data() );
995  if ( ! softLocks.empty() )
996  {
997  // Don't soft lock any installed item.
998  for_( it, system.solvablesBegin(), system.solvablesEnd() )
999  {
1000  softLocks.erase( it->ident() );
1001  }
1002  ResPool::instance().setAutoSoftLocks( softLocks );
1003  }
1004  }
1005  if ( ZConfig::instance().apply_locks_file() )
1006  {
1007  const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1008  if ( ! hardLocks.empty() )
1009  {
1010  ResPool::instance().setHardLockQueries( hardLocks );
1011  }
1012  }
1013 
1014  // now that the target is loaded, we can cache the flavor
1016 
1017  MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1018  }
1019 
1021  //
1022  // COMMIT
1023  //
1026  {
1027  // ----------------------------------------------------------------- //
1028  ZYppCommitPolicy policy_r( policy_rX );
1029 
1030  // Fake outstanding YCP fix: Honour restriction to media 1
1031  // at installation, but install all remaining packages if post-boot.
1032  if ( policy_r.restrictToMedia() > 1 )
1033  policy_r.allMedia();
1034 
1035  if ( policy_r.downloadMode() == DownloadDefault ) {
1036  if ( root() == "/" )
1037  policy_r.downloadMode(DownloadInHeaps);
1038  else
1039  policy_r.downloadMode(DownloadAsNeeded);
1040  }
1041  // DownloadOnly implies dry-run.
1042  else if ( policy_r.downloadMode() == DownloadOnly )
1043  policy_r.dryRun( true );
1044  // ----------------------------------------------------------------- //
1045 
1046  MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1047 
1049  // Prepare execution of commit plugins:
1051  CommitPlugins commitPlugins;
1052  if ( root() == "/" && ! policy_r.dryRun() )
1053  {
1054  Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
1055  commitPlugins.load( plugindir );
1056  }
1057 
1059  // Write out a testcase if we're in dist upgrade mode.
1061  if ( getZYpp()->resolver()->upgradeMode() )
1062  {
1063  if ( ! policy_r.dryRun() )
1064  {
1066  }
1067  else
1068  {
1069  DBG << "dryRun: Not writing upgrade testcase." << endl;
1070  }
1071  }
1072 
1074  // Store non-package data:
1076  if ( ! policy_r.dryRun() )
1077  {
1079  // requested locales
1081  // weak locks
1082  {
1083  SoftLocksFile::Data newdata;
1084  pool_r.getActiveSoftLocks( newdata );
1085  _softLocksFile.setData( newdata );
1086  }
1087  // hard locks
1088  if ( ZConfig::instance().apply_locks_file() )
1089  {
1090  HardLocksFile::Data newdata;
1091  pool_r.getHardLockQueries( newdata );
1092  _hardLocksFile.setData( newdata );
1093  }
1094  }
1095  else
1096  {
1097  DBG << "dryRun: Not stroring non-package data." << endl;
1098  }
1099 
1101  // Compute transaction:
1103  ZYppCommitResult result( root() );
1104  result.rTransaction() = pool_r.resolver().getTransaction();
1105  result.rTransaction().order();
1106  // steps: this is our todo-list
1108  if ( policy_r.restrictToMedia() )
1109  {
1110  // Collect until the 1st package from an unwanted media occurs.
1111  // Further collection could violate install order.
1112  MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1113  for_( it, result.transaction().begin(), result.transaction().end() )
1114  {
1115  if ( makeResObject( *it )->mediaNr() > 1 )
1116  break;
1117  steps.push_back( *it );
1118  }
1119  }
1120  else
1121  {
1122  result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1123  }
1124  MIL << "Todo: " << result << endl;
1125 
1127  // First collect and display all messages
1128  // associated with patches to be installed.
1130  if ( ! policy_r.dryRun() )
1131  {
1132  for_( it, steps.begin(), steps.end() )
1133  {
1134  if ( ! it->satSolvable().isKind<Patch>() )
1135  continue;
1136 
1137  PoolItem pi( *it );
1138  if ( ! pi.status().isToBeInstalled() )
1139  continue;
1140 
1141  Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1142  if ( ! patch ||patch->message().empty() )
1143  continue;
1144 
1145  MIL << "Show message for " << patch << endl;
1147  if ( ! report->show( patch ) )
1148  {
1149  WAR << "commit aborted by the user" << endl;
1150  ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1151  }
1152  }
1153  }
1154  else
1155  {
1156  DBG << "dryRun: Not checking patch messages." << endl;
1157  }
1158 
1160  // Remove/install packages.
1162  DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1163  if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1164  {
1165  // Prepare the package cache. Pass all items requiring download.
1166  CommitPackageCache packageCache( root() );
1167  packageCache.setCommitList( steps.begin(), steps.end() );
1168 
1169  bool miss = false;
1170  if ( policy_r.downloadMode() != DownloadAsNeeded )
1171  {
1172  // Preload the cache. Until now this means pre-loading all packages.
1173  // Once DownloadInHeaps is fully implemented, this will change and
1174  // we may actually have more than one heap.
1175  for_( it, steps.begin(), steps.end() )
1176  {
1177  switch ( it->stepType() )
1178  {
1181  // proceed: only install actionas may require download.
1182  break;
1183 
1184  default:
1185  // next: no download for or non-packages and delete actions.
1186  continue;
1187  break;
1188  }
1189 
1190  PoolItem pi( *it );
1191  if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1192  {
1193  ManagedFile localfile;
1194  try
1195  {
1196  // TODO: unify packageCache.get for Package and SrcPackage
1197  if ( pi->isKind<Package>() )
1198  {
1199  localfile = packageCache.get( pi );
1200  }
1201  else if ( pi->isKind<SrcPackage>() )
1202  {
1203  repo::RepoMediaAccess access;
1204  repo::SrcPackageProvider prov( access );
1205  localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1206  }
1207  else
1208  {
1209  INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1210  continue;
1211  }
1212  localfile.resetDispose(); // keep the package file in the cache
1213  }
1214  catch ( const AbortRequestException & exp )
1215  {
1216  it->stepStage( sat::Transaction::STEP_ERROR );
1217  miss = true;
1218  WAR << "commit cache preload aborted by the user" << endl;
1219  ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1220  break;
1221  }
1222  catch ( const SkipRequestException & exp )
1223  {
1224  ZYPP_CAUGHT( exp );
1225  it->stepStage( sat::Transaction::STEP_ERROR );
1226  miss = true;
1227  WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1228  continue;
1229  }
1230  catch ( const Exception & exp )
1231  {
1232  // bnc #395704: missing catch causes abort.
1233  // TODO see if packageCache fails to handle errors correctly.
1234  ZYPP_CAUGHT( exp );
1235  it->stepStage( sat::Transaction::STEP_ERROR );
1236  miss = true;
1237  INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1238  continue;
1239  }
1240  }
1241  }
1242  }
1243 
1244  if ( miss )
1245  {
1246  ERR << "Some packages could not be provided. Aborting commit."<< endl;
1247  }
1248  else if ( ! policy_r.dryRun() )
1249  {
1250  commit( policy_r, packageCache, result );
1251  }
1252  else
1253  {
1254  DBG << "dryRun: Not installing/deleting anything." << endl;
1255  }
1256  }
1257  else
1258  {
1259  DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1260  }
1261 
1263  // Try to rebuild solv file while rpm database is still in cache
1265  if ( ! policy_r.dryRun() )
1266  {
1267  buildCache();
1268  }
1269 
1270  MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1271  return result;
1272  }
1273 
1275  //
1276  // COMMIT internal
1277  //
1279  void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1280  CommitPackageCache & packageCache_r,
1281  ZYppCommitResult & result_r )
1282  {
1283  // steps: this is our todo-list
1285  MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1286 
1287  bool abort = false;
1288  std::vector<sat::Solvable> successfullyInstalledPackages;
1289  TargetImpl::PoolItemList remaining;
1290 
1291  for_( step, steps.begin(), steps.end() )
1292  {
1293  PoolItem citem( *step );
1294  if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1295  {
1296  if ( citem->isKind<Package>() )
1297  {
1298  // for packages this means being obsoleted (by rpm)
1299  // thius no additional action is needed.
1300  step->stepStage( sat::Transaction::STEP_DONE );
1301  continue;
1302  }
1303  }
1304 
1305  if ( citem->isKind<Package>() )
1306  {
1307  Package::constPtr p = citem->asKind<Package>();
1308  if ( citem.status().isToBeInstalled() )
1309  {
1310  ManagedFile localfile;
1311  try
1312  {
1313  localfile = packageCache_r.get( citem );
1314  }
1315  catch ( const AbortRequestException &e )
1316  {
1317  WAR << "commit aborted by the user" << endl;
1318  abort = true;
1319  step->stepStage( sat::Transaction::STEP_ERROR );
1320  break;
1321  }
1322  catch ( const SkipRequestException &e )
1323  {
1324  ZYPP_CAUGHT( e );
1325  WAR << "Skipping package " << p << " in commit" << endl;
1326  step->stepStage( sat::Transaction::STEP_ERROR );
1327  continue;
1328  }
1329  catch ( const Exception &e )
1330  {
1331  // bnc #395704: missing catch causes abort.
1332  // TODO see if packageCache fails to handle errors correctly.
1333  ZYPP_CAUGHT( e );
1334  INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1335  step->stepStage( sat::Transaction::STEP_ERROR );
1336  continue;
1337  }
1338 
1339 #warning Exception handling
1340  // create a installation progress report proxy
1341  RpmInstallPackageReceiver progress( citem.resolvable() );
1342  progress.connect(); // disconnected on destruction.
1343 
1344  bool success = false;
1345  rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1346  // Why force and nodeps?
1347  //
1348  // Because zypp builds the transaction and the resolver asserts that
1349  // everything is fine.
1350  // We use rpm just to unpack and register the package in the database.
1351  // We do this step by step, so rpm is not aware of the bigger context.
1352  // So we turn off rpms internal checks, because we do it inside zypp.
1353  flags |= rpm::RPMINST_NODEPS;
1354  flags |= rpm::RPMINST_FORCE;
1355  //
1356  if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1357  if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1358  if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1359  if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1360 
1361  try
1362  {
1364  rpm().installPackage( localfile, flags );
1365  HistoryLog().install(citem);
1366 
1367  if ( progress.aborted() )
1368  {
1369  WAR << "commit aborted by the user" << endl;
1370  localfile.resetDispose(); // keep the package file in the cache
1371  abort = true;
1372  step->stepStage( sat::Transaction::STEP_ERROR );
1373  break;
1374  }
1375  else
1376  {
1377  success = true;
1378  step->stepStage( sat::Transaction::STEP_DONE );
1379  }
1380  }
1381  catch ( Exception & excpt_r )
1382  {
1383  ZYPP_CAUGHT(excpt_r);
1384  localfile.resetDispose(); // keep the package file in the cache
1385 
1386  if ( policy_r.dryRun() )
1387  {
1388  WAR << "dry run failed" << endl;
1389  step->stepStage( sat::Transaction::STEP_ERROR );
1390  break;
1391  }
1392  // else
1393  if ( progress.aborted() )
1394  {
1395  WAR << "commit aborted by the user" << endl;
1396  abort = true;
1397  }
1398  else
1399  {
1400  WAR << "Install failed" << endl;
1401  }
1402  step->stepStage( sat::Transaction::STEP_ERROR );
1403  break; // stop
1404  }
1405 
1406  if ( success && !policy_r.dryRun() )
1407  {
1409  successfullyInstalledPackages.push_back( citem.satSolvable() );
1410  step->stepStage( sat::Transaction::STEP_DONE );
1411  }
1412  }
1413  else
1414  {
1415  RpmRemovePackageReceiver progress( citem.resolvable() );
1416  progress.connect(); // disconnected on destruction.
1417 
1418  bool success = false;
1419  rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1420  flags |= rpm::RPMINST_NODEPS;
1421  if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1422  try
1423  {
1424  rpm().removePackage( p, flags );
1425  HistoryLog().remove(citem);
1426 
1427  if ( progress.aborted() )
1428  {
1429  WAR << "commit aborted by the user" << endl;
1430  abort = true;
1431  step->stepStage( sat::Transaction::STEP_ERROR );
1432  break;
1433  }
1434  else
1435  {
1436  success = true;
1437  step->stepStage( sat::Transaction::STEP_DONE );
1438  }
1439  }
1440  catch (Exception & excpt_r)
1441  {
1442  ZYPP_CAUGHT( excpt_r );
1443  if ( progress.aborted() )
1444  {
1445  WAR << "commit aborted by the user" << endl;
1446  abort = true;
1447  step->stepStage( sat::Transaction::STEP_ERROR );
1448  break;
1449  }
1450  // else
1451  WAR << "removal of " << p << " failed";
1452  step->stepStage( sat::Transaction::STEP_ERROR );
1453  }
1454  if ( success && !policy_r.dryRun() )
1455  {
1457  step->stepStage( sat::Transaction::STEP_DONE );
1458  }
1459  }
1460  }
1461  else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1462  {
1463  // Status is changed as the buddy package buddy
1464  // gets installed/deleted. Handle non-buddies only.
1465  if ( ! citem.buddy() )
1466  {
1467  if ( citem->isKind<Product>() )
1468  {
1469  Product::constPtr p = citem->asKind<Product>();
1470  if ( citem.status().isToBeInstalled() )
1471  {
1472  ERR << "Can't install orphan product without release-package! " << citem << endl;
1473  }
1474  else
1475  {
1476  // Deleting the corresponding product entry is all we con do.
1477  // So the product will no longer be visible as installed.
1478  std::string referenceFilename( p->referenceFilename() );
1479  if ( referenceFilename.empty() )
1480  {
1481  ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1482  }
1483  else
1484  {
1485  PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1486  if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1487  {
1488  ERR << "Delete orphan product failed: " << referenceFile << endl;
1489  }
1490  }
1491  }
1492  }
1493  else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1494  {
1495  // SrcPackage is install-only
1496  SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1497  installSrcPackage( p );
1498  }
1499 
1501  step->stepStage( sat::Transaction::STEP_DONE );
1502  }
1503 
1504  } // other resolvables
1505 
1506  } // for
1507 
1508  // Check presence of update scripts/messages. If aborting,
1509  // at least log omitted scripts.
1510  if ( ! successfullyInstalledPackages.empty() )
1511  {
1512  if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1513  successfullyInstalledPackages, abort ) )
1514  {
1515  WAR << "Commit aborted by the user" << endl;
1516  abort = true;
1517  }
1518  // send messages after scripts in case some script generates output,
1519  // that should be kept in t %ghost message file.
1520  RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1521  successfullyInstalledPackages,
1522  result_r );
1523  }
1524 
1525  if ( abort )
1526  {
1527  ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1528  }
1529  }
1530 
1532 
1534  {
1535  return _rpm;
1536  }
1537 
1538  bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1539  {
1540  return _rpm.hasFile(path_str, name_str);
1541  }
1542 
1543 
1545  {
1546  return _rpm.timestamp();
1547  }
1548 
1550  namespace
1551  {
1552  parser::ProductFileData baseproductdata( const Pathname & root_r )
1553  {
1555  PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1556 
1557  if ( baseproduct.isFile() )
1558  {
1559  try
1560  {
1561  ret = parser::ProductFileReader::scanFile( baseproduct.path() );
1562  }
1563  catch ( const Exception & excpt )
1564  {
1565  ZYPP_CAUGHT( excpt );
1566  }
1567  }
1568  else if ( PathInfo( Pathname::assertprefix( root_r, "/etc/products.d" ) ).isDir() )
1569  {
1570  ERR << "baseproduct symlink is dangling or missing: " << baseproduct << endl;
1571  }
1572  return ret;
1573  }
1574 
1575  inline Pathname staticGuessRoot( const Pathname & root_r )
1576  {
1577  if ( root_r.empty() )
1578  {
1579  // empty root: use existing Target or assume "/"
1580  Pathname ret ( ZConfig::instance().systemRoot() );
1581  if ( ret.empty() )
1582  return Pathname("/");
1583  return ret;
1584  }
1585  return root_r;
1586  }
1587 
1588  inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1589  {
1590  std::ifstream idfile( file_r.c_str() );
1591  for( iostr::EachLine in( idfile ); in; in.next() )
1592  {
1593  std::string line( str::trim( *in ) );
1594  if ( ! line.empty() )
1595  return line;
1596  }
1597  return std::string();
1598  }
1599  } // namescpace
1601 
1603  {
1604  ResPool pool(ResPool::instance());
1605  for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1606  {
1607  Product::constPtr p = (*it)->asKind<Product>();
1608  if ( p->isTargetDistribution() )
1609  return p;
1610  }
1611  return nullptr;
1612  }
1613 
1614  LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1615  {
1616  const Pathname needroot( staticGuessRoot(root_r) );
1617  const Target_constPtr target( getZYpp()->getTarget() );
1618  if ( target && target->root() == needroot )
1619  return target->requestedLocales();
1620  return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1621  }
1622 
1624  { return baseproductdata( _root ).registerTarget(); }
1625  // static version:
1626  std::string TargetImpl::targetDistribution( const Pathname & root_r )
1627  { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1628 
1630  { return baseproductdata( _root ).registerRelease(); }
1631  // static version:
1632  std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1633  { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1634 
1636  {
1638  parser::ProductFileData pdata( baseproductdata( _root ) );
1639  ret.shortName = pdata.shortName();
1640  ret.summary = pdata.summary();
1641  return ret;
1642  }
1643  // static version:
1645  {
1647  parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1648  ret.shortName = pdata.shortName();
1649  ret.summary = pdata.summary();
1650  return ret;
1651  }
1652 
1654  {
1655  if ( _distributionVersion.empty() )
1656  {
1658  if ( !_distributionVersion.empty() )
1659  MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1660  }
1661  return _distributionVersion;
1662  }
1663  // static version
1664  std::string TargetImpl::distributionVersion( const Pathname & root_r )
1665  {
1666  std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1667  if ( distributionVersion.empty() )
1668  {
1669  // ...But the baseproduct method is not expected to work on RedHat derivatives.
1670  // On RHEL, Fedora and others the "product version" is determined by the first package
1671  // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1672  // with the $distroverpkg variable.
1673  scoped_ptr<rpm::RpmDb> tmprpmdb;
1674  if ( ZConfig::instance().systemRoot() == Pathname() )
1675  {
1676  try
1677  {
1678  tmprpmdb.reset( new rpm::RpmDb );
1679  tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1680  }
1681  catch( ... )
1682  {
1683  return "";
1684  }
1685  }
1688  distributionVersion = it->tag_version();
1689  }
1690  return distributionVersion;
1691  }
1692 
1693 
1695  {
1696  return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1697  }
1698  // static version:
1699  std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1700  {
1701  return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1702  }
1703 
1705 
1706  std::string TargetImpl::anonymousUniqueId() const
1707  {
1708  return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1709  }
1710  // static version:
1711  std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1712  {
1713  return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1714  }
1715 
1717 
1718  void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1719  {
1720  // provide on local disk
1721  ManagedFile localfile = provideSrcPackage(srcPackage_r);
1722  // install it
1723  rpm().installPackage ( localfile );
1724  }
1725 
1726  ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1727  {
1728  // provide on local disk
1729  repo::RepoMediaAccess access_r;
1730  repo::SrcPackageProvider prov( access_r );
1731  return prov.provideSrcPackage( srcPackage_r );
1732  }
1734  } // namespace target
1737 } // namespace zypp
static bool fileMissing(const Pathname &pathname)
helper functor
Definition: TargetImpl.cc:696
ZYppCommitResult commit(ResPool pool_r, const ZYppCommitPolicy &policy_r)
Commit changes in the pool.
Definition: TargetImpl.cc:1025
int assert_dir(const Pathname &path, unsigned mode)
Like &#39;mkdir -p&#39;.
Definition: PathInfo.cc:324
std::string shortName() const
Interface to gettext.
void getActiveSoftLocks(AutoSoftLocks &activeLocks_r)
Suggest a new soft-lock list based on the current selection.
Definition: ResPool.cc:101
Interface to the rpm program.
Definition: RpmDb.h:47
Product interface.
Definition: Product.h:32
#define MIL
Definition: Logger.h:47
CommitPlugins()
Default ctor: Empty plugin list.
Definition: TargetImpl.cc:77
std::vector< sat::Transaction::Step > TransactionStepList
Save and restore locale set from file.
void setData(const Data &data_r)
Store new Data.
Definition: SoftLocksFile.h:71
Alternating download and install.
Definition: DownloadMode.h:32
void setRequestedLocales(const LocaleSet &locales_r)
Set the requested locales.
Definition: Pool.cc:196
Target::DistributionLabel distributionLabel() const
This is version attribute of the installed base product.
Definition: TargetImpl.cc:1635
ZYppCommitPolicy & rpmNoSignature(bool yesNo_r)
Use rpm option –nosignature (default: false)
[M] Install(multiversion) item (
Definition: Transaction.h:70
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:320
byKind_iterator byKindBegin(const ResKind &kind_r) const
Definition: ResPool.h:215
Result returned from ZYpp::commit.
std::string checksum() const
Checksum of the repository.
Definition: RepoStatus.cc:141
static ZConfig & instance()
Singleton ctor.
Definition: ZConfig.cc:655
Pathname path() const
Definition: TmpPath.cc:146
void addSolv(const Pathname &file_r)
Load Solvables from a solv-file.
Definition: Repository.cc:248
std::string md5sum(const Pathname &file)
Compute a files md5sum.
Definition: PathInfo.cc:953
Command frame for communication with PluginScript.
Definition: PluginFrame.h:40
Pathname home() const
The directory to store things.
Definition: TargetImpl.h:123
std::string distroverpkg() const
Package telling the &quot;product version&quot; on systems not using /etc/product.d/baseproduct.
Definition: ZConfig.cc:951
bool findByProvides(const std::string &tag_r)
Reset to iterate all packages that provide a certain tag.
Definition: librpmDb.cc:822
int readlink(const Pathname &symlink_r, Pathname &target_r)
Like &#39;readlink&#39;.
Definition: PathInfo.cc:853
void resetDispose()
Set no dispose function.
Definition: AutoDispose.h:162
static ProductFileData scanFile(const Pathname &file_r)
Parse one file (or symlink) and return the ProductFileData parsed.
void updateFileContent(const Pathname &filename, boost::function< bool()> condition, boost::function< string()> value)
updates the content of filename if condition is true, setting the content the the value returned by v...
Definition: TargetImpl.cc:661
Target::commit helper optimizing package provision.
ZYppCommitPolicy & rpmInstFlags(target::rpm::RpmInstFlags newFlags_r)
The default target::rpm::RpmInstFlags.
TransactionStepList & rTransactionStepList()
Manipulate transactionStepList.
const Data & data() const
Return the data.
Definition: HardLocksFile.h:57
Pathname root() const
The root set for this target.
Definition: TargetImpl.h:119
#define INT
Definition: Logger.h:51
int chmod(const Pathname &path, mode_t mode)
Like &#39;chmod&#39;.
Definition: PathInfo.cc:1021
void installPackage(const Pathname &filename, RpmInstFlags flags=RPMINST_NONE)
install rpm package
Definition: RpmDb.cc:1814
ZYppCommitPolicy & dryRun(bool yesNo_r)
Set dry run (default: false).
#define N_(MSG)
Just tag text for translation.
Definition: Gettext.h:18
ZYppCommitPolicy & rpmExcludeDocs(bool yesNo_r)
Use rpm option –excludedocs (default: false)
std::string _distributionVersion
Cache distributionVersion.
Definition: TargetImpl.h:216
const Data & data() const
Return the data.
Definition: SoftLocksFile.h:55
void setData(const Data &data_r)
Store new Data.
Definition: HardLocksFile.h:73
SolvableIterator solvablesEnd() const
Iterator behind the last Solvable.
Definition: Repository.cc:169
void load(const Pathname &path_r)
Find and launch plugins sending PLUGINSTART message.
Definition: TargetImpl.cc:109
#define for_(IT, BEG, END)
Convenient for-loops using iterator.
Definition: Easy.h:27
void setAutoSoftLocks(const AutoSoftLocks &newLocks_r)
Set a new soft-lock list.
Definition: ResPool.cc:98
bool resetTransact(TransactByValue causer_r)
Not the same as setTransact( false ).
Definition: ResStatus.h:473
Similar to DownloadInAdvance, but try to split the transaction into heaps, where at the end of each h...
Definition: DownloadMode.h:29
TraitsType::constPtrType constPtr
Definition: Product.h:38
Provide a new empty temporary file and delete it when no longer needed.
Definition: TmpPath.h:126
void writeUpgradeTestcase()
Definition: TargetImpl.cc:186
static RepoStatus fromCookieFile(const Pathname &path)
reads the status from a file which contains the checksum and timestamp in each line.
Definition: RepoStatus.cc:97
byKind_iterator byKindEnd(const ResKind &kind_r) const
Definition: ResPool.h:222
Class representing a patch.
Definition: Patch.h:36
void installSrcPackage(const SrcPackage_constPtr &srcPackage_r)
Install a source package on the Target.
Definition: TargetImpl.cc:1718
LocaleSet requestedLocales() const
Languages to be supported by the system.
Definition: TargetImpl.h:163
ManagedFile provideSrcPackage(const SrcPackage_constPtr &srcPackage_r) const
Provide SrcPackage in a local file.
void install(const PoolItem &pi)
Log installation (or update) of a package.
Definition: HistoryLog.cc:188
#define ERR
Definition: Logger.h:49
unsigned splitEscaped(const C_Str &line_r, _OutputIterator result_r, const C_Str &sepchars_r=" \t", bool withEmpty=false)
Split line_r into words with respect to escape delimeters.
Definition: String.h:446
std::string distributionVersion() const
This is version attribute of the installed base product.
Definition: TargetImpl.cc:1653
const_iterator begin() const
Iterator to the first TransactionStep.
Definition: Transaction.cc:324
Subclass to retrieve database content.
Definition: librpmDb.h:490
void remember(const Exception &old_r)
Store an other Exception as history.
Definition: Exception.cc:89
rpm::RpmDb _rpm
RPM database.
Definition: TargetImpl.h:208
Repository systemRepo()
Return the system repository, create it if missing.
Definition: Pool.cc:138
Date timestamp() const
return the last modification date of the target
Definition: TargetImpl.cc:1544
[ ] Nothing (includes implicit deletes due to obsoletes and non-package actions)
Definition: Transaction.h:67
ResObject::constPtr resolvable() const
Returns the ResObject::constPtr.
Definition: PoolItem.cc:280
int addmod(const Pathname &path, mode_t mode)
Add the mode bits to the file given by path.
Definition: PathInfo.cc:1030
std::string getline(std::istream &str)
Read one line from stream.
Definition: IOStream.cc:33
boost::noncopyable NonCopyable
Ensure derived classes cannot be copied.
Definition: NonCopyable.h:26
Store and operate on date (time_t).
Definition: Date.h:31
Base class for concrete Target implementations.
Definition: TargetImpl.h:53
static Pool instance()
Singleton ctor.
Definition: Pool.h:51
SolvableIterator solvablesBegin() const
Iterator to the first Solvable.
Definition: Repository.cc:159
Pathname _root
Path to the target.
Definition: TargetImpl.h:206
~CommitPlugins()
Dtor: Send PLUGINEND message and close plugins.
Definition: TargetImpl.cc:81
Pathname defaultSolvfilesPath() const
The systems default solv file location.
Definition: TargetImpl.cc:769
Execute a program and give access to its io An object of this class encapsulates the execution of an ...
std::string trim(const std::string &s, const Trim trim_r)
Definition: String.cc:204
int unlink(const Pathname &path)
Like &#39;unlink&#39;.
Definition: PathInfo.cc:660
static const std::string & systemRepoAlias()
Reserved system repository alias .
Definition: Pool.cc:33
static const Pathname & fname()
Get the current log file path.
Definition: HistoryLog.cc:147
int rename(const Pathname &oldpath, const Pathname &newpath)
Like &#39;rename&#39;.
Definition: PathInfo.cc:674
Just download all packages to the local cache.
Definition: DownloadMode.h:25
Options and policies for ZYpp::commit.
libzypp will decide what to do.
Definition: DownloadMode.h:24
bool solvfilesPathIsTemp() const
Whether we&#39;re using a temp.
Definition: TargetImpl.h:99
Package interface.
Definition: Package.h:32
ZYppCommitPolicy & downloadMode(DownloadMode val_r)
Commit download policy to use.
RequestedLocalesFile _requestedLocalesFile
Requested Locales database.
Definition: TargetImpl.h:210
bool providesFile(const std::string &path_str, const std::string &name_str) const
If the package is installed and provides the file Needed to evaluate split provides during Resolver:...
Definition: TargetImpl.cc:1538
void setLocales(const LocaleSet &locales_r)
Store a new locale set.
void getHardLockQueries(HardLockQueries &activeLocks_r)
Suggest a new set of queries based on the current selection.
Definition: ResPool.cc:120
#define USR
Definition: Logger.h:52
int recursive_rmdir(const Pathname &path)
Like &#39;rm -r DIR&#39;.
Definition: PathInfo.cc:417
Interim helper class to collect global options and settings.
Definition: ZConfig.h:58
#define WAR
Definition: Logger.h:48
void createLastDistributionFlavorCache() const
generates a cache of the last product flavor
Definition: TargetImpl.cc:721
SoftLocksFile _softLocksFile
Soft-locks database.
Definition: TargetImpl.h:212
bool startsWith(const C_Str &str_r, const C_Str &prefix_r)
alias for hasPrefix
Definition: String.h:858
ResStatus & status() const
Returns the current status.
Definition: PoolItem.cc:241
const LocaleSet & getRequestedLocales() const
Return the requested locales.
Definition: ResPool.cc:144
bool order()
Order transaction steps for commit.
Definition: Transaction.cc:315
void open()
Setup connection and execute script.
Writing the zypp history fileReference counted signleton for writhing the zypp history file...
Definition: HistoryLog.h:55
TraitsType::constPtrType constPtr
Definition: Patch.h:42
std::tr1::unordered_set< Locale > LocaleSet
Definition: Locale.h:28
Pathname solvfilesPath() const
The solv file location actually in use (default or temp).
Definition: TargetImpl.h:95
#define _(MSG)
Return translated text.
Definition: Gettext.h:21
void closeDatabase()
Block further access to the rpm database and go back to uninitialized state.
Definition: RpmDb.cc:727
ZYppCommitPolicy & restrictToMedia(unsigned mediaNr_r)
Restrict commit to media 1.
std::list< PoolItem > PoolItemList
list of pool items
Definition: TargetImpl.h:59
std::string anonymousUniqueId() const
anonymous unique id
Definition: TargetImpl.cc:1706
sat::Transaction getTransaction()
Return the Transaction computed by the last solver run.
Definition: Resolver.cc:71
bool solvablesEmpty() const
Whether Repository contains solvables.
Definition: Repository.cc:147
PluginFrame receive() const
Receive a PluginFrame.
std::string toLower(const std::string &s)
Return lowercase version of s.
Definition: String.cc:166
static std::string generateRandomId()
generates a random id using uuidgen
Definition: TargetImpl.cc:650
void saveToCookieFile(const Pathname &path) const
save the status information to a cookie file
Definition: RepoStatus.cc:114
Provides files from different repos.
ManagedFile get(const PoolItem &citem_r)
Provide a package.
HardLocksFile _hardLocksFile
Hard-Locks database.
Definition: TargetImpl.h:214
SolvableIdType size_type
Definition: PoolMember.h:99
void testCommitPlugins(const Pathname &path_r)
Definition: TargetImpl.cc:172
static void setRoot(const Pathname &root)
Set new root directory to the default history log file path.
Definition: HistoryLog.cc:131
std::string targetDistribution() const
This is register.target attribute of the installed base product.
Definition: TargetImpl.cc:1623
size_type solvablesSize() const
Number of solvables in Repository.
Definition: Repository.cc:153
void setHardLockQueries(const HardLockQueries &newLocks_r)
Set a new set of queries.
Definition: ResPool.cc:117
#define SUBST_IF(PAT, VAL)
std::list< UpdateNotificationFile > UpdateNotifications
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
Definition: Exception.h:324
std::string form(const char *format,...)
Printf style construction of std::string.
Definition: String.cc:34
int readdir(std::list< std::string > &retlist_r, const Pathname &path_r, bool dots_r)
Return content of directory via retlist.
Definition: PathInfo.cc:599
void doLoad(const PathInfo &pi_r)
Definition: TargetImpl.cc:141
const LocaleSet & locales() const
Return the loacale set.
SrcPackage interface.
Definition: SrcPackage.h:29
std::tr1::unordered_set< IdString > Data
Definition: SoftLocksFile.h:39
std::string distributionFlavor() const
This is flavor attribute of the installed base product but does not require the target to be loaded a...
Definition: TargetImpl.cc:1694
sat::Solvable buddy() const
Return the buddy we share our status object with.
Definition: PoolItem.cc:247
Global ResObject pool.
Definition: ResPool.h:48
Pathname systemRoot() const
The target root directory.
Definition: ZConfig.cc:680
ZYppCommitPolicy & allMedia()
Process all media (default)
pool::PoolTraits::HardLockQueries Data
Definition: HardLocksFile.h:41
const sat::Transaction & transaction() const
The full transaction list.
Base class for Exception.
Definition: Exception.h:143
Resolver & resolver() const
The Resolver.
Definition: ResPool.cc:57
bool isToBeInstalled() const
Definition: ResStatus.h:241
Data returned by ProductFileReader.
const_iterator end() const
Iterator behind the last TransactionStep.
Definition: Transaction.cc:330
void remove(const PoolItem &pi)
Log removal of a package.
Definition: HistoryLog.cc:217
Product::constPtr baseProduct() const
returns the target base installed product, also known as the distribution or platform.
Definition: TargetImpl.cc:1602
callback::SendReport< DownloadProgressReport > * report
Definition: MediaCurl.cc:178
void initDatabase(Pathname root_r=Pathname(), Pathname dbPath_r=Pathname(), bool doRebuild_r=false)
Prepare access to the rpm database.
Definition: RpmDb.cc:329
void removePackage(const std::string &name_r, RpmInstFlags flags=RPMINST_NONE)
remove rpm package
virtual ~TargetImpl()
Dtor.
Definition: TargetImpl.cc:757
Reference counted access to a _Tp object calling a custom Dispose function when the last AutoDispose ...
Definition: AutoDispose.h:92
void eraseFromPool()
Remove this Repository from it&#39;s Pool.
Definition: Repository.cc:225
Global sat-pool.
Definition: Pool.h:42
sat::Solvable satSolvable() const
Return the corresponding sat::Solvable.
Definition: PoolItem.h:114
bool hasFile(const std::string &file_r, const std::string &name_r="") const
Return true if at least one package owns a certain file (name_r empty) Return true if package name_r ...
Definition: RpmDb.cc:1300
void comment(const std::string &comment, bool timestamp=false)
Log a comment (even multiline).
Definition: HistoryLog.cc:156
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
Definition: Exception.cc:75
TraitsType::constPtrType constPtr
Definition: SrcPackage.h:36
Date timestamp() const
timestamp of the rpm database (last modification)
Definition: RpmDb.cc:275
ResObject::Ptr makeResObject(const sat::Solvable &solvable_r)
Create ResObject from sat::Solvable.
Definition: ResObject.cc:123
Helper for commit plugin execution.
Definition: TargetImpl.cc:71
sat::Transaction & rTransaction()
Manipulate transaction.
void setHeader(const std::string &key_r, const std::string &value_r=std::string())
Set header for key_r removing all other occurences of key_r.
Definition: PluginFrame.cc:289
Reference to a PoolItem connecting ResObject and ResStatus.
Definition: PoolItem.h:50
ManagedFile provideSrcPackage(const SrcPackage_constPtr &srcPackage_r)
Provides a source package on the Target.
Definition: TargetImpl.cc:1726
static TmpFile makeSibling(const Pathname &sibling_r)
Provide a new empty temporary directory as sibling.
Definition: TmpPath.cc:218
Local facts about a repository This class represents the status of a repository on the system...
Definition: RepoStatus.h:37
void XRunUpdateMessages(const Pathname &root_r, const Pathname &messagesPath_r, const std::vector< sat::Solvable > &checkPackages_r, ZYppCommitResult &result_r)
Definition: TargetImpl.cc:607
Interface to pluigin scripts using a Stomp inspired communication protocol.
Definition: PluginScript.h:62
std::string targetDistributionRelease() const
This is register.release attribute of the installed base product.
Definition: TargetImpl.cc:1629
std::string asString(const std::string &t)
Global asString() that works with std::string too.
Definition: String.h:125
bool hasPrefix(const C_Str &str_r, const C_Str &prefix_r)
Return whether str_r has prefix prefix_r.
Definition: String.h:828
void createAnonymousId() const
generates the unique anonymous id which is called when creating the target
Definition: TargetImpl.cc:701
void send(const PluginFrame &frame_r) const
Send a PluginFrame.
bool empty() const
Whether this is an empty object without valid data.
void setCommitList(std::vector< sat::Solvable > commitList_r)
Download(commit) sequence of solvables to compute read ahead.
rpm::RpmDb & rpm()
The RPM database.
Definition: TargetImpl.cc:1533
TraitsType::constPtrType constPtr
Definition: Package.h:38
#define IMPL_PTR_TYPE(NAME)
#define DBG
Definition: Logger.h:46
static ResPool instance()
Singleton ctor.
Definition: ResPool.cc:33
std::list< PluginScript > _scripts
Definition: TargetImpl.cc:169
void load(bool force=true)
Definition: TargetImpl.cc:935