libzypp  15.21.4
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 #include "zypp/base/Json.h"
30 
31 #include "zypp/ZConfig.h"
32 #include "zypp/ZYppFactory.h"
33 
34 #include "zypp/PoolItem.h"
35 #include "zypp/ResObjects.h"
36 #include "zypp/Url.h"
37 #include "zypp/TmpPath.h"
38 #include "zypp/RepoStatus.h"
39 #include "zypp/ExternalProgram.h"
40 #include "zypp/Repository.h"
41 
42 #include "zypp/ResFilters.h"
43 #include "zypp/HistoryLog.h"
44 #include "zypp/target/TargetImpl.h"
49 
52 
53 #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 {
65  namespace
66  {
67  // HACK for bnc#906096: let pool re-evaluate multiversion spec
68  // if target root changes. ZConfig returns data sensitive to
69  // current target root.
70  inline void sigMultiversionSpecChanged()
71  {
72  sat::detail::PoolMember::myPool().multiversionSpecChanged();
73  }
74  } //namespace
76 
78  namespace json
79  {
80  // Lazy via template specialisation / should switch to overloading
81 
82  template<>
83  inline std::string toJSON( const ZYppCommitResult::TransactionStepList & steps_r )
84  {
85  using sat::Transaction;
86  json::Array ret;
87 
88  for ( const Transaction::Step & step : steps_r )
89  // ignore implicit deletes due to obsoletes and non-package actions
90  if ( step.stepType() != Transaction::TRANSACTION_IGNORE )
91  ret.add( step );
92 
93  return ret.asJSON();
94  }
95 
97  template<>
98  inline std::string toJSON( const sat::Transaction::Step & step_r )
99  {
100  static const std::string strType( "type" );
101  static const std::string strStage( "stage" );
102  static const std::string strSolvable( "solvable" );
103 
104  static const std::string strTypeDel( "-" );
105  static const std::string strTypeIns( "+" );
106  static const std::string strTypeMul( "M" );
107 
108  static const std::string strStageDone( "ok" );
109  static const std::string strStageFailed( "err" );
110 
111  static const std::string strSolvableN( "n" );
112  static const std::string strSolvableE( "e" );
113  static const std::string strSolvableV( "v" );
114  static const std::string strSolvableR( "r" );
115  static const std::string strSolvableA( "a" );
116 
117  using sat::Transaction;
118  json::Object ret;
119 
120  switch ( step_r.stepType() )
121  {
122  case Transaction::TRANSACTION_IGNORE: /*empty*/ break;
123  case Transaction::TRANSACTION_ERASE: ret.add( strType, strTypeDel ); break;
124  case Transaction::TRANSACTION_INSTALL: ret.add( strType, strTypeIns ); break;
125  case Transaction::TRANSACTION_MULTIINSTALL: ret.add( strType, strTypeMul ); break;
126  }
127 
128  switch ( step_r.stepStage() )
129  {
130  case Transaction::STEP_TODO: /*empty*/ break;
131  case Transaction::STEP_DONE: ret.add( strStage, strStageDone ); break;
132  case Transaction::STEP_ERROR: ret.add( strStage, strStageFailed ); break;
133  }
134 
135  {
136  IdString ident;
137  Edition ed;
138  Arch arch;
139  if ( sat::Solvable solv = step_r.satSolvable() )
140  {
141  ident = solv.ident();
142  ed = solv.edition();
143  arch = solv.arch();
144  }
145  else
146  {
147  // deleted package; post mortem data stored in Transaction::Step
148  ident = step_r.ident();
149  ed = step_r.edition();
150  arch = step_r.arch();
151  }
152 
153  json::Object s {
154  { strSolvableN, ident.asString() },
155  { strSolvableV, ed.version() },
156  { strSolvableR, ed.release() },
157  { strSolvableA, arch.asString() }
158  };
159  if ( Edition::epoch_t epoch = ed.epoch() )
160  s.add( strSolvableE, epoch );
161 
162  ret.add( strSolvable, s );
163  }
164 
165  return ret.asJSON();
166  }
167  } // namespace json
169 
171  namespace target
172  {
174  namespace
175  {
176  SolvIdentFile::Data getUserInstalledFromHistory( const Pathname & historyFile_r )
177  {
178  SolvIdentFile::Data onSystemByUserList;
179  // go and parse it: 'who' must constain an '@', then it was installed by user request.
180  // 2009-09-29 07:25:19|install|lirc-remotes|0.8.5-3.2|x86_64|root@opensuse|InstallationImage|a204211eb0...
181  std::ifstream infile( historyFile_r.c_str() );
182  for( iostr::EachLine in( infile ); in; in.next() )
183  {
184  const char * ch( (*in).c_str() );
185  // start with year
186  if ( *ch < '1' || '9' < *ch )
187  continue;
188  const char * sep1 = ::strchr( ch, '|' ); // | after date
189  if ( !sep1 )
190  continue;
191  ++sep1;
192  // if logs an install or delete
193  bool installs = true;
194  if ( ::strncmp( sep1, "install|", 8 ) )
195  {
196  if ( ::strncmp( sep1, "remove |", 8 ) )
197  continue; // no install and no remove
198  else
199  installs = false; // remove
200  }
201  sep1 += 8; // | after what
202  // get the package name
203  const char * sep2 = ::strchr( sep1, '|' ); // | after name
204  if ( !sep2 || sep1 == sep2 )
205  continue;
206  (*in)[sep2-ch] = '\0';
207  IdString pkg( sep1 );
208  // we're done, if a delete
209  if ( !installs )
210  {
211  onSystemByUserList.erase( pkg );
212  continue;
213  }
214  // now guess whether user installed or not (3rd next field contains 'user@host')
215  if ( (sep1 = ::strchr( sep2+1, '|' )) // | after version
216  && (sep1 = ::strchr( sep1+1, '|' )) // | after arch
217  && (sep2 = ::strchr( sep1+1, '|' )) ) // | after who
218  {
219  (*in)[sep2-ch] = '\0';
220  if ( ::strchr( sep1+1, '@' ) )
221  {
222  // by user
223  onSystemByUserList.insert( pkg );
224  continue;
225  }
226  }
227  }
228  MIL << "onSystemByUserList found: " << onSystemByUserList.size() << endl;
229  return onSystemByUserList;
230  }
231  } // namespace
233 
238  {
239  public:
242  {}
243 
246  {
247  if ( ! _scripts.empty() )
248  send( PluginFrame( "PLUGINEND" ) );
249  // ~PluginScript will disconnect all remaining plugins!
250  }
251 
253  bool empty() const
254  { return _scripts.empty(); }
255 
256 
260  void send( const PluginFrame & frame_r )
261  {
262  DBG << "+++++++++++++++ send " << frame_r << endl;
263  for ( auto it = _scripts.begin(); it != _scripts.end(); )
264  {
265  doSend( *it, frame_r );
266  if ( it->isOpen() )
267  ++it;
268  else
269  it = _scripts.erase( it );
270  }
271  DBG << "--------------- send " << frame_r << endl;
272  }
273 
280  void load( const Pathname & path_r )
281  {
282  PathInfo pi( path_r );
283  DBG << "+++++++++++++++ load " << pi << endl;
284  if ( pi.isDir() )
285  {
286  std::list<Pathname> entries;
287  if ( filesystem::readdir( entries, pi.path(), false ) != 0 )
288  {
289  WAR << "Plugin dir is not readable: " << pi << endl;
290  return;
291  }
292  for_( it, entries.begin(), entries.end() )
293  {
294  PathInfo pii( *it );
295  if ( pii.isFile() && pii.userMayRX() )
296  doLoad( pii );
297  }
298  }
299  else if ( pi.isFile() )
300  {
301  if ( pi.userMayRX() )
302  doLoad( pi );
303  else
304  WAR << "Plugin file is not executable: " << pi << endl;
305  }
306  else
307  {
308  WAR << "Plugin path is neither dir nor file: " << pi << endl;
309  }
310  DBG << "--------------- load " << pi << endl;
311  }
312 
313  private:
319  PluginFrame doSend( PluginScript & script_r, const PluginFrame & frame_r )
320  {
321  PluginFrame ret;
322 
323  try {
324  script_r.send( frame_r );
325  ret = script_r.receive();
326  }
327  catch( const zypp::Exception & e )
328  { ZYPP_CAUGHT(e); }
329 
330  if ( ! ( ret.isAckCommand() || ret.isEnomethodCommand() ) )
331  {
332  WAR << "Bad plugin response from " << script_r << endl;
333  WAR << dump(ret) << endl;
334  script_r.close();
335  }
336 
337  return ret;
338  }
339 
341  void doLoad( const PathInfo & pi_r )
342  {
343  MIL << "Load plugin: " << pi_r << endl;
344  try {
345  PluginScript plugin( pi_r.path() );
346  plugin.open();
347 
348  PluginFrame frame( "PLUGINBEGIN" );
349  if ( ZConfig::instance().hasUserData() )
350  frame.setHeader( "userdata", ZConfig::instance().userData() );
351 
352  doSend( plugin, frame ); // closes on error
353  if ( plugin.isOpen() )
354  _scripts.push_back( plugin );
355  }
356  catch( const zypp::Exception & e )
357  {
358  WAR << "Failed to load plugin " << pi_r << endl;
359  }
360  }
361 
362  private:
363  std::list<PluginScript> _scripts;
364  };
365 
366  void testCommitPlugins( const Pathname & path_r ) // for testing only
367  {
368  USR << "+++++" << endl;
369  {
370  CommitPlugins pl;
371  pl.load( path_r );
372  USR << "=====" << endl;
373  }
374  USR << "-----" << endl;
375  }
376 
378  namespace
379  {
380  inline PluginFrame transactionPluginFrame( const std::string & command_r, ZYppCommitResult::TransactionStepList & steps_r )
381  {
382  return PluginFrame( command_r, json::Object {
383  { "TransactionStepList", steps_r }
384  }.asJSON() );
385  }
386  } // namespace
388 
391  {
392  unsigned toKeep( ZConfig::instance().solver_upgradeTestcasesToKeep() );
393  MIL << "Testcases to keep: " << toKeep << endl;
394  if ( !toKeep )
395  return;
396  Target_Ptr target( getZYpp()->getTarget() );
397  if ( ! target )
398  {
399  WAR << "No Target no Testcase!" << endl;
400  return;
401  }
402 
403  std::string stem( "updateTestcase" );
404  Pathname dir( target->assertRootPrefix("/var/log/") );
405  Pathname next( dir / Date::now().form( stem+"-%Y-%m-%d-%H-%M-%S" ) );
406 
407  {
408  std::list<std::string> content;
409  filesystem::readdir( content, dir, /*dots*/false );
410  std::set<std::string> cases;
411  for_( c, content.begin(), content.end() )
412  {
413  if ( str::startsWith( *c, stem ) )
414  cases.insert( *c );
415  }
416  if ( cases.size() >= toKeep )
417  {
418  unsigned toDel = cases.size() - toKeep + 1; // +1 for the new one
419  for_( c, cases.begin(), cases.end() )
420  {
421  filesystem::recursive_rmdir( dir/(*c) );
422  if ( ! --toDel )
423  break;
424  }
425  }
426  }
427 
428  MIL << "Write new testcase " << next << endl;
429  getZYpp()->resolver()->createSolverTestcase( next.asString(), false/*no solving*/ );
430  }
431 
433  namespace
434  {
435 
446  std::pair<bool,PatchScriptReport::Action> doExecuteScript( const Pathname & root_r,
447  const Pathname & script_r,
449  {
450  MIL << "Execute script " << PathInfo(Pathname::assertprefix( root_r,script_r)) << endl;
451 
452  HistoryLog historylog;
453  historylog.comment(script_r.asString() + _(" executed"), /*timestamp*/true);
454  ExternalProgram prog( script_r.asString(), ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
455 
456  for ( std::string output = prog.receiveLine(); output.length(); output = prog.receiveLine() )
457  {
458  historylog.comment(output);
459  if ( ! report_r->progress( PatchScriptReport::OUTPUT, output ) )
460  {
461  WAR << "User request to abort script " << script_r << endl;
462  prog.kill();
463  // the rest is handled by exit code evaluation
464  // in case the script has meanwhile finished.
465  }
466  }
467 
468  std::pair<bool,PatchScriptReport::Action> ret( std::make_pair( false, PatchScriptReport::ABORT ) );
469 
470  if ( prog.close() != 0 )
471  {
472  ret.second = report_r->problem( prog.execError() );
473  WAR << "ACTION" << ret.second << "(" << prog.execError() << ")" << endl;
474  std::ostringstream sstr;
475  sstr << script_r << _(" execution failed") << " (" << prog.execError() << ")" << endl;
476  historylog.comment(sstr.str(), /*timestamp*/true);
477  return ret;
478  }
479 
480  report_r->finish();
481  ret.first = true;
482  return ret;
483  }
484 
488  bool executeScript( const Pathname & root_r,
489  const Pathname & script_r,
490  callback::SendReport<PatchScriptReport> & report_r )
491  {
492  std::pair<bool,PatchScriptReport::Action> action( std::make_pair( false, PatchScriptReport::ABORT ) );
493 
494  do {
495  action = doExecuteScript( root_r, script_r, report_r );
496  if ( action.first )
497  return true; // success
498 
499  switch ( action.second )
500  {
501  case PatchScriptReport::ABORT:
502  WAR << "User request to abort at script " << script_r << endl;
503  return false; // requested abort.
504  break;
505 
506  case PatchScriptReport::IGNORE:
507  WAR << "User request to skip script " << script_r << endl;
508  return true; // requested skip.
509  break;
510 
511  case PatchScriptReport::RETRY:
512  break; // again
513  }
514  } while ( action.second == PatchScriptReport::RETRY );
515 
516  // THIS is not intended to be reached:
517  INT << "Abort on unknown ACTION request " << action.second << " returned" << endl;
518  return false; // abort.
519  }
520 
526  bool RunUpdateScripts( const Pathname & root_r,
527  const Pathname & scriptsPath_r,
528  const std::vector<sat::Solvable> & checkPackages_r,
529  bool aborting_r )
530  {
531  if ( checkPackages_r.empty() )
532  return true; // no installed packages to check
533 
534  MIL << "Looking for new update scripts in (" << root_r << ")" << scriptsPath_r << endl;
535  Pathname scriptsDir( Pathname::assertprefix( root_r, scriptsPath_r ) );
536  if ( ! PathInfo( scriptsDir ).isDir() )
537  return true; // no script dir
538 
539  std::list<std::string> scripts;
540  filesystem::readdir( scripts, scriptsDir, /*dots*/false );
541  if ( scripts.empty() )
542  return true; // no scripts in script dir
543 
544  // Now collect and execute all matching scripts.
545  // On ABORT: at least log all outstanding scripts.
546  // - "name-version-release"
547  // - "name-version-release-*"
548  bool abort = false;
549  std::map<std::string, Pathname> unify; // scripts <md5,path>
550  for_( it, checkPackages_r.begin(), checkPackages_r.end() )
551  {
552  std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
553  for_( sit, scripts.begin(), scripts.end() )
554  {
555  if ( ! str::hasPrefix( *sit, prefix ) )
556  continue;
557 
558  if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
559  continue; // if not exact match it had to continue with '-'
560 
561  PathInfo script( scriptsDir / *sit );
562  Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
563  std::string unifytag; // must not stay empty
564 
565  if ( script.isFile() )
566  {
567  // Assert it's set executable, unify by md5sum.
568  filesystem::addmod( script.path(), 0500 );
569  unifytag = filesystem::md5sum( script.path() );
570  }
571  else if ( ! script.isExist() )
572  {
573  // Might be a dangling symlink, might be ok if we are in
574  // instsys (absolute symlink within the system below /mnt).
575  // readlink will tell....
576  unifytag = filesystem::readlink( script.path() ).asString();
577  }
578 
579  if ( unifytag.empty() )
580  continue;
581 
582  // Unify scripts
583  if ( unify[unifytag].empty() )
584  {
585  unify[unifytag] = localPath;
586  }
587  else
588  {
589  // translators: We may find the same script content in files with different names.
590  // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
591  // message for a log file. Preferably start translation with "%s"
592  std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
593  MIL << "Skip update script: " << msg << endl;
594  HistoryLog().comment( msg, /*timestamp*/true );
595  continue;
596  }
597 
598  if ( abort || aborting_r )
599  {
600  WAR << "Aborting: Skip update script " << *sit << endl;
601  HistoryLog().comment(
602  localPath.asString() + _(" execution skipped while aborting"),
603  /*timestamp*/true);
604  }
605  else
606  {
607  MIL << "Found update script " << *sit << endl;
608  callback::SendReport<PatchScriptReport> report;
609  report->start( make<Package>( *it ), script.path() );
610 
611  if ( ! executeScript( root_r, localPath, report ) ) // script path without root prefix!
612  abort = true; // requested abort.
613  }
614  }
615  }
616  return !abort;
617  }
618 
620  //
622 
623  inline void copyTo( std::ostream & out_r, const Pathname & file_r )
624  {
625  std::ifstream infile( file_r.c_str() );
626  for( iostr::EachLine in( infile ); in; in.next() )
627  {
628  out_r << *in << endl;
629  }
630  }
631 
632  inline std::string notificationCmdSubst( const std::string & cmd_r, const UpdateNotificationFile & notification_r )
633  {
634  std::string ret( cmd_r );
635 #define SUBST_IF(PAT,VAL) if ( ret.find( PAT ) != std::string::npos ) ret = str::gsub( ret, PAT, VAL )
636  SUBST_IF( "%p", notification_r.solvable().asString() );
637  SUBST_IF( "%P", notification_r.file().asString() );
638 #undef SUBST_IF
639  return ret;
640  }
641 
642  void sendNotification( const Pathname & root_r,
643  const UpdateNotifications & notifications_r )
644  {
645  if ( notifications_r.empty() )
646  return;
647 
648  std::string cmdspec( ZConfig::instance().updateMessagesNotify() );
649  MIL << "Notification command is '" << cmdspec << "'" << endl;
650  if ( cmdspec.empty() )
651  return;
652 
653  std::string::size_type pos( cmdspec.find( '|' ) );
654  if ( pos == std::string::npos )
655  {
656  ERR << "Can't send Notification: Missing 'format |' in command spec." << endl;
657  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
658  return;
659  }
660 
661  std::string formatStr( str::toLower( str::trim( cmdspec.substr( 0, pos ) ) ) );
662  std::string commandStr( str::trim( cmdspec.substr( pos + 1 ) ) );
663 
664  enum Format { UNKNOWN, NONE, SINGLE, DIGEST, BULK };
665  Format format = UNKNOWN;
666  if ( formatStr == "none" )
667  format = NONE;
668  else if ( formatStr == "single" )
669  format = SINGLE;
670  else if ( formatStr == "digest" )
671  format = DIGEST;
672  else if ( formatStr == "bulk" )
673  format = BULK;
674  else
675  {
676  ERR << "Can't send Notification: Unknown format '" << formatStr << " |' in command spec." << endl;
677  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
678  return;
679  }
680 
681  // Take care: commands are ececuted chroot(root_r). The message file
682  // pathnames in notifications_r are local to root_r. For physical access
683  // to the file they need to be prefixed.
684 
685  if ( format == NONE || format == SINGLE )
686  {
687  for_( it, notifications_r.begin(), notifications_r.end() )
688  {
689  std::vector<std::string> command;
690  if ( format == SINGLE )
691  command.push_back( "<"+Pathname::assertprefix( root_r, it->file() ).asString() );
692  str::splitEscaped( notificationCmdSubst( commandStr, *it ), std::back_inserter( command ) );
693 
694  ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
695  if ( true ) // Wait for feedback
696  {
697  for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
698  {
699  DBG << line;
700  }
701  int ret = prog.close();
702  if ( ret != 0 )
703  {
704  ERR << "Notification command returned with error (" << ret << ")." << endl;
705  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
706  return;
707  }
708  }
709  }
710  }
711  else if ( format == DIGEST || format == BULK )
712  {
713  filesystem::TmpFile tmpfile;
714  ofstream out( tmpfile.path().c_str() );
715  for_( it, notifications_r.begin(), notifications_r.end() )
716  {
717  if ( format == DIGEST )
718  {
719  out << it->file() << endl;
720  }
721  else if ( format == BULK )
722  {
723  copyTo( out << '\f', Pathname::assertprefix( root_r, it->file() ) );
724  }
725  }
726 
727  std::vector<std::string> command;
728  command.push_back( "<"+tmpfile.path().asString() ); // redirect input
729  str::splitEscaped( notificationCmdSubst( commandStr, *notifications_r.begin() ), std::back_inserter( command ) );
730 
731  ExternalProgram prog( command, ExternalProgram::Stderr_To_Stdout, false, -1, true, root_r );
732  if ( true ) // Wait for feedback otherwise the TmpFile goes out of scope.
733  {
734  for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
735  {
736  DBG << line;
737  }
738  int ret = prog.close();
739  if ( ret != 0 )
740  {
741  ERR << "Notification command returned with error (" << ret << ")." << endl;
742  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
743  return;
744  }
745  }
746  }
747  else
748  {
749  INT << "Can't send Notification: Missing handler for 'format |' in command spec." << endl;
750  HistoryLog().comment( str::Str() << _("Error sending update message notification."), /*timestamp*/true );
751  return;
752  }
753  }
754 
755 
761  void RunUpdateMessages( const Pathname & root_r,
762  const Pathname & messagesPath_r,
763  const std::vector<sat::Solvable> & checkPackages_r,
764  ZYppCommitResult & result_r )
765  {
766  if ( checkPackages_r.empty() )
767  return; // no installed packages to check
768 
769  MIL << "Looking for new update messages in (" << root_r << ")" << messagesPath_r << endl;
770  Pathname messagesDir( Pathname::assertprefix( root_r, messagesPath_r ) );
771  if ( ! PathInfo( messagesDir ).isDir() )
772  return; // no messages dir
773 
774  std::list<std::string> messages;
775  filesystem::readdir( messages, messagesDir, /*dots*/false );
776  if ( messages.empty() )
777  return; // no messages in message dir
778 
779  // Now collect all matching messages in result and send them
780  // - "name-version-release"
781  // - "name-version-release-*"
782  HistoryLog historylog;
783  for_( it, checkPackages_r.begin(), checkPackages_r.end() )
784  {
785  std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
786  for_( sit, messages.begin(), messages.end() )
787  {
788  if ( ! str::hasPrefix( *sit, prefix ) )
789  continue;
790 
791  if ( (*sit)[prefix.size()] != '\0' && (*sit)[prefix.size()] != '-' )
792  continue; // if not exact match it had to continue with '-'
793 
794  PathInfo message( messagesDir / *sit );
795  if ( ! message.isFile() || message.size() == 0 )
796  continue;
797 
798  MIL << "Found update message " << *sit << endl;
799  Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
800  result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
801  historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
802  }
803  }
804  sendNotification( root_r, result_r.updateMessages() );
805  }
806 
808  } // namespace
810 
811  void XRunUpdateMessages( const Pathname & root_r,
812  const Pathname & messagesPath_r,
813  const std::vector<sat::Solvable> & checkPackages_r,
814  ZYppCommitResult & result_r )
815  { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
816 
818 
819  IMPL_PTR_TYPE(TargetImpl);
820 
822  //
823  // METHOD NAME : TargetImpl::TargetImpl
824  // METHOD TYPE : Ctor
825  //
826  TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
827  : _root( root_r )
828  , _requestedLocalesFile( home() / "RequestedLocales" )
829  , _autoInstalledFile( home() / "AutoInstalled" )
830  , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
831  {
832  _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
833 
835 
837  sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
838  MIL << "Initialized target on " << _root << endl;
839  }
840 
844  static std::string generateRandomId()
845  {
846  std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
847  return iostr::getline( uuidprovider );
848  }
849 
855  void updateFileContent( const Pathname &filename,
856  boost::function<bool ()> condition,
857  boost::function<string ()> value )
858  {
859  string val = value();
860  // if the value is empty, then just dont
861  // do anything, regardless of the condition
862  if ( val.empty() )
863  return;
864 
865  if ( condition() )
866  {
867  MIL << "updating '" << filename << "' content." << endl;
868 
869  // if the file does not exist we need to generate the uuid file
870 
871  std::ofstream filestr;
872  // make sure the path exists
873  filesystem::assert_dir( filename.dirname() );
874  filestr.open( filename.c_str() );
875 
876  if ( filestr.good() )
877  {
878  filestr << val;
879  filestr.close();
880  }
881  else
882  {
883  // FIXME, should we ignore the error?
884  ZYPP_THROW(Exception("Can't openfile '" + filename.asString() + "' for writing"));
885  }
886  }
887  }
888 
890  static bool fileMissing( const Pathname &pathname )
891  {
892  return ! PathInfo(pathname).isExist();
893  }
894 
896  {
897 
898  // create the anonymous unique id
899  // this value is used for statistics
900  Pathname idpath( home() / "AnonymousUniqueId");
901 
902  try
903  {
904  updateFileContent( idpath,
905  boost::bind(fileMissing, idpath),
907  }
908  catch ( const Exception &e )
909  {
910  WAR << "Can't create anonymous id file" << endl;
911  }
912 
913  }
914 
916  {
917  // create the anonymous unique id
918  // this value is used for statistics
919  Pathname flavorpath( home() / "LastDistributionFlavor");
920 
921  // is there a product
923  if ( ! p )
924  {
925  WAR << "No base product, I won't create flavor cache" << endl;
926  return;
927  }
928 
929  string flavor = p->flavor();
930 
931  try
932  {
933 
934  updateFileContent( flavorpath,
935  // only if flavor is not empty
936  functor::Constant<bool>( ! flavor.empty() ),
937  functor::Constant<string>(flavor) );
938  }
939  catch ( const Exception &e )
940  {
941  WAR << "Can't create flavor cache" << endl;
942  return;
943  }
944  }
945 
947  //
948  // METHOD NAME : TargetImpl::~TargetImpl
949  // METHOD TYPE : Dtor
950  //
952  {
954  sigMultiversionSpecChanged(); // HACK: see sigMultiversionSpecChanged
955  MIL << "Targets closed" << endl;
956  }
957 
959  //
960  // solv file handling
961  //
963 
965  {
966  return Pathname::assertprefix( _root, ZConfig::instance().repoSolvfilesPath() / sat::Pool::instance().systemRepoAlias() );
967  }
968 
970  {
971  Pathname base = solvfilesPath();
973  }
974 
976  {
977  Pathname base = solvfilesPath();
978  Pathname rpmsolv = base/"solv";
979  Pathname rpmsolvcookie = base/"cookie";
980 
981  bool build_rpm_solv = true;
982  // lets see if the rpm solv cache exists
983 
984  RepoStatus rpmstatus( RepoStatus(_root/"var/lib/rpm/Name") && RepoStatus(_root/"etc/products.d") );
985 
986  bool solvexisted = PathInfo(rpmsolv).isExist();
987  if ( solvexisted )
988  {
989  // see the status of the cache
990  PathInfo cookie( rpmsolvcookie );
991  MIL << "Read cookie: " << cookie << endl;
992  if ( cookie.isExist() )
993  {
994  RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
995  // now compare it with the rpm database
996  if ( status == rpmstatus )
997  build_rpm_solv = false;
998  MIL << "Read cookie: " << rpmsolvcookie << " says: "
999  << (build_rpm_solv ? "outdated" : "uptodate") << endl;
1000  }
1001  }
1002 
1003  if ( build_rpm_solv )
1004  {
1005  // if the solvfile dir does not exist yet, we better create it
1006  filesystem::assert_dir( base );
1007 
1008  Pathname oldSolvFile( solvexisted ? rpmsolv : Pathname() ); // to speedup rpmdb2solv
1009 
1011  if ( !tmpsolv )
1012  {
1013  // Can't create temporary solv file, usually due to insufficient permission
1014  // (user query while @System solv needs refresh). If so, try switching
1015  // to a location within zypps temp. space (will be cleaned at application end).
1016 
1017  bool switchingToTmpSolvfile = false;
1018  Exception ex("Failed to cache rpm database.");
1019  ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
1020 
1021  if ( ! solvfilesPathIsTemp() )
1022  {
1023  base = getZYpp()->tmpPath() / sat::Pool::instance().systemRepoAlias();
1024  rpmsolv = base/"solv";
1025  rpmsolvcookie = base/"cookie";
1026 
1027  filesystem::assert_dir( base );
1028  tmpsolv = filesystem::TmpFile::makeSibling( rpmsolv );
1029 
1030  if ( tmpsolv )
1031  {
1032  WAR << "Using a temporary solv file at " << base << endl;
1033  switchingToTmpSolvfile = true;
1034  _tmpSolvfilesPath = base;
1035  }
1036  else
1037  {
1038  ex.remember(str::form("Cannot create temporary file under %s.", base.c_str()));
1039  }
1040  }
1041 
1042  if ( ! switchingToTmpSolvfile )
1043  {
1044  ZYPP_THROW(ex);
1045  }
1046  }
1047 
1048  // Take care we unlink the solvfile on exception
1050 
1052  cmd.push_back( "rpmdb2solv" );
1053  if ( ! _root.empty() ) {
1054  cmd.push_back( "-r" );
1055  cmd.push_back( _root.asString() );
1056  }
1057  cmd.push_back( "-X" ); // autogenerate pattern/product/... from -package
1058  cmd.push_back( "-A" ); // autogenerate application pseudo packages
1059  cmd.push_back( "-p" );
1060  cmd.push_back( Pathname::assertprefix( _root, "/etc/products.d" ).asString() );
1061 
1062  if ( ! oldSolvFile.empty() )
1063  cmd.push_back( oldSolvFile.asString() );
1064 
1065  cmd.push_back( "-o" );
1066  cmd.push_back( tmpsolv.path().asString() );
1067 
1069  std::string errdetail;
1070 
1071  for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1072  WAR << " " << output;
1073  if ( errdetail.empty() ) {
1074  errdetail = prog.command();
1075  errdetail += '\n';
1076  }
1077  errdetail += output;
1078  }
1079 
1080  int ret = prog.close();
1081  if ( ret != 0 )
1082  {
1083  Exception ex(str::form("Failed to cache rpm database (%d).", ret));
1084  ex.remember( errdetail );
1085  ZYPP_THROW(ex);
1086  }
1087 
1088  ret = filesystem::rename( tmpsolv, rpmsolv );
1089  if ( ret != 0 )
1090  ZYPP_THROW(Exception("Failed to move cache to final destination"));
1091  // if this fails, don't bother throwing exceptions
1092  filesystem::chmod( rpmsolv, 0644 );
1093 
1094  rpmstatus.saveToCookieFile(rpmsolvcookie);
1095 
1096  // We keep it.
1097  guard.resetDispose();
1098  sat::updateSolvFileIndex( rpmsolv ); // content digest for zypper bash completion
1099 
1100  // Finally send notification to plugins
1101  // NOTE: quick hack looking for spacewalk plugin only
1102  {
1103  Pathname script( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"system/spacewalk" ) );
1104  if ( PathInfo( script ).isX() )
1105  try {
1106  PluginScript spacewalk( script );
1107  spacewalk.open();
1108 
1109  PluginFrame notify( "PACKAGESETCHANGED" );
1110  spacewalk.send( notify );
1111 
1112  PluginFrame ret( spacewalk.receive() );
1113  MIL << ret << endl;
1114  if ( ret.command() == "ERROR" )
1115  ret.writeTo( WAR ) << endl;
1116  }
1117  catch ( const Exception & excpt )
1118  {
1119  WAR << excpt.asUserHistory() << endl;
1120  }
1121  }
1122  }
1123  else
1124  {
1125  // On the fly add missing solv.idx files for bash completion.
1126  if ( ! PathInfo(base/"solv.idx").isExist() )
1127  sat::updateSolvFileIndex( rpmsolv );
1128  }
1129  return build_rpm_solv;
1130  }
1131 
1133  {
1134  load( false );
1135  }
1136 
1138  {
1139  Repository system( sat::Pool::instance().findSystemRepo() );
1140  if ( system )
1141  system.eraseFromPool();
1142  }
1143 
1144  void TargetImpl::load( bool force )
1145  {
1146  bool newCache = buildCache();
1147  MIL << "New cache built: " << (newCache?"true":"false") <<
1148  ", force loading: " << (force?"true":"false") << endl;
1149 
1150  // now add the repos to the pool
1151  sat::Pool satpool( sat::Pool::instance() );
1152  Pathname rpmsolv( solvfilesPath() / "solv" );
1153  MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
1154 
1155  // Providing an empty system repo, unload any old content
1156  Repository system( sat::Pool::instance().findSystemRepo() );
1157 
1158  if ( system && ! system.solvablesEmpty() )
1159  {
1160  if ( newCache || force )
1161  {
1162  system.eraseFromPool(); // invalidates system
1163  }
1164  else
1165  {
1166  return; // nothing to do
1167  }
1168  }
1169 
1170  if ( ! system )
1171  {
1172  system = satpool.systemRepo();
1173  }
1174 
1175  try
1176  {
1177  MIL << "adding " << rpmsolv << " to system" << endl;
1178  system.addSolv( rpmsolv );
1179  }
1180  catch ( const Exception & exp )
1181  {
1182  ZYPP_CAUGHT( exp );
1183  MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1184  clearCache();
1185  buildCache();
1186 
1187  system.addSolv( rpmsolv );
1188  }
1189  satpool.rootDir( _root );
1190 
1191  // (Re)Load the requested locales et al.
1192  // If the requested locales are empty, we leave the pool untouched
1193  // to avoid undoing changes the application applied. We expect this
1194  // to happen on a bare metal installation only. An already existing
1195  // target should be loaded before its settings are changed.
1196  {
1198  if ( ! requestedLocales.empty() )
1199  {
1201  }
1202  }
1203  {
1204  if ( ! PathInfo( _autoInstalledFile.file() ).isExist() )
1205  {
1206  // Initialize from history, if it does not exist
1207  Pathname historyFile( Pathname::assertprefix( _root, ZConfig::instance().historyLogFile() ) );
1208  if ( PathInfo( historyFile ).isExist() )
1209  {
1210  SolvIdentFile::Data onSystemByUser( getUserInstalledFromHistory( historyFile ) );
1211  SolvIdentFile::Data onSystemByAuto;
1212  for_( it, system.solvablesBegin(), system.solvablesEnd() )
1213  {
1214  IdString ident( (*it).ident() );
1215  if ( onSystemByUser.find( ident ) == onSystemByUser.end() )
1216  onSystemByAuto.insert( ident );
1217  }
1218  _autoInstalledFile.setData( onSystemByAuto );
1219  }
1220  // on the fly removed any obsolete SoftLocks file
1221  filesystem::unlink( home() / "SoftLocks" );
1222  }
1223  // read from AutoInstalled file
1224  sat::StringQueue q;
1225  for ( const auto & idstr : _autoInstalledFile.data() )
1226  q.push( idstr.id() );
1227  satpool.setAutoInstalled( q );
1228  }
1229  if ( ZConfig::instance().apply_locks_file() )
1230  {
1231  const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1232  if ( ! hardLocks.empty() )
1233  {
1234  ResPool::instance().setHardLockQueries( hardLocks );
1235  }
1236  }
1237 
1238  // now that the target is loaded, we can cache the flavor
1240 
1241  MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1242  }
1243 
1245  //
1246  // COMMIT
1247  //
1250  {
1251  // ----------------------------------------------------------------- //
1252  ZYppCommitPolicy policy_r( policy_rX );
1253 
1254  // Fake outstanding YCP fix: Honour restriction to media 1
1255  // at installation, but install all remaining packages if post-boot.
1256  if ( policy_r.restrictToMedia() > 1 )
1257  policy_r.allMedia();
1258 
1259  if ( policy_r.downloadMode() == DownloadDefault ) {
1260  if ( root() == "/" )
1261  policy_r.downloadMode(DownloadInHeaps);
1262  else
1263  policy_r.downloadMode(DownloadAsNeeded);
1264  }
1265  // DownloadOnly implies dry-run.
1266  else if ( policy_r.downloadMode() == DownloadOnly )
1267  policy_r.dryRun( true );
1268  // ----------------------------------------------------------------- //
1269 
1270  MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1271 
1273  // Compute transaction:
1275  ZYppCommitResult result( root() );
1276  result.rTransaction() = pool_r.resolver().getTransaction();
1277  result.rTransaction().order();
1278  // steps: this is our todo-list
1280  if ( policy_r.restrictToMedia() )
1281  {
1282  // Collect until the 1st package from an unwanted media occurs.
1283  // Further collection could violate install order.
1284  MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1285  for_( it, result.transaction().begin(), result.transaction().end() )
1286  {
1287  if ( makeResObject( *it )->mediaNr() > 1 )
1288  break;
1289  steps.push_back( *it );
1290  }
1291  }
1292  else
1293  {
1294  result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1295  }
1296  MIL << "Todo: " << result << endl;
1297 
1299  // Prepare execution of commit plugins:
1301  CommitPlugins commitPlugins;
1302  if ( root() == "/" && ! policy_r.dryRun() )
1303  {
1304  Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
1305  commitPlugins.load( plugindir );
1306  }
1307  if ( ! commitPlugins.empty() )
1308  commitPlugins.send( transactionPluginFrame( "COMMITBEGIN", steps ) );
1309 
1311  // Write out a testcase if we're in dist upgrade mode.
1313  if ( getZYpp()->resolver()->upgradeMode() )
1314  {
1315  if ( ! policy_r.dryRun() )
1316  {
1318  }
1319  else
1320  {
1321  DBG << "dryRun: Not writing upgrade testcase." << endl;
1322  }
1323  }
1324 
1326  // Store non-package data:
1328  if ( ! policy_r.dryRun() )
1329  {
1331  // requested locales
1333  // autoinstalled
1334  {
1335  SolvIdentFile::Data newdata;
1336  for ( sat::Queue::value_type id : result.rTransaction().autoInstalled() )
1337  newdata.insert( IdString(id) );
1338  _autoInstalledFile.setData( newdata );
1339  }
1340  // hard locks
1341  if ( ZConfig::instance().apply_locks_file() )
1342  {
1343  HardLocksFile::Data newdata;
1344  pool_r.getHardLockQueries( newdata );
1345  _hardLocksFile.setData( newdata );
1346  }
1347  }
1348  else
1349  {
1350  DBG << "dryRun: Not stroring non-package data." << endl;
1351  }
1352 
1354  // First collect and display all messages
1355  // associated with patches to be installed.
1357  if ( ! policy_r.dryRun() )
1358  {
1359  for_( it, steps.begin(), steps.end() )
1360  {
1361  if ( ! it->satSolvable().isKind<Patch>() )
1362  continue;
1363 
1364  PoolItem pi( *it );
1365  if ( ! pi.status().isToBeInstalled() )
1366  continue;
1367 
1368  Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1369  if ( ! patch ||patch->message().empty() )
1370  continue;
1371 
1372  MIL << "Show message for " << patch << endl;
1374  if ( ! report->show( patch ) )
1375  {
1376  WAR << "commit aborted by the user" << endl;
1377  ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1378  }
1379  }
1380  }
1381  else
1382  {
1383  DBG << "dryRun: Not checking patch messages." << endl;
1384  }
1385 
1387  // Remove/install packages.
1389  DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1390  if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1391  {
1392  // Prepare the package cache. Pass all items requiring download.
1393  CommitPackageCache packageCache( root() );
1394  packageCache.setCommitList( steps.begin(), steps.end() );
1395 
1396  bool miss = false;
1397  if ( policy_r.downloadMode() != DownloadAsNeeded )
1398  {
1399  // Preload the cache. Until now this means pre-loading all packages.
1400  // Once DownloadInHeaps is fully implemented, this will change and
1401  // we may actually have more than one heap.
1402  for_( it, steps.begin(), steps.end() )
1403  {
1404  switch ( it->stepType() )
1405  {
1408  // proceed: only install actionas may require download.
1409  break;
1410 
1411  default:
1412  // next: no download for or non-packages and delete actions.
1413  continue;
1414  break;
1415  }
1416 
1417  PoolItem pi( *it );
1418  if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1419  {
1420  ManagedFile localfile;
1421  try
1422  {
1423  // TODO: unify packageCache.get for Package and SrcPackage
1424  if ( pi->isKind<Package>() )
1425  {
1426  localfile = packageCache.get( pi );
1427  }
1428  else if ( pi->isKind<SrcPackage>() )
1429  {
1430  repo::RepoMediaAccess access;
1431  repo::SrcPackageProvider prov( access );
1432  localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1433  }
1434  else
1435  {
1436  INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1437  continue;
1438  }
1439  localfile.resetDispose(); // keep the package file in the cache
1440  }
1441  catch ( const AbortRequestException & exp )
1442  {
1443  it->stepStage( sat::Transaction::STEP_ERROR );
1444  miss = true;
1445  WAR << "commit cache preload aborted by the user" << endl;
1446  ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1447  break;
1448  }
1449  catch ( const SkipRequestException & exp )
1450  {
1451  ZYPP_CAUGHT( exp );
1452  it->stepStage( sat::Transaction::STEP_ERROR );
1453  miss = true;
1454  WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1455  continue;
1456  }
1457  catch ( const Exception & exp )
1458  {
1459  // bnc #395704: missing catch causes abort.
1460  // TODO see if packageCache fails to handle errors correctly.
1461  ZYPP_CAUGHT( exp );
1462  it->stepStage( sat::Transaction::STEP_ERROR );
1463  miss = true;
1464  INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1465  continue;
1466  }
1467  }
1468  }
1469  packageCache.preloaded( true ); // try to avoid duplicate infoInCache CBs in commit
1470  }
1471 
1472  if ( miss )
1473  {
1474  ERR << "Some packages could not be provided. Aborting commit."<< endl;
1475  }
1476  else
1477  {
1478  if ( ! policy_r.dryRun() )
1479  {
1480  // if cache is preloaded, check for file conflicts
1481  commitFindFileConflicts( policy_r, result );
1482  commit( policy_r, packageCache, result );
1483  }
1484  else
1485  {
1486  DBG << "dryRun/downloadOnly: Not installing/deleting anything." << endl;
1487  }
1488  }
1489  }
1490  else
1491  {
1492  DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1493  }
1494 
1496  // Send result to commit plugins:
1498  if ( ! commitPlugins.empty() )
1499  commitPlugins.send( transactionPluginFrame( "COMMITEND", steps ) );
1500 
1502  // Try to rebuild solv file while rpm database is still in cache
1504  if ( ! policy_r.dryRun() )
1505  {
1506  buildCache();
1507  }
1508 
1509  MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1510  return result;
1511  }
1512 
1514  //
1515  // COMMIT internal
1516  //
1518  namespace
1519  {
1520  struct NotifyAttemptToModify
1521  {
1522  NotifyAttemptToModify( ZYppCommitResult & result_r ) : _result( result_r ) {}
1523 
1524  void operator()()
1525  { if ( _guard ) { _result.attemptToModify( true ); _guard = false; } }
1526 
1527  TrueBool _guard;
1528  ZYppCommitResult & _result;
1529  };
1530  } // namespace
1531 
1532  void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1533  CommitPackageCache & packageCache_r,
1534  ZYppCommitResult & result_r )
1535  {
1536  // steps: this is our todo-list
1538  MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1539 
1541 
1542  // Send notification once upon 1st call to rpm
1543  NotifyAttemptToModify attemptToModify( result_r );
1544 
1545  bool abort = false;
1546 
1547  RpmPostTransCollector postTransCollector( _root );
1548  std::vector<sat::Solvable> successfullyInstalledPackages;
1549  TargetImpl::PoolItemList remaining;
1550 
1551  for_( step, steps.begin(), steps.end() )
1552  {
1553  PoolItem citem( *step );
1554  if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1555  {
1556  if ( citem->isKind<Package>() )
1557  {
1558  // for packages this means being obsoleted (by rpm)
1559  // thius no additional action is needed.
1560  step->stepStage( sat::Transaction::STEP_DONE );
1561  continue;
1562  }
1563  }
1564 
1565  if ( citem->isKind<Package>() )
1566  {
1567  Package::constPtr p = citem->asKind<Package>();
1568  if ( citem.status().isToBeInstalled() )
1569  {
1570  ManagedFile localfile;
1571  try
1572  {
1573  localfile = packageCache_r.get( citem );
1574  }
1575  catch ( const AbortRequestException &e )
1576  {
1577  WAR << "commit aborted by the user" << endl;
1578  abort = true;
1579  step->stepStage( sat::Transaction::STEP_ERROR );
1580  break;
1581  }
1582  catch ( const SkipRequestException &e )
1583  {
1584  ZYPP_CAUGHT( e );
1585  WAR << "Skipping package " << p << " in commit" << endl;
1586  step->stepStage( sat::Transaction::STEP_ERROR );
1587  continue;
1588  }
1589  catch ( const Exception &e )
1590  {
1591  // bnc #395704: missing catch causes abort.
1592  // TODO see if packageCache fails to handle errors correctly.
1593  ZYPP_CAUGHT( e );
1594  INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1595  step->stepStage( sat::Transaction::STEP_ERROR );
1596  continue;
1597  }
1598 
1599 #warning Exception handling
1600  // create a installation progress report proxy
1601  RpmInstallPackageReceiver progress( citem.resolvable() );
1602  progress.connect(); // disconnected on destruction.
1603 
1604  bool success = false;
1605  rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1606  // Why force and nodeps?
1607  //
1608  // Because zypp builds the transaction and the resolver asserts that
1609  // everything is fine.
1610  // We use rpm just to unpack and register the package in the database.
1611  // We do this step by step, so rpm is not aware of the bigger context.
1612  // So we turn off rpms internal checks, because we do it inside zypp.
1613  flags |= rpm::RPMINST_NODEPS;
1614  flags |= rpm::RPMINST_FORCE;
1615  //
1616  if (p->multiversionInstall()) flags |= rpm::RPMINST_NOUPGRADE;
1617  if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1618  if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1619  if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1620 
1621  attemptToModify();
1622  try
1623  {
1625  if ( postTransCollector.collectScriptFromPackage( localfile ) )
1626  flags |= rpm::RPMINST_NOPOSTTRANS;
1627  rpm().installPackage( localfile, flags );
1628  HistoryLog().install(citem);
1629 
1630  if ( progress.aborted() )
1631  {
1632  WAR << "commit aborted by the user" << endl;
1633  localfile.resetDispose(); // keep the package file in the cache
1634  abort = true;
1635  step->stepStage( sat::Transaction::STEP_ERROR );
1636  break;
1637  }
1638  else
1639  {
1640  success = true;
1641  step->stepStage( sat::Transaction::STEP_DONE );
1642  }
1643  }
1644  catch ( Exception & excpt_r )
1645  {
1646  ZYPP_CAUGHT(excpt_r);
1647  localfile.resetDispose(); // keep the package file in the cache
1648 
1649  if ( policy_r.dryRun() )
1650  {
1651  WAR << "dry run failed" << endl;
1652  step->stepStage( sat::Transaction::STEP_ERROR );
1653  break;
1654  }
1655  // else
1656  if ( progress.aborted() )
1657  {
1658  WAR << "commit aborted by the user" << endl;
1659  abort = true;
1660  }
1661  else
1662  {
1663  WAR << "Install failed" << endl;
1664  }
1665  step->stepStage( sat::Transaction::STEP_ERROR );
1666  break; // stop
1667  }
1668 
1669  if ( success && !policy_r.dryRun() )
1670  {
1672  successfullyInstalledPackages.push_back( citem.satSolvable() );
1673  step->stepStage( sat::Transaction::STEP_DONE );
1674  }
1675  }
1676  else
1677  {
1678  RpmRemovePackageReceiver progress( citem.resolvable() );
1679  progress.connect(); // disconnected on destruction.
1680 
1681  bool success = false;
1682  rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1683  flags |= rpm::RPMINST_NODEPS;
1684  if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1685 
1686  attemptToModify();
1687  try
1688  {
1689  rpm().removePackage( p, flags );
1690  HistoryLog().remove(citem);
1691 
1692  if ( progress.aborted() )
1693  {
1694  WAR << "commit aborted by the user" << endl;
1695  abort = true;
1696  step->stepStage( sat::Transaction::STEP_ERROR );
1697  break;
1698  }
1699  else
1700  {
1701  success = true;
1702  step->stepStage( sat::Transaction::STEP_DONE );
1703  }
1704  }
1705  catch (Exception & excpt_r)
1706  {
1707  ZYPP_CAUGHT( excpt_r );
1708  if ( progress.aborted() )
1709  {
1710  WAR << "commit aborted by the user" << endl;
1711  abort = true;
1712  step->stepStage( sat::Transaction::STEP_ERROR );
1713  break;
1714  }
1715  // else
1716  WAR << "removal of " << p << " failed";
1717  step->stepStage( sat::Transaction::STEP_ERROR );
1718  }
1719  if ( success && !policy_r.dryRun() )
1720  {
1722  step->stepStage( sat::Transaction::STEP_DONE );
1723  }
1724  }
1725  }
1726  else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1727  {
1728  // Status is changed as the buddy package buddy
1729  // gets installed/deleted. Handle non-buddies only.
1730  if ( ! citem.buddy() )
1731  {
1732  if ( citem->isKind<Product>() )
1733  {
1734  Product::constPtr p = citem->asKind<Product>();
1735  if ( citem.status().isToBeInstalled() )
1736  {
1737  ERR << "Can't install orphan product without release-package! " << citem << endl;
1738  }
1739  else
1740  {
1741  // Deleting the corresponding product entry is all we con do.
1742  // So the product will no longer be visible as installed.
1743  std::string referenceFilename( p->referenceFilename() );
1744  if ( referenceFilename.empty() )
1745  {
1746  ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1747  }
1748  else
1749  {
1750  PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1751  if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1752  {
1753  ERR << "Delete orphan product failed: " << referenceFile << endl;
1754  }
1755  }
1756  }
1757  }
1758  else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1759  {
1760  // SrcPackage is install-only
1761  SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1762  installSrcPackage( p );
1763  }
1764 
1766  step->stepStage( sat::Transaction::STEP_DONE );
1767  }
1768 
1769  } // other resolvables
1770 
1771  } // for
1772 
1773  // process all remembered posttrans scripts.
1774  if ( !abort )
1775  postTransCollector.executeScripts();
1776  else
1777  postTransCollector.discardScripts();
1778 
1779  // Check presence of update scripts/messages. If aborting,
1780  // at least log omitted scripts.
1781  if ( ! successfullyInstalledPackages.empty() )
1782  {
1783  if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1784  successfullyInstalledPackages, abort ) )
1785  {
1786  WAR << "Commit aborted by the user" << endl;
1787  abort = true;
1788  }
1789  // send messages after scripts in case some script generates output,
1790  // that should be kept in t %ghost message file.
1791  RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1792  successfullyInstalledPackages,
1793  result_r );
1794  }
1795 
1796  if ( abort )
1797  {
1798  ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1799  }
1800  }
1801 
1803 
1805  {
1806  return _rpm;
1807  }
1808 
1809  bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1810  {
1811  return _rpm.hasFile(path_str, name_str);
1812  }
1813 
1814 
1816  {
1817  return _rpm.timestamp();
1818  }
1819 
1821  namespace
1822  {
1823  parser::ProductFileData baseproductdata( const Pathname & root_r )
1824  {
1826  PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1827 
1828  if ( baseproduct.isFile() )
1829  {
1830  try
1831  {
1832  ret = parser::ProductFileReader::scanFile( baseproduct.path() );
1833  }
1834  catch ( const Exception & excpt )
1835  {
1836  ZYPP_CAUGHT( excpt );
1837  }
1838  }
1839  else if ( PathInfo( Pathname::assertprefix( root_r, "/etc/products.d" ) ).isDir() )
1840  {
1841  ERR << "baseproduct symlink is dangling or missing: " << baseproduct << endl;
1842  }
1843  return ret;
1844  }
1845 
1846  inline Pathname staticGuessRoot( const Pathname & root_r )
1847  {
1848  if ( root_r.empty() )
1849  {
1850  // empty root: use existing Target or assume "/"
1851  Pathname ret ( ZConfig::instance().systemRoot() );
1852  if ( ret.empty() )
1853  return Pathname("/");
1854  return ret;
1855  }
1856  return root_r;
1857  }
1858 
1859  inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1860  {
1861  std::ifstream idfile( file_r.c_str() );
1862  for( iostr::EachLine in( idfile ); in; in.next() )
1863  {
1864  std::string line( str::trim( *in ) );
1865  if ( ! line.empty() )
1866  return line;
1867  }
1868  return std::string();
1869  }
1870  } // namescpace
1872 
1874  {
1875  ResPool pool(ResPool::instance());
1876  for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1877  {
1878  Product::constPtr p = (*it)->asKind<Product>();
1879  if ( p->isTargetDistribution() )
1880  return p;
1881  }
1882  return nullptr;
1883  }
1884 
1885  LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1886  {
1887  const Pathname needroot( staticGuessRoot(root_r) );
1888  const Target_constPtr target( getZYpp()->getTarget() );
1889  if ( target && target->root() == needroot )
1890  return target->requestedLocales();
1891  return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1892  }
1893 
1895  { return baseproductdata( _root ).registerTarget(); }
1896  // static version:
1897  std::string TargetImpl::targetDistribution( const Pathname & root_r )
1898  { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1899 
1901  { return baseproductdata( _root ).registerRelease(); }
1902  // static version:
1903  std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1904  { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1905 
1907  { return baseproductdata( _root ).registerFlavor(); }
1908  // static version:
1909  std::string TargetImpl::targetDistributionFlavor( const Pathname & root_r )
1910  { return baseproductdata( staticGuessRoot(root_r) ).registerFlavor();}
1911 
1913  {
1915  parser::ProductFileData pdata( baseproductdata( _root ) );
1916  ret.shortName = pdata.shortName();
1917  ret.summary = pdata.summary();
1918  return ret;
1919  }
1920  // static version:
1922  {
1924  parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1925  ret.shortName = pdata.shortName();
1926  ret.summary = pdata.summary();
1927  return ret;
1928  }
1929 
1931  {
1932  if ( _distributionVersion.empty() )
1933  {
1935  if ( !_distributionVersion.empty() )
1936  MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1937  }
1938  return _distributionVersion;
1939  }
1940  // static version
1941  std::string TargetImpl::distributionVersion( const Pathname & root_r )
1942  {
1943  std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1944  if ( distributionVersion.empty() )
1945  {
1946  // ...But the baseproduct method is not expected to work on RedHat derivatives.
1947  // On RHEL, Fedora and others the "product version" is determined by the first package
1948  // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1949  // with the $distroverpkg variable.
1950  scoped_ptr<rpm::RpmDb> tmprpmdb;
1951  if ( ZConfig::instance().systemRoot() == Pathname() )
1952  {
1953  try
1954  {
1955  tmprpmdb.reset( new rpm::RpmDb );
1956  tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1957  }
1958  catch( ... )
1959  {
1960  return "";
1961  }
1962  }
1965  distributionVersion = it->tag_version();
1966  }
1967  return distributionVersion;
1968  }
1969 
1970 
1972  {
1973  return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1974  }
1975  // static version:
1976  std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1977  {
1978  return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1979  }
1980 
1982 
1983  std::string TargetImpl::anonymousUniqueId() const
1984  {
1985  return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1986  }
1987  // static version:
1988  std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1989  {
1990  return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1991  }
1992 
1994 
1995  void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1996  {
1997  // provide on local disk
1998  ManagedFile localfile = provideSrcPackage(srcPackage_r);
1999  // create a installation progress report proxy
2000  RpmInstallPackageReceiver progress( srcPackage_r );
2001  progress.connect(); // disconnected on destruction.
2002  // install it
2003  rpm().installPackage ( localfile );
2004  }
2005 
2006  ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
2007  {
2008  // provide on local disk
2009  repo::RepoMediaAccess access_r;
2010  repo::SrcPackageProvider prov( access_r );
2011  return prov.provideSrcPackage( srcPackage_r );
2012  }
2014  } // namespace target
2017 } // namespace zypp
void saveToCookieFile(const Pathname &path_r) const
Save the status information to a cookie file.
Definition: RepoStatus.cc:126
std::string asString(const Patch::Category &obj)
Definition: Patch.cc:117
StringQueue autoInstalled() const
Return the ident strings of all packages that would be auto-installed after the transaction is run...
Definition: Transaction.cc:356
static bool fileMissing(const Pathname &pathname)
helper functor
Definition: TargetImpl.cc:890
ZYppCommitResult commit(ResPool pool_r, const ZYppCommitPolicy &policy_r)
Commit changes in the pool.
Definition: TargetImpl.cc:1249
unsigned splitEscaped(const C_Str &line_r, TOutputIterator result_r, const C_Str &sepchars_r=" \t", bool withEmpty=false)
Split line_r into words with respect to escape delimeters.
Definition: String.h:577
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
Definition: PathInfo.cc:320
std::string asJSON() const
JSON representation.
Definition: Json.h:344
std::string shortName() const
Interface to gettext.
Interface to the rpm program.
Definition: RpmDb.h:47
Product interface.
Definition: Product.h:32
#define MIL
Definition: Logger.h:64
sat::Transaction getTransaction()
Return the Transaction computed by the last solver run.
Definition: Resolver.cc:74
CommitPlugins()
Default ctor: Empty plugin list.
Definition: TargetImpl.cc:241
A Solvable object within the sat Pool.
Definition: Solvable.h:53
std::vector< sat::Transaction::Step > TransactionStepList
Save and restore locale set from file.
Alternating download and install.
Definition: DownloadMode.h:32
Target::DistributionLabel distributionLabel() const
This is shortName and summary attribute of the installed base product.
Definition: TargetImpl.cc:1912
ZYppCommitPolicy & rpmNoSignature(bool yesNo_r)
Use rpm option –nosignature (default: false)
[M] Install(multiversion) item (
Definition: Transaction.h:67
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:321
byKind_iterator byKindBegin(const ResKind &kind_r) const
Definition: ResPool.h:261
Result returned from ZYpp::commit.
static ZConfig & instance()
Singleton ctor.
Definition: Resolver.cc:121
Pathname path() const
Definition: TmpPath.cc:146
void addSolv(const Pathname &file_r)
Load Solvables from a solv-file.
Definition: Repository.cc:320
const std::string & asString() const
Definition: Arch.cc:471
std::string md5sum(const Pathname &file)
Compute a files md5sum.
Definition: PathInfo.cc:947
Command frame for communication with PluginScript.
Definition: PluginFrame.h:40
Pathname home() const
The directory to store things.
Definition: TargetImpl.h:120
std::string distroverpkg() const
Package telling the "product version" on systems not using /etc/product.d/baseproduct.
Definition: ZConfig.cc:1099
bool findByProvides(const std::string &tag_r)
Reset to iterate all packages that provide a certain tag.
Definition: librpmDb.cc:826
int readlink(const Pathname &symlink_r, Pathname &target_r)
Like 'readlink'.
Definition: PathInfo.cc:847
void setData(const Data &data_r)
Store new Data.
Definition: SolvIdentFile.h:69
SolvIdentFile _autoInstalledFile
user/auto installed database
Definition: TargetImpl.h:216
detail::IdType value_type
Definition: Queue.h:38
Architecture.
Definition: Arch.h:36
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:855
void stampCommand()
Log info about the current process.
Definition: HistoryLog.cc:220
std::string release() const
Release.
Definition: Edition.cc:110
Target::commit helper optimizing package provision.
const std::string & asString() const
String representation.
Definition: Pathname.h:90
const std::string & command() const
The command we're executing.
bool isEnomethodCommand() const
Convenience to identify an _ENOMETHOD command.
Definition: PluginFrame.h:114
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
void discardScripts()
Discard all remembered scrips.
Pathname root() const
The root set for this target.
Definition: TargetImpl.h:116
#define INT
Definition: Logger.h:68
int chmod(const Pathname &path, mode_t mode)
Like 'chmod'.
Definition: PathInfo.cc:1015
void installPackage(const Pathname &filename, RpmInstFlags flags=RPMINST_NONE)
install rpm package
Definition: RpmDb.cc:1892
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:220
void commitFindFileConflicts(const ZYppCommitPolicy &policy_r, ZYppCommitResult &result_r)
Commit helper checking for file conflicts after download.
void setData(const Data &data_r)
Store new Data.
Definition: HardLocksFile.h:73
void setAutoInstalled(const Queue &autoInstalled_r)
Set ident list of all autoinstalled solvables.
Definition: Pool.cc:244
const std::string & asString(const std::string &t)
Global asString() that works with std::string too.
Definition: String.h:136
SolvableIterator solvablesEnd() const
Iterator behind the last Solvable.
Definition: Repository.cc:241
void load(const Pathname &path_r)
Find and launch plugins sending PLUGINSTART message.
Definition: TargetImpl.cc:280
Access to the sat-pools string space.
Definition: IdString.h:41
Libsolv transaction wrapper.
Definition: Transaction.h:51
#define for_(IT, BEG, END)
Convenient for-loops using iterator.
Definition: Easy.h:27
Edition represents [epoch:]version[-release]
Definition: Edition.h:60
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
unsigned epoch_t
Type of an epoch.
Definition: Edition.h:64
void writeUpgradeTestcase()
Definition: TargetImpl.cc:390
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
Definition: String.cc:36
static RepoStatus fromCookieFile(const Pathname &path)
Reads the status from a cookie file.
Definition: RepoStatus.cc:108
byKind_iterator byKindEnd(const ResKind &kind_r) const
Definition: ResPool.h:268
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:1995
bool isKind(const ResKind &kind_r) const
Definition: SolvableType.h:64
LocaleSet requestedLocales() const
Languages to be supported by the system.
Definition: TargetImpl.h:160
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:232
#define ERR
Definition: Logger.h:66
std::string distributionVersion() const
This is version attribute of the installed base product.
Definition: TargetImpl.cc:1930
JSON object.
Definition: Json.h:321
std::vector< std::string > Arguments
PluginFrame doSend(PluginScript &script_r, const PluginFrame &frame_r)
Send PluginFrame and expect valid answer (ACK|_ENOMETHOD).
Definition: TargetImpl.cc:319
std::string asString() const
Conversion to std::string
Definition: IdString.h:91
Extract and remember posttrans scripts for later execution.
const_iterator begin() const
Iterator to the first TransactionStep.
Definition: Transaction.cc:335
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
StepStage stepStage() const
Step action result.
Definition: Transaction.cc:389
rpm::RpmDb _rpm
RPM database.
Definition: TargetImpl.h:212
Repository systemRepo()
Return the system repository, create it if missing.
Definition: Pool.cc:157
Date timestamp() const
return the last modification date of the target
Definition: TargetImpl.cc:1815
void initRequestedLocales(const LocaleSet &locales_r)
Start tracking changes based on this locales_r.
Definition: Pool.cc:230
[ ] Nothing (includes implicit deletes due to obsoletes and non-package actions)
Definition: Transaction.h:64
ResObject::constPtr resolvable() const
Returns the ResObject::constPtr.
Definition: PoolItem.cc:217
int addmod(const Pathname &path, mode_t mode)
Add the mode bits to the file given by path.
Definition: PathInfo.cc:1024
void push(value_type val_r)
Push a value to the end off the Queue.
Definition: Queue.cc:103
const Data & data() const
Return the data.
Definition: SolvIdentFile.h:53
std::string getline(std::istream &str)
Read one line from stream.
Definition: IOStream.cc:33
StepType stepType() const
Type of action to perform in this step.
Definition: Transaction.cc:386
boost::noncopyable NonCopyable
Ensure derived classes cannot be copied.
Definition: NonCopyable.h:26
Store and operate on date (time_t).
Definition: Date.h:32
static Pool instance()
Singleton ctor.
Definition: Pool.h:53
SolvableIterator solvablesBegin() const
Iterator to the first Solvable.
Definition: Repository.cc:231
Pathname _root
Path to the target.
Definition: TargetImpl.h:210
~CommitPlugins()
Dtor: Send PLUGINEND message and close plugins.
Definition: TargetImpl.cc:245
Pathname defaultSolvfilesPath() const
The systems default solv file location.
Definition: TargetImpl.cc:964
bool empty() const
Whether no plugins are waiting.
Definition: TargetImpl.cc:253
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:221
int unlink(const Pathname &path)
Like 'unlink'.
Definition: PathInfo.cc:653
static const std::string & systemRepoAlias()
Reserved system repository alias .
Definition: Pool.cc:46
bool collectScriptFromPackage(ManagedFile rpmPackage_r)
Extract and remember a packages posttrans script for later execution.
static const Pathname & fname()
Get the current log file path.
Definition: HistoryLog.cc:179
int rename(const Pathname &oldpath, const Pathname &newpath)
Like 'rename'.
Definition: PathInfo.cc:667
Just download all packages to the local cache.
Definition: DownloadMode.h:25
Options and policies for ZYpp::commit.
void send(const PluginFrame &frame_r)
Send PluginFrame to all open plugins.
Definition: TargetImpl.cc:260
libzypp will decide what to do.
Definition: DownloadMode.h:24
bool solvfilesPathIsTemp() const
Whether we're using a temp.
Definition: TargetImpl.h:96
A single step within a Transaction.
Definition: Transaction.h:216
Package interface.
Definition: Package.h:32
ZYppCommitPolicy & downloadMode(DownloadMode val_r)
Commit download policy to use.
RequestedLocalesFile _requestedLocalesFile
Requested Locales database.
Definition: TargetImpl.h:214
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:1809
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:101
#define USR
Definition: Logger.h:69
int recursive_rmdir(const Pathname &path)
Like 'rm -r DIR'.
Definition: PathInfo.cc:413
Interim helper class to collect global options and settings.
Definition: ZConfig.h:59
#define WAR
Definition: Logger.h:65
bool isAckCommand() const
Convenience to identify an ACK command.
Definition: PluginFrame.h:106
void createLastDistributionFlavorCache() const
generates a cache of the last product flavor
Definition: TargetImpl.cc:915
std::string targetDistributionFlavor() const
This is register.flavor attribute of the installed base product.
Definition: TargetImpl.cc:1906
bool startsWith(const C_Str &str_r, const C_Str &prefix_r)
alias for hasPrefix
Definition: String.h:1057
epoch_t epoch() const
Epoch.
Definition: Edition.cc:82
std::string version() const
Version.
Definition: Edition.cc:94
Pathname rootDir() const
Get rootdir (for file conflicts check)
Definition: Pool.cc:64
ResStatus & status() const
Returns the current status.
Definition: PoolItem.cc:204
const LocaleSet & getRequestedLocales() const
Return the requested locales.
Definition: ResPool.cc:125
bool order()
Order transaction steps for commit.
Definition: Transaction.cc:326
void updateSolvFileIndex(const Pathname &solvfile_r)
Create solv file content digest for zypper bash completion.
Definition: Pool.cc:263
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
JSON array.
Definition: Json.h:256
Pathname solvfilesPath() const
The solv file location actually in use (default or temp).
Definition: TargetImpl.h:92
#define _(MSG)
Definition: Gettext.h:29
std::string receiveLine()
Read one line from the input stream.
void closeDatabase()
Block further access to the rpm database and go back to uninitialized state.
Definition: RpmDb.cc:729
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:1983
bool solvablesEmpty() const
Whether Repository contains solvables.
Definition: Repository.cc:219
PluginFrame receive() const
Receive a PluginFrame.
std::string toLower(const std::string &s)
Return lowercase version of s.
Definition: String.cc:175
static std::string generateRandomId()
generates a random id using uuidgen
Definition: TargetImpl.cc:844
void resetDispose()
Set no dispose function.
Definition: AutoDispose.h:162
Provides files from different repos.
ManagedFile get(const PoolItem &citem_r)
Provide a package.
HardLocksFile _hardLocksFile
Hard-Locks database.
Definition: TargetImpl.h:218
SolvableIdType size_type
Definition: PoolMember.h:126
Solvable satSolvable() const
Return the corresponding Solvable.
Definition: Transaction.h:241
std::string asJSON() const
JSON representation.
Definition: Json.h:279
void testCommitPlugins(const Pathname &path_r)
Definition: TargetImpl.cc:366
static void setRoot(const Pathname &root)
Set new root directory to the default history log file path.
Definition: HistoryLog.cc:163
std::string targetDistribution() const
This is register.target attribute of the installed base product.
Definition: TargetImpl.cc:1894
int close()
Wait for the progamm to complete.
size_type solvablesSize() const
Number of solvables in Repository.
Definition: Repository.cc:225
void setHardLockQueries(const HardLockQueries &newLocks_r)
Set a new set of queries.
Definition: ResPool.cc:98
#define SUBST_IF(PAT, VAL)
std::list< UpdateNotificationFile > UpdateNotifications
Libsolv Id queue wrapper.
Definition: Queue.h:34
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
Definition: Exception.h:325
int readdir(std::list< std::string > &retlist_r, const Pathname &path_r, bool dots_r)
Return content of directory via retlist.
Definition: PathInfo.cc:589
void doLoad(const PathInfo &pi_r)
Launch a plugin sending PLUGINSTART message.
Definition: TargetImpl.cc:341
const LocaleSet & locales() const
Return the loacale set.
SrcPackage interface.
Definition: SrcPackage.h:29
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:1971
sat::Solvable buddy() const
Return the buddy we share our status object with.
Definition: PoolItem.cc:206
Global ResObject pool.
Definition: ResPool.h:60
Pathname systemRoot() const
The target root directory.
Definition: ZConfig.cc:805
ZYppCommitPolicy & allMedia()
Process all media (default)
pool::PoolTraits::HardLockQueries Data
Definition: HardLocksFile.h:41
const sat::Transaction & transaction() const
The full transaction list.
void add(const Value &val_r)
Push JSON Value to Array.
Definition: Json.h:271
int close()
Close any open connection.
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:341
void remove(const PoolItem &pi)
Log removal of a package.
Definition: HistoryLog.cc:261
Product::constPtr baseProduct() const
returns the target base installed product, also known as the distribution or platform.
Definition: TargetImpl.cc:1873
callback::SendReport< DownloadProgressReport > * report
Definition: MediaCurl.cc:177
Solvable satSolvable() const
Return the corresponding sat::Solvable.
Definition: SolvableType.h:57
void initDatabase(Pathname root_r=Pathname(), Pathname dbPath_r=Pathname(), bool doRebuild_r=false)
Prepare access to the rpm database.
Definition: RpmDb.cc:331
void removePackage(const std::string &name_r, RpmInstFlags flags=RPMINST_NONE)
remove rpm package
Definition: RpmDb.cc:2080
virtual ~TargetImpl()
Dtor.
Definition: TargetImpl.cc:951
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
Definition: AutoDispose.h:92
void eraseFromPool()
Remove this Repository from it's Pool.
Definition: Repository.cc:297
Global sat-pool.
Definition: Pool.h:44
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:1302
void comment(const std::string &comment, bool timestamp=false)
Log a comment (even multiline).
Definition: HistoryLog.cc:188
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:277
ResObject::Ptr makeResObject(const sat::Solvable &solvable_r)
Create ResObject from sat::Solvable.
Definition: ResObject.cc:44
Helper for commit plugin execution.
Definition: TargetImpl.cc:237
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:319
Combining sat::Solvable and ResStatus.
Definition: PoolItem.h:50
void executeScripts()
Execute te remembered scripts.
ManagedFile provideSrcPackage(const SrcPackage_constPtr &srcPackage_r)
Provides a source package on the Target.
Definition: TargetImpl.cc:2006
static TmpFile makeSibling(const Pathname &sibling_r)
Provide a new empty temporary directory as sibling.
Definition: TmpPath.cc:218
Track changing files or directories.
Definition: RepoStatus.h:38
std::string toJSON(const sat::Transaction::Step &step_r)
See COMMITBEGIN (added in v1) on page Commit plugin for the specs.
Definition: TargetImpl.cc:98
void XRunUpdateMessages(const Pathname &root_r, const Pathname &messagesPath_r, const std::vector< sat::Solvable > &checkPackages_r, ZYppCommitResult &result_r)
Definition: TargetImpl.cc:811
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:1900
std::unordered_set< IdString > Data
Definition: SolvIdentFile.h:37
#define idstr(V)
void add(const String &key_r, const Value &val_r)
Add key/value pair.
Definition: Json.h:336
bool hasPrefix(const C_Str &str_r, const C_Str &prefix_r)
Return whether str_r has prefix prefix_r.
Definition: String.h:1027
void createAnonymousId() const
generates the unique anonymous id which is called when creating the target
Definition: TargetImpl.cc:895
void send(const PluginFrame &frame_r) const
Send a PluginFrame.
bool empty() const
Whether this is an empty object without valid data.
detail::Dump< Tp > dump(const Tp &obj_r)
Definition: LogTools.h:384
void setCommitList(std::vector< sat::Solvable > commitList_r)
Download(commit) sequence of solvables to compute read ahead.
const Pathname & file() const
Return the file path.
Definition: SolvIdentFile.h:46
std::unordered_set< Locale > LocaleSet
Definition: Locale.h:27
TrueBool _guard
Definition: TargetImpl.cc:1527
rpm::RpmDb & rpm()
The RPM database.
Definition: TargetImpl.cc:1804
TraitsType::constPtrType constPtr
Definition: Package.h:38
#define IMPL_PTR_TYPE(NAME)
#define DBG
Definition: Logger.h:63
bool preloaded() const
Whether preloaded hint is set.
ZYppCommitResult & _result
Definition: TargetImpl.cc:1528
static ResPool instance()
Singleton ctor.
Definition: ResPool.cc:33
std::list< PluginScript > _scripts
Definition: TargetImpl.cc:363
void load(bool force=true)
Definition: TargetImpl.cc:1144