Target::reload() added
[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     bool 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       return build_rpm_solv;
962     }
963
964     void TargetImpl::reload()
965     {
966         load( false );
967     }
968
969     void TargetImpl::unload()
970     {
971       Repository system( sat::Pool::instance().findSystemRepo() );
972       if ( system )
973         system.eraseFromPool();
974     }
975
976     void TargetImpl::load( bool force )
977     {
978       bool newCache = buildCache();
979       MIL << "New cache built: " << (newCache?"true":"false") <<
980         ", force loading: " << (force?"true":"false") << endl;
981  
982       // now add the repos to the pool
983       sat::Pool satpool( sat::Pool::instance() );
984       Pathname rpmsolv( solvfilesPath() / "solv" );
985       MIL << "adding " << rpmsolv << " to pool(" << satpool.systemRepoAlias() << ")" << endl;
986
987       // Providing an empty system repo, unload any old content
988       Repository system( sat::Pool::instance().findSystemRepo() );
989
990       if ( system && ! system.solvablesEmpty() )
991       {
992         if ( newCache || force )
993         {
994           system.eraseFromPool(); // invalidates system
995         }
996         else
997         {
998           return;     // nothing to do
999         }
1000       }
1001       
1002       if ( ! system )
1003       {
1004         system = satpool.systemRepo();
1005       }
1006
1007       try
1008       {
1009         MIL << "adding " << rpmsolv << " to system" << endl;
1010         system.addSolv( rpmsolv );
1011       }
1012       catch ( const Exception & exp )
1013       {
1014         ZYPP_CAUGHT( exp );
1015         MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1016         clearCache();
1017         buildCache();
1018
1019         system.addSolv( rpmsolv );
1020       }
1021
1022       // (Re)Load the requested locales et al.
1023       // If the requested locales are empty, we leave the pool untouched
1024       // to avoid undoing changes the application applied. We expect this
1025       // to happen on a bare metal installation only. An already existing
1026       // target should be loaded before its settings are changed.
1027       {
1028         const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
1029         if ( ! requestedLocales.empty() )
1030         {
1031           satpool.setRequestedLocales( requestedLocales );
1032         }
1033       }
1034       {
1035         SoftLocksFile::Data softLocks( _softLocksFile.data() );
1036         if ( ! softLocks.empty() )
1037         {
1038           // Don't soft lock any installed item.
1039           for_( it, system.solvablesBegin(), system.solvablesEnd() )
1040           {
1041             softLocks.erase( it->ident() );
1042           }
1043           ResPool::instance().setAutoSoftLocks( softLocks );
1044         }
1045       }
1046       if ( ZConfig::instance().apply_locks_file() )
1047       {
1048         const HardLocksFile::Data & hardLocks( _hardLocksFile.data() );
1049         if ( ! hardLocks.empty() )
1050         {
1051           ResPool::instance().setHardLockQueries( hardLocks );
1052         }
1053       }
1054
1055       // now that the target is loaded, we can cache the flavor
1056       createLastDistributionFlavorCache();
1057
1058       MIL << "Target loaded: " << system.solvablesSize() << " resolvables" << endl;
1059     }
1060
1061     ///////////////////////////////////////////////////////////////////
1062     //
1063     // COMMIT
1064     //
1065     ///////////////////////////////////////////////////////////////////
1066     ZYppCommitResult TargetImpl::commit( ResPool pool_r, const ZYppCommitPolicy & policy_rX )
1067     {
1068       // ----------------------------------------------------------------- //
1069       ZYppCommitPolicy policy_r( policy_rX );
1070
1071       // Fake outstanding YCP fix: Honour restriction to media 1
1072       // at installation, but install all remaining packages if post-boot.
1073       if ( policy_r.restrictToMedia() > 1 )
1074         policy_r.allMedia();
1075
1076       if ( policy_r.downloadMode() == DownloadDefault ) {
1077         if ( root() == "/" )
1078           policy_r.downloadMode(DownloadInHeaps);
1079         else
1080           policy_r.downloadMode(DownloadAsNeeded);
1081       }
1082       // DownloadOnly implies dry-run.
1083       else if ( policy_r.downloadMode() == DownloadOnly )
1084         policy_r.dryRun( true );
1085       // ----------------------------------------------------------------- //
1086
1087       MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
1088
1089       ///////////////////////////////////////////////////////////////////
1090       // Prepare execution of commit plugins:
1091       ///////////////////////////////////////////////////////////////////
1092       CommitPlugins commitPlugins;
1093       if ( root() == "/" && ! policy_r.dryRun() )
1094       {
1095         Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
1096         commitPlugins.load( plugindir );
1097       }
1098
1099       ///////////////////////////////////////////////////////////////////
1100       // Write out a testcase if we're in dist upgrade mode.
1101       ///////////////////////////////////////////////////////////////////
1102       if ( getZYpp()->resolver()->upgradeMode() )
1103       {
1104         if ( ! policy_r.dryRun() )
1105         {
1106           writeUpgradeTestcase();
1107         }
1108         else
1109         {
1110           DBG << "dryRun: Not writing upgrade testcase." << endl;
1111         }
1112       }
1113
1114       ///////////////////////////////////////////////////////////////////
1115       // Store non-package data:
1116       ///////////////////////////////////////////////////////////////////
1117       if ( ! policy_r.dryRun() )
1118       {
1119         filesystem::assert_dir( home() );
1120         // requested locales
1121         _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
1122         // weak locks
1123         {
1124           SoftLocksFile::Data newdata;
1125           pool_r.getActiveSoftLocks( newdata );
1126           _softLocksFile.setData( newdata );
1127         }
1128         // hard locks
1129         if ( ZConfig::instance().apply_locks_file() )
1130         {
1131           HardLocksFile::Data newdata;
1132           pool_r.getHardLockQueries( newdata );
1133           _hardLocksFile.setData( newdata );
1134         }
1135       }
1136       else
1137       {
1138         DBG << "dryRun: Not stroring non-package data." << endl;
1139       }
1140
1141       ///////////////////////////////////////////////////////////////////
1142       // Compute transaction:
1143       ///////////////////////////////////////////////////////////////////
1144       ZYppCommitResult result( root() );
1145       result.rTransaction() = pool_r.resolver().getTransaction();
1146       result.rTransaction().order();
1147       // steps: this is our todo-list
1148       ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
1149       if ( policy_r.restrictToMedia() )
1150       {
1151         // Collect until the 1st package from an unwanted media occurs.
1152         // Further collection could violate install order.
1153         MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
1154         for_( it, result.transaction().begin(), result.transaction().end() )
1155         {
1156           if ( makeResObject( *it )->mediaNr() > 1 )
1157             break;
1158           steps.push_back( *it );
1159         }
1160       }
1161       else
1162       {
1163         result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
1164       }
1165       MIL << "Todo: " << result << endl;
1166
1167       ///////////////////////////////////////////////////////////////////
1168       // First collect and display all messages
1169       // associated with patches to be installed.
1170       ///////////////////////////////////////////////////////////////////
1171       if ( ! policy_r.dryRun() )
1172       {
1173         for_( it, steps.begin(), steps.end() )
1174         {
1175           if ( ! it->satSolvable().isKind<Patch>() )
1176             continue;
1177
1178           PoolItem pi( *it );
1179           if ( ! pi.status().isToBeInstalled() )
1180             continue;
1181
1182           Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
1183           if ( ! patch ||patch->message().empty()  )
1184             continue;
1185
1186           MIL << "Show message for " << patch << endl;
1187           callback::SendReport<target::PatchMessageReport> report;
1188           if ( ! report->show( patch ) )
1189           {
1190             WAR << "commit aborted by the user" << endl;
1191             ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1192           }
1193         }
1194       }
1195       else
1196       {
1197         DBG << "dryRun: Not checking patch messages." << endl;
1198       }
1199
1200       ///////////////////////////////////////////////////////////////////
1201       // Remove/install packages.
1202       ///////////////////////////////////////////////////////////////////
1203       DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
1204       if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
1205       {
1206         // Prepare the package cache. Pass all items requiring download.
1207         repo::RepoMediaAccess access;
1208         RepoProvidePackage repoProvidePackage( access, pool_r );
1209         CommitPackageCache packageCache( root() / "tmp", repoProvidePackage );
1210         packageCache.setCommitList( steps.begin(), steps.end() );
1211
1212         bool miss = false;
1213         if ( policy_r.downloadMode() != DownloadAsNeeded )
1214         {
1215           // Preload the cache. Until now this means pre-loading all packages.
1216           // Once DownloadInHeaps is fully implemented, this will change and
1217           // we may actually have more than one heap.
1218           for_( it, steps.begin(), steps.end() )
1219           {
1220             switch ( it->stepType() )
1221             {
1222               case sat::Transaction::TRANSACTION_INSTALL:
1223               case sat::Transaction::TRANSACTION_MULTIINSTALL:
1224                 // proceed: only install actionas may require download.
1225                 break;
1226
1227               default:
1228                 // next: no download for or non-packages and delete actions.
1229                 continue;
1230                 break;
1231             }
1232
1233             PoolItem pi( *it );
1234             if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
1235             {
1236               ManagedFile localfile;
1237               try
1238               {
1239                 // TODO: unify packageCache.get for Package and SrcPackage
1240                 if ( pi->isKind<Package>() )
1241                 {
1242                   localfile = packageCache.get( pi );
1243                 }
1244                 else if ( pi->isKind<SrcPackage>() )
1245                 {
1246                   repo::RepoMediaAccess access;
1247                   repo::SrcPackageProvider prov( access );
1248                   localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
1249                 }
1250                 else
1251                 {
1252                   INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
1253                   continue;
1254                 }
1255                 localfile.resetDispose(); // keep the package file in the cache
1256               }
1257               catch ( const AbortRequestException & exp )
1258               {
1259                 it->stepStage( sat::Transaction::STEP_ERROR );
1260                 miss = true;
1261                 WAR << "commit cache preload aborted by the user" << endl;
1262                 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1263                 break;
1264               }
1265               catch ( const SkipRequestException & exp )
1266               {
1267                 ZYPP_CAUGHT( exp );
1268                 it->stepStage( sat::Transaction::STEP_ERROR );
1269                 miss = true;
1270                 WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1271                 continue;
1272               }
1273               catch ( const Exception & exp )
1274               {
1275                 // bnc #395704: missing catch causes abort.
1276                 // TODO see if packageCache fails to handle errors correctly.
1277                 ZYPP_CAUGHT( exp );
1278                 it->stepStage( sat::Transaction::STEP_ERROR );
1279                 miss = true;
1280                 INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
1281                 continue;
1282               }
1283             }
1284           }
1285         }
1286
1287         if ( miss )
1288         {
1289           ERR << "Some packages could not be provided. Aborting commit."<< endl;
1290         }
1291         else if ( ! policy_r.dryRun() )
1292         {
1293           commit( policy_r, packageCache, result );
1294         }
1295         else
1296         {
1297           DBG << "dryRun: Not installing/deleting anything." << endl;
1298         }
1299       }
1300       else
1301       {
1302         DBG << "dryRun: Not downloading/installing/deleting anything." << endl;
1303       }
1304
1305       ///////////////////////////////////////////////////////////////////
1306       // Try to rebuild solv file while rpm database is still in cache
1307       ///////////////////////////////////////////////////////////////////
1308       if ( ! policy_r.dryRun() )
1309       {
1310         buildCache();
1311       }
1312
1313       // for DEPRECATED old ZyppCommitResult results:
1314       ///////////////////////////////////////////////////////////////////
1315       // build return statistics
1316       ///////////////////////////////////////////////////////////////////
1317       result._errors.clear();
1318       result._remaining.clear();
1319       result._srcremaining.clear();
1320       unsigned toInstall = 0;
1321       for_( step, steps.begin(), steps.end() )
1322       {
1323         if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1324         {
1325           // For non-packages only products might have beed installed.
1326           // All the rest is ignored.
1327           if ( step->satSolvable().isSystem() || ! step->satSolvable().isKind<Product>() )
1328             continue;
1329         }
1330         else if ( step->stepType() == sat::Transaction::TRANSACTION_ERASE )
1331         {
1332           continue;
1333         }
1334         // to be installed:
1335         ++toInstall;
1336         switch ( step->stepStage() )
1337         {
1338           case sat::Transaction::STEP_TODO:
1339             if ( step->satSolvable().isKind<Package>() )
1340               result._remaining.push_back( PoolItem( *step ) );
1341             else if ( step->satSolvable().isKind<SrcPackage>() )
1342               result._srcremaining.push_back( PoolItem( *step ) );
1343             break;
1344           case sat::Transaction::STEP_DONE:
1345             // NOOP
1346             break;
1347           case sat::Transaction::STEP_ERROR:
1348             result._errors.push_back( PoolItem( *step ) );
1349             break;
1350         }
1351       }
1352       result._result = (toInstall - result._remaining.size());
1353       ///////////////////////////////////////////////////////////////////
1354
1355       MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
1356       return result;
1357     }
1358
1359     ///////////////////////////////////////////////////////////////////
1360     //
1361     // COMMIT internal
1362     //
1363     ///////////////////////////////////////////////////////////////////
1364     void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
1365                              CommitPackageCache & packageCache_r,
1366                              ZYppCommitResult & result_r )
1367     {
1368       // steps: this is our todo-list
1369       ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
1370       MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
1371
1372       bool abort = false;
1373       std::vector<sat::Solvable> successfullyInstalledPackages;
1374       TargetImpl::PoolItemList remaining;
1375
1376       for_( step, steps.begin(), steps.end() )
1377       {
1378         PoolItem citem( *step );
1379         if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
1380         {
1381           if ( citem->isKind<Package>() )
1382           {
1383             // for packages this means being obsoleted (by rpm)
1384             // thius no additional action is needed.
1385             step->stepStage( sat::Transaction::STEP_DONE );
1386             continue;
1387           }
1388         }
1389
1390         if ( citem->isKind<Package>() )
1391         {
1392           Package::constPtr p = citem->asKind<Package>();
1393           if ( citem.status().isToBeInstalled() )
1394           {
1395             ManagedFile localfile;
1396             try
1397             {
1398               localfile = packageCache_r.get( citem );
1399             }
1400             catch ( const AbortRequestException &e )
1401             {
1402               WAR << "commit aborted by the user" << endl;
1403               abort = true;
1404               step->stepStage( sat::Transaction::STEP_ERROR );
1405               break;
1406             }
1407             catch ( const SkipRequestException &e )
1408             {
1409               ZYPP_CAUGHT( e );
1410               WAR << "Skipping package " << p << " in commit" << endl;
1411               step->stepStage( sat::Transaction::STEP_ERROR );
1412               continue;
1413             }
1414             catch ( const Exception &e )
1415             {
1416               // bnc #395704: missing catch causes abort.
1417               // TODO see if packageCache fails to handle errors correctly.
1418               ZYPP_CAUGHT( e );
1419               INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
1420               step->stepStage( sat::Transaction::STEP_ERROR );
1421               continue;
1422             }
1423
1424 #warning Exception handling
1425             // create a installation progress report proxy
1426             RpmInstallPackageReceiver progress( citem.resolvable() );
1427             progress.connect(); // disconnected on destruction.
1428
1429             bool success = false;
1430             rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1431             // Why force and nodeps?
1432             //
1433             // Because zypp builds the transaction and the resolver asserts that
1434             // everything is fine.
1435             // We use rpm just to unpack and register the package in the database.
1436             // We do this step by step, so rpm is not aware of the bigger context.
1437             // So we turn off rpms internal checks, because we do it inside zypp.
1438             flags |= rpm::RPMINST_NODEPS;
1439             flags |= rpm::RPMINST_FORCE;
1440             //
1441             if (p->multiversionInstall())  flags |= rpm::RPMINST_NOUPGRADE;
1442             if (policy_r.dryRun())         flags |= rpm::RPMINST_TEST;
1443             if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
1444             if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
1445
1446             try
1447             {
1448               progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
1449               rpm().installPackage( localfile, flags );
1450               HistoryLog().install(citem);
1451
1452               if ( progress.aborted() )
1453               {
1454                 WAR << "commit aborted by the user" << endl;
1455                 localfile.resetDispose(); // keep the package file in the cache
1456                 abort = true;
1457                 step->stepStage( sat::Transaction::STEP_ERROR );
1458                 break;
1459               }
1460               else
1461               {
1462                 success = true;
1463                 step->stepStage( sat::Transaction::STEP_DONE );
1464               }
1465             }
1466             catch ( Exception & excpt_r )
1467             {
1468               ZYPP_CAUGHT(excpt_r);
1469               localfile.resetDispose(); // keep the package file in the cache
1470
1471               if ( policy_r.dryRun() )
1472               {
1473                 WAR << "dry run failed" << endl;
1474                 step->stepStage( sat::Transaction::STEP_ERROR );
1475                 break;
1476               }
1477               // else
1478               if ( progress.aborted() )
1479               {
1480                 WAR << "commit aborted by the user" << endl;
1481                 abort = true;
1482               }
1483               else
1484               {
1485                 WAR << "Install failed" << endl;
1486               }
1487               step->stepStage( sat::Transaction::STEP_ERROR );
1488               break; // stop
1489             }
1490
1491             if ( success && !policy_r.dryRun() )
1492             {
1493               citem.status().resetTransact( ResStatus::USER );
1494               successfullyInstalledPackages.push_back( citem.satSolvable() );
1495               step->stepStage( sat::Transaction::STEP_DONE );
1496             }
1497           }
1498           else
1499           {
1500             RpmRemovePackageReceiver progress( citem.resolvable() );
1501             progress.connect(); // disconnected on destruction.
1502
1503             bool success = false;
1504             rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
1505             flags |= rpm::RPMINST_NODEPS;
1506             if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
1507             try
1508             {
1509               rpm().removePackage( p, flags );
1510               HistoryLog().remove(citem);
1511
1512               if ( progress.aborted() )
1513               {
1514                 WAR << "commit aborted by the user" << endl;
1515                 abort = true;
1516                 step->stepStage( sat::Transaction::STEP_ERROR );
1517                 break;
1518               }
1519               else
1520               {
1521                 success = true;
1522                 step->stepStage( sat::Transaction::STEP_DONE );
1523               }
1524             }
1525             catch (Exception & excpt_r)
1526             {
1527               ZYPP_CAUGHT( excpt_r );
1528               if ( progress.aborted() )
1529               {
1530                 WAR << "commit aborted by the user" << endl;
1531                 abort = true;
1532                 step->stepStage( sat::Transaction::STEP_ERROR );
1533                 break;
1534               }
1535               // else
1536               WAR << "removal of " << p << " failed";
1537               step->stepStage( sat::Transaction::STEP_ERROR );
1538             }
1539             if ( success && !policy_r.dryRun() )
1540             {
1541               citem.status().resetTransact( ResStatus::USER );
1542               step->stepStage( sat::Transaction::STEP_DONE );
1543             }
1544           }
1545         }
1546         else if ( ! policy_r.dryRun() ) // other resolvables (non-Package)
1547         {
1548           // Status is changed as the buddy package buddy
1549           // gets installed/deleted. Handle non-buddies only.
1550           if ( ! citem.buddy() )
1551           {
1552             if ( citem->isKind<Product>() )
1553             {
1554               Product::constPtr p = citem->asKind<Product>();
1555               if ( citem.status().isToBeInstalled() )
1556               {
1557                 ERR << "Can't install orphan product without release-package! " << citem << endl;
1558               }
1559               else
1560               {
1561                 // Deleting the corresponding product entry is all we con do.
1562                 // So the product will no longer be visible as installed.
1563                 std::string referenceFilename( p->referenceFilename() );
1564                 if ( referenceFilename.empty() )
1565                 {
1566                   ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
1567                 }
1568                 else
1569                 {
1570                   PathInfo referenceFile( Pathname::assertprefix( _root, Pathname( "/etc/products.d" ) ) / referenceFilename );
1571                   if ( ! referenceFile.isFile() || filesystem::unlink( referenceFile.path() ) != 0 )
1572                   {
1573                     ERR << "Delete orphan product failed: " << referenceFile << endl;
1574                   }
1575                 }
1576               }
1577             }
1578             else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
1579             {
1580               // SrcPackage is install-only
1581               SrcPackage::constPtr p = citem->asKind<SrcPackage>();
1582               installSrcPackage( p );
1583             }
1584
1585             citem.status().resetTransact( ResStatus::USER );
1586             step->stepStage( sat::Transaction::STEP_DONE );
1587           }
1588
1589         }  // other resolvables
1590
1591       } // for
1592
1593       // Check presence of update scripts/messages. If aborting,
1594       // at least log omitted scripts.
1595       if ( ! successfullyInstalledPackages.empty() )
1596       {
1597         if ( ! RunUpdateScripts( _root, ZConfig::instance().update_scriptsPath(),
1598                                  successfullyInstalledPackages, abort ) )
1599         {
1600           WAR << "Commit aborted by the user" << endl;
1601           abort = true;
1602         }
1603         // send messages after scripts in case some script generates output,
1604         // that should be kept in t %ghost message file.
1605         RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
1606                            successfullyInstalledPackages,
1607                            result_r );
1608       }
1609
1610       if ( abort )
1611       {
1612         ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
1613       }
1614     }
1615
1616     ///////////////////////////////////////////////////////////////////
1617
1618     rpm::RpmDb & TargetImpl::rpm()
1619     {
1620       return _rpm;
1621     }
1622
1623     bool TargetImpl::providesFile (const std::string & path_str, const std::string & name_str) const
1624     {
1625       return _rpm.hasFile(path_str, name_str);
1626     }
1627
1628
1629     Date TargetImpl::timestamp() const
1630     {
1631       return _rpm.timestamp();
1632     }
1633
1634     ///////////////////////////////////////////////////////////////////
1635     namespace
1636     {
1637       parser::ProductFileData baseproductdata( const Pathname & root_r )
1638       {
1639         PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
1640         if ( baseproduct.isFile() )
1641         {
1642           try
1643           {
1644             return parser::ProductFileReader::scanFile( baseproduct.path() );
1645           }
1646           catch ( const Exception & excpt )
1647           {
1648             ZYPP_CAUGHT( excpt );
1649           }
1650         }
1651         return parser::ProductFileData();
1652       }
1653
1654       inline Pathname staticGuessRoot( const Pathname & root_r )
1655       {
1656         if ( root_r.empty() )
1657         {
1658           // empty root: use existing Target or assume "/"
1659           Pathname ret ( ZConfig::instance().systemRoot() );
1660           if ( ret.empty() )
1661             return Pathname("/");
1662           return ret;
1663         }
1664         return root_r;
1665       }
1666
1667       inline std::string firstNonEmptyLineIn( const Pathname & file_r )
1668       {
1669         std::ifstream idfile( file_r.c_str() );
1670         for( iostr::EachLine in( idfile ); in; in.next() )
1671         {
1672           std::string line( str::trim( *in ) );
1673           if ( ! line.empty() )
1674             return line;
1675         }
1676         return std::string();
1677       }
1678     } // namescpace
1679     ///////////////////////////////////////////////////////////////////
1680
1681     Product::constPtr TargetImpl::baseProduct() const
1682     {
1683       ResPool pool(ResPool::instance());
1684       for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
1685       {
1686         Product::constPtr p = (*it)->asKind<Product>();
1687         if ( p->isTargetDistribution() )
1688           return p;
1689       }
1690       return nullptr;
1691     }
1692
1693     LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
1694     {
1695       const Pathname needroot( staticGuessRoot(root_r) );
1696       const Target_constPtr target( getZYpp()->getTarget() );
1697       if ( target && target->root() == needroot )
1698         return target->requestedLocales();
1699       return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
1700     }
1701
1702     std::string TargetImpl::targetDistribution() const
1703     { return baseproductdata( _root ).registerTarget(); }
1704     // static version:
1705     std::string TargetImpl::targetDistribution( const Pathname & root_r )
1706     { return baseproductdata( staticGuessRoot(root_r) ).registerTarget(); }
1707
1708     std::string TargetImpl::targetDistributionRelease() const
1709     { return baseproductdata( _root ).registerRelease(); }
1710     // static version:
1711     std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
1712     { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
1713
1714     Target::DistributionLabel TargetImpl::distributionLabel() const
1715     {
1716       Target::DistributionLabel ret;
1717       parser::ProductFileData pdata( baseproductdata( _root ) );
1718       ret.shortName = pdata.shortName();
1719       ret.summary = pdata.summary();
1720       return ret;
1721     }
1722     // static version:
1723     Target::DistributionLabel TargetImpl::distributionLabel( const Pathname & root_r )
1724     {
1725       Target::DistributionLabel ret;
1726       parser::ProductFileData pdata( baseproductdata( staticGuessRoot(root_r) ) );
1727       ret.shortName = pdata.shortName();
1728       ret.summary = pdata.summary();
1729       return ret;
1730     }
1731
1732     std::string TargetImpl::distributionVersion() const
1733     {
1734       if ( _distributionVersion.empty() )
1735       {
1736         _distributionVersion = TargetImpl::distributionVersion(root());
1737         if ( !_distributionVersion.empty() )
1738           MIL << "Remember distributionVersion = '" << _distributionVersion << "'" << endl;
1739       }
1740       return _distributionVersion;
1741     }
1742     // static version
1743     std::string TargetImpl::distributionVersion( const Pathname & root_r )
1744     {
1745       std::string distributionVersion = baseproductdata( staticGuessRoot(root_r) ).edition().version();
1746       if ( distributionVersion.empty() )
1747       {
1748         // ...But the baseproduct method is not expected to work on RedHat derivatives.
1749         // On RHEL, Fedora and others the "product version" is determined by the first package
1750         // providing 'redhat-release'. This value is not hardcoded in YUM and can be configured
1751         // with the $distroverpkg variable.
1752         scoped_ptr<rpm::RpmDb> tmprpmdb;
1753         if ( ZConfig::instance().systemRoot() == Pathname() )
1754         {
1755           try
1756           {
1757               tmprpmdb.reset( new rpm::RpmDb );
1758               tmprpmdb->initDatabase( /*default ctor uses / but no additional keyring exports */ );
1759           }
1760           catch( ... )
1761           {
1762             return "";
1763           }
1764         }
1765         rpm::librpmDb::db_const_iterator it;
1766         if ( it.findByProvides( ZConfig::instance().distroverpkg() ) )
1767           distributionVersion = it->tag_version();
1768       }
1769       return distributionVersion;
1770     }
1771
1772
1773     std::string TargetImpl::distributionFlavor() const
1774     {
1775       return firstNonEmptyLineIn( home() / "LastDistributionFlavor" );
1776     }
1777     // static version:
1778     std::string TargetImpl::distributionFlavor( const Pathname & root_r )
1779     {
1780       return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/LastDistributionFlavor" );
1781     }
1782
1783     ///////////////////////////////////////////////////////////////////
1784
1785     std::string TargetImpl::anonymousUniqueId() const
1786     {
1787       return firstNonEmptyLineIn( home() / "AnonymousUniqueId" );
1788     }
1789     // static version:
1790     std::string TargetImpl::anonymousUniqueId( const Pathname & root_r )
1791     {
1792       return firstNonEmptyLineIn( staticGuessRoot(root_r) / "/var/lib/zypp/AnonymousUniqueId" );
1793     }
1794
1795     ///////////////////////////////////////////////////////////////////
1796
1797     void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
1798     {
1799       // provide on local disk
1800       repo::RepoMediaAccess access_r;
1801       repo::SrcPackageProvider prov( access_r );
1802       ManagedFile localfile = prov.provideSrcPackage( srcPackage_r );
1803       // install it
1804       rpm().installPackage ( localfile );
1805     }
1806
1807     /////////////////////////////////////////////////////////////////
1808   } // namespace target
1809   ///////////////////////////////////////////////////////////////////
1810   /////////////////////////////////////////////////////////////////
1811 } // namespace zypp
1812 ///////////////////////////////////////////////////////////////////