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