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