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