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