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