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