Imported Upstream version 15.18.0
[platform/upstream/libzypp.git] / zypp / target / TargetImpl.cc
index c05353d..ff1b264 100644 (file)
@@ -26,6 +26,7 @@
 #include "zypp/base/IOStream.h"
 #include "zypp/base/Functional.h"
 #include "zypp/base/UserRequestException.h"
+#include "zypp/base/Json.h"
 
 #include "zypp/ZConfig.h"
 #include "zypp/ZYppFactory.h"
 #include "zypp/target/TargetCallbackReceiver.h"
 #include "zypp/target/rpm/librpmDb.h"
 #include "zypp/target/CommitPackageCache.h"
+#include "zypp/target/RpmPostTransCollector.h"
 
 #include "zypp/parser/ProductFileReader.h"
-
-#include "zypp/pool/GetResolvablesToInsDel.h"
-#include "zypp/solver/detail/Testcase.h"
-
-#include "zypp/repo/DeltaCandidates.h"
-#include "zypp/repo/PackageProvider.h"
 #include "zypp/repo/SrcPackageProvider.h"
 
 #include "zypp/sat/Pool.h"
+#include "zypp/sat/detail/PoolImpl.h"
+#include "zypp/sat/Transaction.h"
 
 #include "zypp/PluginScript.h"
 
 using namespace std;
 
-
 ///////////////////////////////////////////////////////////////////
 namespace zypp
-{ /////////////////////////////////////////////////////////////////
+{
+  /////////////////////////////////////////////////////////////////
+  namespace
+  {
+    // HACK for bnc#906096: let pool re-evaluate multiversion spec
+    // if target root changes. ZConfig returns data sensitive to
+    // current target root.
+    inline void sigMultiversionSpecChanged()
+    {
+      sat::detail::PoolMember::myPool().multiversionSpecChanged();
+    }
+  } //namespace
+  /////////////////////////////////////////////////////////////////
+
+  ///////////////////////////////////////////////////////////////////
+  namespace json
+  {
+    // Lazy via template specialisation / should switch to overloading
+
+    template<>
+    inline std::string toJSON( const ZYppCommitResult::TransactionStepList & steps_r )
+    {
+      using sat::Transaction;
+      json::Array ret;
+
+      for ( const Transaction::Step & step : steps_r )
+       // ignore implicit deletes due to obsoletes and non-package actions
+       if ( step.stepType() != Transaction::TRANSACTION_IGNORE )
+         ret.add( step );
+
+      return ret.asJSON();
+    }
+
+    /** See \ref commitbegin on page \ref plugin-commit for the specs. */
+    template<>
+    inline std::string toJSON( const sat::Transaction::Step & step_r )
+    {
+      static const std::string strType( "type" );
+      static const std::string strStage( "stage" );
+      static const std::string strSolvable( "solvable" );
+
+      static const std::string strTypeDel( "-" );
+      static const std::string strTypeIns( "+" );
+      static const std::string strTypeMul( "M" );
+
+      static const std::string strStageDone( "ok" );
+      static const std::string strStageFailed( "err" );
+
+      static const std::string strSolvableN( "n" );
+      static const std::string strSolvableE( "e" );
+      static const std::string strSolvableV( "v" );
+      static const std::string strSolvableR( "r" );
+      static const std::string strSolvableA( "a" );
+
+      using sat::Transaction;
+      json::Object ret;
+
+      switch ( step_r.stepType() )
+      {
+       case Transaction::TRANSACTION_IGNORE:   /*empty*/ break;
+       case Transaction::TRANSACTION_ERASE:    ret.add( strType, strTypeDel ); break;
+       case Transaction::TRANSACTION_INSTALL:  ret.add( strType, strTypeIns ); break;
+       case Transaction::TRANSACTION_MULTIINSTALL: ret.add( strType, strTypeMul ); break;
+      }
+
+      switch ( step_r.stepStage() )
+      {
+       case Transaction::STEP_TODO:            /*empty*/ break;
+       case Transaction::STEP_DONE:            ret.add( strStage, strStageDone ); break;
+       case Transaction::STEP_ERROR:           ret.add( strStage, strStageFailed ); break;
+      }
+
+      {
+       IdString ident;
+       Edition ed;
+       Arch arch;
+       if ( sat::Solvable solv = step_r.satSolvable() )
+       {
+         ident = solv.ident();
+         ed    = solv.edition();
+         arch  = solv.arch();
+       }
+       else
+       {
+         // deleted package; post mortem data stored in Transaction::Step
+         ident = step_r.ident();
+         ed    = step_r.edition();
+         arch  = step_r.arch();
+       }
+
+       json::Object s {
+         { strSolvableN, ident.asString() },
+         { strSolvableV, ed.version() },
+         { strSolvableR, ed.release() },
+         { strSolvableA, arch.asString() }
+       };
+       if ( Edition::epoch_t epoch = ed.epoch() )
+         s.add( strSolvableE, epoch );
+
+       ret.add( strSolvable, s );
+      }
+
+      return ret.asJSON();
+    }
+  } // namespace json
+  ///////////////////////////////////////////////////////////////////
+
   ///////////////////////////////////////////////////////////////////
   namespace target
-  { /////////////////////////////////////////////////////////////////
+  {
+    ///////////////////////////////////////////////////////////////////
+    namespace
+    {
+      SolvIdentFile::Data getUserInstalledFromHistory( const Pathname & historyFile_r )
+      {
+       SolvIdentFile::Data onSystemByUserList;
+       // go and parse it: 'who' must constain an '@', then it was installed by user request.
+       // 2009-09-29 07:25:19|install|lirc-remotes|0.8.5-3.2|x86_64|root@opensuse|InstallationImage|a204211eb0...
+       std::ifstream infile( historyFile_r.c_str() );
+       for( iostr::EachLine in( infile ); in; in.next() )
+       {
+         const char * ch( (*in).c_str() );
+         // start with year
+         if ( *ch < '1' || '9' < *ch )
+           continue;
+         const char * sep1 = ::strchr( ch, '|' );      // | after date
+         if ( !sep1 )
+           continue;
+         ++sep1;
+         // if logs an install or delete
+         bool installs = true;
+         if ( ::strncmp( sep1, "install|", 8 ) )
+         {
+           if ( ::strncmp( sep1, "remove |", 8 ) )
+             continue; // no install and no remove
+             else
+               installs = false; // remove
+         }
+         sep1 += 8;                                    // | after what
+         // get the package name
+         const char * sep2 = ::strchr( sep1, '|' );    // | after name
+         if ( !sep2 || sep1 == sep2 )
+           continue;
+         (*in)[sep2-ch] = '\0';
+         IdString pkg( sep1 );
+         // we're done, if a delete
+         if ( !installs )
+         {
+           onSystemByUserList.erase( pkg );
+           continue;
+         }
+         // now guess whether user installed or not (3rd next field contains 'user@host')
+         if ( (sep1 = ::strchr( sep2+1, '|' ))         // | after version
+           && (sep1 = ::strchr( sep1+1, '|' ))         // | after arch
+           && (sep2 = ::strchr( sep1+1, '|' )) )       // | after who
+         {
+           (*in)[sep2-ch] = '\0';
+           if ( ::strchr( sep1+1, '@' ) )
+           {
+             // by user
+             onSystemByUserList.insert( pkg );
+             continue;
+           }
+         }
+       }
+       MIL << "onSystemByUserList found: " << onSystemByUserList.size() << endl;
+       return onSystemByUserList;
+      }
+    } // namespace
+    ///////////////////////////////////////////////////////////////////
+
+    /** Helper for commit plugin execution.
+     * \ingroup g_RAII
+     */
+    class CommitPlugins : private base::NonCopyable
+    {
+      public:
+       /** Default ctor: Empty plugin list */
+       CommitPlugins()
+       {}
+
+       /** Dtor: Send PLUGINEND message and close plugins. */
+       ~CommitPlugins()
+       {
+         if ( ! _scripts.empty() )
+           send( PluginFrame( "PLUGINEND" ) );
+         // ~PluginScript will disconnect all remaining plugins!
+       }
+
+       /** Whether no plugins are waiting */
+       bool empty() const
+       { return _scripts.empty(); }
+
+
+       /** Send \ref PluginFrame to all open plugins.
+        * Failed plugins are removed from the execution list.
+        */
+       void send( const PluginFrame & frame_r )
+       {
+         DBG << "+++++++++++++++ send " << frame_r << endl;
+         for ( auto it = _scripts.begin(); it != _scripts.end(); )
+         {
+           doSend( *it, frame_r );
+           if ( it->isOpen() )
+             ++it;
+           else
+             it = _scripts.erase( it );
+         }
+         DBG << "--------------- send " << frame_r << endl;
+       }
+
+       /** Find and launch plugins sending PLUGINSTART message.
+        *
+        * If \a path_r is a directory all executable files whithin are
+        * expected to be plugins. Otherwise \a path_r must point to an
+        * executable plugin.
+        */
+       void load( const Pathname & path_r )
+       {
+         PathInfo pi( path_r );
+         DBG << "+++++++++++++++ load " << pi << endl;
+         if ( pi.isDir() )
+         {
+           std::list<Pathname> entries;
+           if ( filesystem::readdir( entries, pi.path(), false ) != 0 )
+           {
+             WAR << "Plugin dir is not readable: " << pi << endl;
+             return;
+           }
+           for_( it, entries.begin(), entries.end() )
+           {
+             PathInfo pii( *it );
+             if ( pii.isFile() && pii.userMayRX() )
+               doLoad( pii );
+           }
+         }
+         else if ( pi.isFile() )
+         {
+           if ( pi.userMayRX() )
+             doLoad( pi );
+           else
+             WAR << "Plugin file is not executable: " << pi << endl;
+         }
+         else
+         {
+           WAR << "Plugin path is neither dir nor file: " << pi << endl;
+         }
+         DBG << "--------------- load " << pi << endl;
+       }
+
+      private:
+       /** Send \ref PluginFrame and expect valid answer (ACK|_ENOMETHOD).
+        * Upon invalid answer or error, close the plugin. and remove it from the
+        * execution list.
+        * \returns the received \ref PluginFrame (empty Frame upon Exception)
+        */
+       PluginFrame doSend( PluginScript & script_r, const PluginFrame & frame_r )
+       {
+         PluginFrame ret;
+
+         try {
+           script_r.send( frame_r );
+           ret = script_r.receive();
+         }
+         catch( const zypp::Exception & e )
+         { ZYPP_CAUGHT(e); }
+
+         if ( ! ( ret.isAckCommand() || ret.isEnomethodCommand() ) )
+         {
+           WAR << "Bad plugin response from " << script_r << endl;
+           WAR << dump(ret) << endl;
+           script_r.close();
+         }
+
+         return ret;
+       }
+
+       /** Launch a plugin sending PLUGINSTART message. */
+       void doLoad( const PathInfo & pi_r )
+       {
+         MIL << "Load plugin: " << pi_r << endl;
+         try {
+           PluginScript plugin( pi_r.path() );
+           plugin.open();
+
+           PluginFrame frame( "PLUGINBEGIN" );
+           if ( ZConfig::instance().hasUserData() )
+             frame.setHeader( "userdata", ZConfig::instance().userData() );
+
+           doSend( plugin, frame );    // closes on error
+           if ( plugin.isOpen() )
+             _scripts.push_back( plugin );
+         }
+         catch( const zypp::Exception & e )
+         {
+            WAR << "Failed to load plugin " << pi_r << endl;
+         }
+       }
+
+      private:
+       std::list<PluginScript> _scripts;
+    };
+
+    void testCommitPlugins( const Pathname & path_r ) // for testing only
+    {
+      USR << "+++++" << endl;
+      {
+       CommitPlugins pl;
+       pl.load( path_r );
+       USR << "=====" << endl;
+      }
+      USR << "-----" << endl;
+    }
+
+    ///////////////////////////////////////////////////////////////////
+    namespace
+    {
+      inline PluginFrame transactionPluginFrame( const std::string & command_r, ZYppCommitResult::TransactionStepList & steps_r )
+      {
+       return PluginFrame( command_r, json::Object {
+         { "TransactionStepList", steps_r }
+       }.asJSON() );
+      }
+    } // namespace
+    ///////////////////////////////////////////////////////////////////
 
     /** \internal Manage writing a new testcase when doing an upgrade. */
     void writeUpgradeTestcase()
@@ -228,6 +546,7 @@ namespace zypp
         // - "name-version-release"
         // - "name-version-release-*"
         bool abort = false;
+       std::map<std::string, Pathname> unify; // scripts <md5,path>
         for_( it, checkPackages_r.begin(), checkPackages_r.end() )
         {
           std::string prefix( str::form( "%s-%s", it->name().c_str(), it->edition().c_str() ) );
@@ -240,13 +559,42 @@ namespace zypp
               continue; // if not exact match it had to continue with '-'
 
             PathInfo script( scriptsDir / *sit );
-            if ( ! script.isFile() )
-              continue;
+            Pathname localPath( scriptsPath_r/(*sit) );        // without root prefix
+            std::string unifytag;                      // must not stay empty
 
-            // Assert it's set executable
-            filesystem::addmod( script.path(), 0500 );
+           if ( script.isFile() )
+           {
+             // Assert it's set executable, unify by md5sum.
+             filesystem::addmod( script.path(), 0500 );
+             unifytag = filesystem::md5sum( script.path() );
+           }
+           else if ( ! script.isExist() )
+           {
+             // Might be a dangling symlink, might be ok if we are in
+             // instsys (absolute symlink within the system below /mnt).
+             // readlink will tell....
+             unifytag = filesystem::readlink( script.path() ).asString();
+           }
+
+           if ( unifytag.empty() )
+             continue;
+
+           // Unify scripts
+           if ( unify[unifytag].empty() )
+           {
+             unify[unifytag] = localPath;
+           }
+           else
+           {
+             // translators: We may find the same script content in files with different names.
+             // Only the first occurence is executed, subsequent ones are skipped. It's a one-line
+             // message for a log file. Preferably start translation with "%s"
+             std::string msg( str::form(_("%s already executed as %s)"), localPath.asString().c_str(), unify[unifytag].c_str() ) );
+              MIL << "Skip update script: " << msg << endl;
+              HistoryLog().comment( msg, /*timestamp*/true );
+             continue;
+           }
 
-            Pathname localPath( scriptsPath_r/(*sit) ); // without root prefix
             if ( abort || aborting_r )
             {
               WAR << "Aborting: Skip update script " << *sit << endl;
@@ -449,7 +797,7 @@ namespace zypp
 
             MIL << "Found update message " << *sit << endl;
             Pathname localPath( messagesPath_r/(*sit) ); // without root prefix
-            result_r.setUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
+            result_r.rUpdateMessages().push_back( UpdateNotificationFile( *it, localPath ) );
             historylog.comment( str::Str() << _("New update message") << " " << localPath, /*timestamp*/true );
           }
         }
@@ -466,73 +814,10 @@ namespace zypp
                              ZYppCommitResult & result_r )
     { RunUpdateMessages( root_r, messagesPath_r, checkPackages_r, result_r ); }
 
-    /** Helper for PackageProvider queries during commit. */
-    struct QueryInstalledEditionHelper
-    {
-      bool operator()( const std::string & name_r,
-                       const Edition &     ed_r,
-                       const Arch &        arch_r ) const
-      {
-        rpm::librpmDb::db_const_iterator it;
-        for ( it.findByName( name_r ); *it; ++it )
-          {
-            if ( arch_r == it->tag_arch()
-                 && ( ed_r == Edition::noedition || ed_r == it->tag_edition() ) )
-              {
-                return true;
-              }
-          }
-        return false;
-      }
-    };
-
-    /**
-     * \short Let the Source provide the package.
-     * \p pool_r \ref ResPool used to get candidates
-     * \p pi item to be commited
-    */
-    struct RepoProvidePackage
-    {
-      ResPool _pool;
-      repo::RepoMediaAccess &_access;
-
-      RepoProvidePackage( repo::RepoMediaAccess &access, ResPool pool_r )
-        : _pool(pool_r), _access(access)
-      {}
-
-      ManagedFile operator()( const PoolItem & pi )
-      {
-        // Redirect PackageProvider queries for installed editions
-        // (in case of patch/delta rpm processing) to rpmDb.
-        repo::PackageProviderPolicy packageProviderPolicy;
-        packageProviderPolicy.queryInstalledCB( QueryInstalledEditionHelper() );
-
-        Package::constPtr p = asKind<Package>(pi.resolvable());
-
-        // Build a repository list for repos
-        // contributing to the pool
-        std::list<Repository> repos( _pool.knownRepositoriesBegin(), _pool.knownRepositoriesEnd() );
-        repo::DeltaCandidates deltas(repos, p->name());
-        repo::PackageProvider pkgProvider( _access, p, deltas, packageProviderPolicy );
-
-        ManagedFile ret( pkgProvider.providePackage() );
-        return ret;
-      }
-    };
     ///////////////////////////////////////////////////////////////////
 
     IMPL_PTR_TYPE(TargetImpl);
 
-    TargetImpl_Ptr TargetImpl::_nullimpl;
-
-    /** Null implementation */
-    TargetImpl_Ptr TargetImpl::nullimpl()
-    {
-      if (_nullimpl == 0)
-        _nullimpl = new TargetImpl;
-      return _nullimpl;
-    }
-
     ///////////////////////////////////////////////////////////////////
     //
     // METHOD NAME : TargetImpl::TargetImpl
@@ -541,7 +826,7 @@ namespace zypp
     TargetImpl::TargetImpl( const Pathname & root_r, bool doRebuild_r )
     : _root( root_r )
     , _requestedLocalesFile( home() / "RequestedLocales" )
-    , _softLocksFile( home() / "SoftLocks" )
+    , _autoInstalledFile( home() / "AutoInstalled" )
     , _hardLocksFile( Pathname::assertprefix( _root, ZConfig::instance().locksFile() ) )
     {
       _rpm.initDatabase( root_r, Pathname(), doRebuild_r );
@@ -549,36 +834,17 @@ namespace zypp
       HistoryLog::setRoot(_root);
 
       createAnonymousId();
-
+      sigMultiversionSpecChanged();    // HACK: see sigMultiversionSpecChanged
       MIL << "Initialized target on " << _root << endl;
     }
 
     /**
      * generates a random id using uuidgen
      */
-    static string generateRandomId()
+    static std::string generateRandomId()
     {
-      string id;
-      const char* argv[] =
-      {
-         "/usr/bin/uuidgen",
-         NULL
-      };
-
-      ExternalProgram prog( argv,
-                            ExternalProgram::Normal_Stderr,
-                            false, -1, true);
-      std::string line;
-      for(line = prog.receiveLine();
-          ! line.empty();
-          line = prog.receiveLine() )
-      {
-          MIL << line << endl;
-          id = line;
-          break;
-      }
-      prog.close();
-      return id;
+      std::ifstream uuidprovider( "/proc/sys/kernel/random/uuid" );
+      return iostr::getline( uuidprovider );
     }
 
     /**
@@ -685,6 +951,7 @@ namespace zypp
     TargetImpl::~TargetImpl()
     {
       _rpm.closeDatabase();
+      sigMultiversionSpecChanged();    // HACK: see sigMultiversionSpecChanged
       MIL << "Targets closed" << endl;
     }
 
@@ -705,7 +972,7 @@ namespace zypp
       filesystem::recursive_rmdir( base );
     }
 
-    void TargetImpl::buildCache()
+    bool TargetImpl::buildCache()
     {
       Pathname base = solvfilesPath();
       Pathname rpmsolv       = base/"solv";
@@ -714,8 +981,7 @@ namespace zypp
       bool build_rpm_solv = true;
       // lets see if the rpm solv cache exists
 
-      RepoStatus rpmstatus( RepoStatus( _root/"/var/lib/rpm/Name" )
-                            && (_root/"/etc/products.d") );
+      RepoStatus rpmstatus( RepoStatus(_root/"var/lib/rpm/Name") && RepoStatus(_root/"etc/products.d") );
 
       bool solvexisted = PathInfo(rpmsolv).isExist();
       if ( solvexisted )
@@ -727,10 +993,10 @@ namespace zypp
         {
           RepoStatus status = RepoStatus::fromCookieFile(rpmsolvcookie);
           // now compare it with the rpm database
-          if ( status.checksum() == rpmstatus.checksum() )
-            build_rpm_solv = false;
-          MIL << "Read cookie: " << rpmsolvcookie << " says: "
-              << (build_rpm_solv ? "outdated" : "uptodate") << endl;
+          if ( status == rpmstatus )
+           build_rpm_solv = false;
+         MIL << "Read cookie: " << rpmsolvcookie << " says: "
+         << (build_rpm_solv ? "outdated" : "uptodate") << endl;
         }
       }
 
@@ -782,32 +1048,40 @@ namespace zypp
         // Take care we unlink the solvfile on exception
         ManagedFile guard( base, filesystem::recursive_rmdir );
 
-        std::ostringstream cmd;
-        cmd << "rpmdb2solv";
-        if ( ! _root.empty() )
-          cmd << " -r '" << _root << "'";
-
-        cmd << " -p '" << Pathname::assertprefix( _root, "/etc/products.d" ) << "'";
+        ExternalProgram::Arguments cmd;
+        cmd.push_back( "rpmdb2solv" );
+        if ( ! _root.empty() ) {
+          cmd.push_back( "-r" );
+          cmd.push_back( _root.asString() );
+        }
+        cmd.push_back( "-X" ); // autogenerate pattern/product/... from -package
+        cmd.push_back( "-A" ); // autogenerate application pseudo packages
+        cmd.push_back( "-p" );
+        cmd.push_back( Pathname::assertprefix( _root, "/etc/products.d" ).asString() );
 
         if ( ! oldSolvFile.empty() )
-          cmd << " '" << oldSolvFile << "'";
+          cmd.push_back( oldSolvFile.asString() );
 
-        cmd << "  > '" << tmpsolv.path() << "'";
+        cmd.push_back( "-o" );
+        cmd.push_back( tmpsolv.path().asString() );
 
-        MIL << "Executing: " << cmd << endl;
-        ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
+        ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
+       std::string errdetail;
 
-        cmd << endl;
         for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
           WAR << "  " << output;
-          cmd << "     " << output;
+          if ( errdetail.empty() ) {
+            errdetail = prog.command();
+            errdetail += '\n';
+          }
+          errdetail += output;
         }
 
         int ret = prog.close();
         if ( ret != 0 )
         {
           Exception ex(str::form("Failed to cache rpm database (%d).", ret));
-          ex.remember( cmd.str() );
+          ex.remember( errdetail );
           ZYPP_THROW(ex);
         }
 
@@ -821,6 +1095,7 @@ namespace zypp
 
         // We keep it.
         guard.resetDispose();
+       sat::updateSolvFileIndex( rpmsolv );    // content digest for zypper bash completion
 
        // Finally send notification to plugins
        // NOTE: quick hack looking for spacewalk plugin only
@@ -845,6 +1120,18 @@ namespace zypp
            }
        }
       }
+      else
+      {
+       // On the fly add missing solv.idx files for bash completion.
+       if ( ! PathInfo(base/"solv.idx").isExist() )
+         sat::updateSolvFileIndex( rpmsolv );
+      }
+      return build_rpm_solv;
+    }
+
+    void TargetImpl::reload()
+    {
+        load( false );
     }
 
     void TargetImpl::unload()
@@ -854,10 +1141,11 @@ namespace zypp
         system.eraseFromPool();
     }
 
-
-    void TargetImpl::load()
+    void TargetImpl::load( bool force )
     {
-      buildCache();
+      bool newCache = buildCache();
+      MIL << "New cache built: " << (newCache?"true":"false") <<
+        ", force loading: " << (force?"true":"false") << endl;
 
       // now add the repos to the pool
       sat::Pool satpool( sat::Pool::instance() );
@@ -866,10 +1154,19 @@ namespace zypp
 
       // Providing an empty system repo, unload any old content
       Repository system( sat::Pool::instance().findSystemRepo() );
+
       if ( system && ! system.solvablesEmpty() )
       {
-        system.eraseFromPool(); // invalidates system
+        if ( newCache || force )
+        {
+          system.eraseFromPool(); // invalidates system
+        }
+        else
+        {
+          return;     // nothing to do
+        }
       }
+
       if ( ! system )
       {
         system = satpool.systemRepo();
@@ -877,6 +1174,7 @@ namespace zypp
 
       try
       {
+        MIL << "adding " << rpmsolv << " to system" << endl;
         system.addSolv( rpmsolv );
       }
       catch ( const Exception & exp )
@@ -888,6 +1186,7 @@ namespace zypp
 
         system.addSolv( rpmsolv );
       }
+      satpool.rootDir( _root );
 
       // (Re)Load the requested locales et al.
       // If the requested locales are empty, we leave the pool untouched
@@ -898,20 +1197,34 @@ namespace zypp
         const LocaleSet & requestedLocales( _requestedLocalesFile.locales() );
         if ( ! requestedLocales.empty() )
         {
-          satpool.setRequestedLocales( requestedLocales );
+          satpool.initRequestedLocales( requestedLocales );
         }
       }
       {
-        SoftLocksFile::Data softLocks( _softLocksFile.data() );
-        if ( ! softLocks.empty() )
-        {
-          // Don't soft lock any installed item.
-          for_( it, system.solvablesBegin(), system.solvablesEnd() )
-          {
-            softLocks.erase( it->ident() );
-          }
-          ResPool::instance().setAutoSoftLocks( softLocks );
-        }
+       if ( ! PathInfo( _autoInstalledFile.file() ).isExist() )
+       {
+         // Initialize from history, if it does not exist
+         Pathname historyFile( Pathname::assertprefix( _root, ZConfig::instance().historyLogFile() ) );
+         if ( PathInfo( historyFile ).isExist() )
+         {
+           SolvIdentFile::Data onSystemByUser( getUserInstalledFromHistory( historyFile ) );
+           SolvIdentFile::Data onSystemByAuto;
+           for_( it, system.solvablesBegin(), system.solvablesEnd() )
+           {
+             IdString ident( (*it).ident() );
+             if ( onSystemByUser.find( ident ) == onSystemByUser.end() )
+               onSystemByAuto.insert( ident );
+           }
+           _autoInstalledFile.setData( onSystemByAuto );
+         }
+         // on the fly removed any obsolete SoftLocks file
+         filesystem::unlink( home() / "SoftLocks" );
+       }
+       // read from AutoInstalled file
+       sat::StringQueue q;
+       for ( const auto & idstr : _autoInstalledFile.data() )
+         q.push( idstr.id() );
+       satpool.setAutoInstalled( q );
       }
       if ( ZConfig::instance().apply_locks_file() )
       {
@@ -957,6 +1270,44 @@ namespace zypp
       MIL << "TargetImpl::commit(<pool>, " << policy_r << ")" << endl;
 
       ///////////////////////////////////////////////////////////////////
+      // Compute transaction:
+      ///////////////////////////////////////////////////////////////////
+      ZYppCommitResult result( root() );
+      result.rTransaction() = pool_r.resolver().getTransaction();
+      result.rTransaction().order();
+      // steps: this is our todo-list
+      ZYppCommitResult::TransactionStepList & steps( result.rTransactionStepList() );
+      if ( policy_r.restrictToMedia() )
+      {
+       // Collect until the 1st package from an unwanted media occurs.
+        // Further collection could violate install order.
+       MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
+       for_( it, result.transaction().begin(), result.transaction().end() )
+       {
+         if ( makeResObject( *it )->mediaNr() > 1 )
+           break;
+         steps.push_back( *it );
+       }
+      }
+      else
+      {
+       result.rTransactionStepList().insert( steps.end(), result.transaction().begin(), result.transaction().end() );
+      }
+      MIL << "Todo: " << result << endl;
+
+      ///////////////////////////////////////////////////////////////////
+      // Prepare execution of commit plugins:
+      ///////////////////////////////////////////////////////////////////
+      CommitPlugins commitPlugins;
+      if ( root() == "/" && ! policy_r.dryRun() )
+      {
+       Pathname plugindir( Pathname::assertprefix( _root, ZConfig::instance().pluginsPath()/"commit" ) );
+       commitPlugins.load( plugindir );
+      }
+      if ( ! commitPlugins.empty() )
+       commitPlugins.send( transactionPluginFrame( "COMMITBEGIN", steps ) );
+
+      ///////////////////////////////////////////////////////////////////
       // Write out a testcase if we're in dist upgrade mode.
       ///////////////////////////////////////////////////////////////////
       if ( getZYpp()->resolver()->upgradeMode() )
@@ -971,7 +1322,7 @@ namespace zypp
         }
       }
 
-      ///////////////////////////////////////////////////////////////////
+     ///////////////////////////////////////////////////////////////////
       // Store non-package data:
       ///////////////////////////////////////////////////////////////////
       if ( ! policy_r.dryRun() )
@@ -979,11 +1330,12 @@ namespace zypp
         filesystem::assert_dir( home() );
         // requested locales
         _requestedLocalesFile.setLocales( pool_r.getRequestedLocales() );
-        // weak locks
+       // autoinstalled
         {
-          SoftLocksFile::Data newdata;
-          pool_r.getActiveSoftLocks( newdata );
-          _softLocksFile.setData( newdata );
+         SolvIdentFile::Data newdata;
+         for ( sat::Queue::value_type id : result.rTransaction().autoInstalled() )
+           newdata.insert( IdString(id) );
+         _autoInstalledFile.setData( newdata );
         }
         // hard locks
         if ( ZConfig::instance().apply_locks_file() )
@@ -999,91 +1351,30 @@ namespace zypp
       }
 
       ///////////////////////////////////////////////////////////////////
-      // Compute transaction:
-      ///////////////////////////////////////////////////////////////////
-
-      ZYppCommitResult result( root() );
-      TargetImpl::PoolItemList to_uninstall;
-      TargetImpl::PoolItemList to_install;
-      TargetImpl::PoolItemList to_srcinstall;
-
-      {
-        pool::GetResolvablesToInsDel
-        collect( pool_r, policy_r.restrictToMedia() ? pool::GetResolvablesToInsDel::ORDER_BY_MEDIANR
-                 : pool::GetResolvablesToInsDel::ORDER_BY_SOURCE );
-        MIL << "GetResolvablesToInsDel: " << endl << collect << endl;
-        to_uninstall.swap ( collect._toDelete );
-        to_install.swap   ( collect._toInstall );
-        to_srcinstall.swap( collect._toSrcinstall );
-      }
-
-      if ( policy_r.restrictToMedia() )
-      {
-        MIL << "Restrict to media number " << policy_r.restrictToMedia() << endl;
-
-        TargetImpl::PoolItemList current_install;
-        TargetImpl::PoolItemList current_srcinstall;
-
-        // Collect until the 1st package from an unwanted media occurs.
-        // Further collection could violate install order.
-        bool hitUnwantedMedia = false;
-        for ( TargetImpl::PoolItemList::iterator it = to_install.begin(); it != to_install.end(); ++it )
-        {
-          ResObject::constPtr res( it->resolvable() );
-
-          if ( hitUnwantedMedia
-               || ( res->mediaNr() && res->mediaNr() != policy_r.restrictToMedia() ) )
-          {
-            hitUnwantedMedia = true;
-            result._remaining.push_back( *it );
-          }
-          else
-          {
-            current_install.push_back( *it );
-          }
-        }
-
-        for (TargetImpl::PoolItemList::iterator it = to_srcinstall.begin(); it != to_srcinstall.end(); ++it)
-        {
-          Resolvable::constPtr res( it->resolvable() );
-          Package::constPtr pkg( asKind<Package>(res) );
-          if ( pkg && policy_r.restrictToMedia() != pkg->mediaNr() ) // check medianr for packages only
-          {
-            result._srcremaining.push_back( *it );
-          }
-          else
-          {
-            current_srcinstall.push_back( *it );
-          }
-        }
-
-        to_install.swap   ( current_install );
-        to_srcinstall.swap( current_srcinstall );
-      }
-
-      ///////////////////////////////////////////////////////////////////
       // First collect and display all messages
       // associated with patches to be installed.
       ///////////////////////////////////////////////////////////////////
       if ( ! policy_r.dryRun() )
       {
-        for_( it, to_install.begin(), to_install.end() )
+        for_( it, steps.begin(), steps.end() )
         {
-          if ( ! isKind<Patch>(it->resolvable()) )
-            continue;
-          if ( ! it->status().isToBeInstalled() )
+         if ( ! it->satSolvable().isKind<Patch>() )
+           continue;
+
+         PoolItem pi( *it );
+          if ( ! pi.status().isToBeInstalled() )
             continue;
 
-          Patch::constPtr patch( asKind<Patch>(it->resolvable()) );
-          if ( ! patch->message().empty() )
-          {
-            MIL << "Show message for " << patch << endl;
-            callback::SendReport<target::PatchMessageReport> report;
-            if ( ! report->show( patch ) )
-            {
-              WAR << "commit aborted by the user" << endl;
-              ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
-            }
+          Patch::constPtr patch( asKind<Patch>(pi.resolvable()) );
+         if ( ! patch ||patch->message().empty()  )
+           continue;
+
+         MIL << "Show message for " << patch << endl;
+         callback::SendReport<target::PatchMessageReport> report;
+         if ( ! report->show( patch ) )
+         {
+           WAR << "commit aborted by the user" << endl;
+           ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
           }
         }
       }
@@ -1095,24 +1386,12 @@ namespace zypp
       ///////////////////////////////////////////////////////////////////
       // Remove/install packages.
       ///////////////////////////////////////////////////////////////////
-
       DBG << "commit log file is set to: " << HistoryLog::fname() << endl;
       if ( ! policy_r.dryRun() || policy_r.downloadMode() == DownloadOnly )
       {
-        // somewhat uggly constraint: The iterator passed to the CommitPackageCache
-        // must match begin and end of the install PoolItemList passed to commit.
-        // For the download policies it's the easiest, if we have just a single
-        // toInstall list. So we unify to_install and to_srcinstall. In case
-        // of errors we have to split it up again. This will be cleaned up when
-        // we introduce the new install order.
-        TargetImpl::PoolItemList items( to_install );
-        items.insert( items.end(), to_srcinstall.begin(), to_srcinstall.end() );
-
-        // prepare the package cache according to the download options:
-        repo::RepoMediaAccess access;
-        RepoProvidePackage repoProvidePackage( access, pool_r );
-        CommitPackageCache packageCache( items.begin(), items.end(),
-                                         root() / "tmp", repoProvidePackage );
+       // Prepare the package cache. Pass all items requiring download.
+        CommitPackageCache packageCache( root() );
+       packageCache.setCommitList( steps.begin(), steps.end() );
 
         bool miss = false;
         if ( policy_r.downloadMode() != DownloadAsNeeded )
@@ -1120,34 +1399,49 @@ namespace zypp
           // Preload the cache. Until now this means pre-loading all packages.
           // Once DownloadInHeaps is fully implemented, this will change and
           // we may actually have more than one heap.
-          for_( it, items.begin(), items.end() )
+          for_( it, steps.begin(), steps.end() )
           {
-            if ( (*it)->isKind<Package>() || (*it)->isKind<SrcPackage>() )
+           switch ( it->stepType() )
+           {
+             case sat::Transaction::TRANSACTION_INSTALL:
+             case sat::Transaction::TRANSACTION_MULTIINSTALL:
+               // proceed: only install actionas may require download.
+               break;
+
+             default:
+               // next: no download for or non-packages and delete actions.
+               continue;
+               break;
+           }
+
+           PoolItem pi( *it );
+            if ( pi->isKind<Package>() || pi->isKind<SrcPackage>() )
             {
               ManagedFile localfile;
               try
               {
-               if ( (*it)->isKind<Package>() )
+               // TODO: unify packageCache.get for Package and SrcPackage
+               if ( pi->isKind<Package>() )
                {
-                 localfile = packageCache.get( it );
+                 localfile = packageCache.get( pi );
                }
-               else if ( (*it)->isKind<SrcPackage>() )
+               else if ( pi->isKind<SrcPackage>() )
                {
                  repo::RepoMediaAccess access;
                  repo::SrcPackageProvider prov( access );
-                 localfile = prov.provideSrcPackage( (*it)->asKind<SrcPackage>() );
+                 localfile = prov.provideSrcPackage( pi->asKind<SrcPackage>() );
                }
                else
                {
-                 INT << "Don't know howto cache: Neither Package nor SrcPackage: " << *it << endl;
+                 INT << "Don't know howto cache: Neither Package nor SrcPackage: " << pi << endl;
                  continue;
                }
                 localfile.resetDispose(); // keep the package file in the cache
               }
               catch ( const AbortRequestException & exp )
               {
+               it->stepStage( sat::Transaction::STEP_ERROR );
                 miss = true;
-               result._errors.push_back( *it );
                 WAR << "commit cache preload aborted by the user" << endl;
                 ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
                 break;
@@ -1155,9 +1449,9 @@ namespace zypp
               catch ( const SkipRequestException & exp )
               {
                 ZYPP_CAUGHT( exp );
+               it->stepStage( sat::Transaction::STEP_ERROR );
                 miss = true;
-               result._errors.push_back( *it );
-                WAR << "Skipping cache preload package " << (*it)->asKind<Package>() << " in commit" << endl;
+                WAR << "Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
                 continue;
               }
               catch ( const Exception & exp )
@@ -1165,40 +1459,33 @@ namespace zypp
                 // bnc #395704: missing catch causes abort.
                 // TODO see if packageCache fails to handle errors correctly.
                 ZYPP_CAUGHT( exp );
+               it->stepStage( sat::Transaction::STEP_ERROR );
                 miss = true;
-               result._errors.push_back( *it );
-                INT << "Unexpected Error: Skipping cache preload package " << (*it)->asKind<Package>() << " in commit" << endl;
+                INT << "Unexpected Error: Skipping cache preload package " << pi->asKind<Package>() << " in commit" << endl;
                 continue;
               }
             }
           }
+          packageCache.preloaded( true ); // try to avoid duplicate infoInCache CBs in commit
         }
 
         if ( miss )
         {
           ERR << "Some packages could not be provided. Aborting commit."<< endl;
-          result._remaining.insert( result._remaining.end(), to_install.begin(), to_install.end() );
-          result._srcremaining.insert( result._srcremaining.end(), to_srcinstall.begin(), to_srcinstall.end() );
-        }
-        else if ( ! policy_r.dryRun() )
-        {
-          commit ( to_uninstall, policy_r, result, packageCache );
-          TargetImpl::PoolItemList bad = commit( items, policy_r, result, packageCache );
-          if ( ! bad.empty() )
-          {
-            for_( it, bad.begin(), bad.end() )
-            {
-              if ( isKind<SrcPackage>(it->resolvable()) )
-                result._srcremaining.push_back( *it );
-              else
-                result._remaining.push_back( *it );
-            }
-          }
         }
         else
-        {
-          DBG << "dryRun: Not installing/deleting anything." << endl;
-        }
+       {
+         if ( ! policy_r.dryRun() )
+         {
+           // if cache is preloaded, check for file conflicts
+           commitFindFileConflicts( policy_r, result );
+           commit( policy_r, packageCache, result );
+         }
+         else
+         {
+           DBG << "dryRun/downloadOnly: Not installing/deleting anything." << endl;
+         }
+       }
       }
       else
       {
@@ -1206,6 +1493,12 @@ namespace zypp
       }
 
       ///////////////////////////////////////////////////////////////////
+      // Send result to commit plugins:
+      ///////////////////////////////////////////////////////////////////
+      if ( ! commitPlugins.empty() )
+       commitPlugins.send( transactionPluginFrame( "COMMITEND", steps ) );
+
+      ///////////////////////////////////////////////////////////////////
       // Try to rebuild solv file while rpm database is still in cache
       ///////////////////////////////////////////////////////////////////
       if ( ! policy_r.dryRun() )
@@ -1213,55 +1506,84 @@ namespace zypp
         buildCache();
       }
 
-      result._result = (to_install.size() - result._remaining.size());
       MIL << "TargetImpl::commit(<pool>, " << policy_r << ") returns: " << result << endl;
       return result;
     }
 
-
     ///////////////////////////////////////////////////////////////////
     //
     // COMMIT internal
     //
     ///////////////////////////////////////////////////////////////////
-    TargetImpl::PoolItemList
-    TargetImpl::commit( const TargetImpl::PoolItemList & items_r,
-                        const ZYppCommitPolicy & policy_r,
-                        ZYppCommitResult & result_r,
-                        CommitPackageCache & packageCache_r )
+    namespace
     {
-      MIL << "TargetImpl::commit(<list>" << policy_r << ")" << items_r.size() << endl;
+      struct NotifyAttemptToModify
+      {
+       NotifyAttemptToModify( ZYppCommitResult & result_r ) : _result( result_r ) {}
+
+       void operator()()
+       { if ( _guard ) { _result.attemptToModify( true ); _guard = false; } }
+
+       TrueBool           _guard;
+       ZYppCommitResult & _result;
+      };
+    } // namespace
+
+    void TargetImpl::commit( const ZYppCommitPolicy & policy_r,
+                            CommitPackageCache & packageCache_r,
+                            ZYppCommitResult & result_r )
+    {
+      // steps: this is our todo-list
+      ZYppCommitResult::TransactionStepList & steps( result_r.rTransactionStepList() );
+      MIL << "TargetImpl::commit(<list>" << policy_r << ")" << steps.size() << endl;
+
+      HistoryLog().stampCommand();
+
+      // Send notification once upon 1st call to rpm
+      NotifyAttemptToModify attemptToModify( result_r );
 
       bool abort = false;
+
+      RpmPostTransCollector postTransCollector( _root );
       std::vector<sat::Solvable> successfullyInstalledPackages;
       TargetImpl::PoolItemList remaining;
 
-      for ( TargetImpl::PoolItemList::const_iterator it = items_r.begin(); it != items_r.end(); it++ )
+      for_( step, steps.begin(), steps.end() )
       {
-        if ( (*it)->isKind<Package>() )
+       PoolItem citem( *step );
+       if ( step->stepType() == sat::Transaction::TRANSACTION_IGNORE )
+       {
+         if ( citem->isKind<Package>() )
+         {
+           // for packages this means being obsoleted (by rpm)
+           // thius no additional action is needed.
+           step->stepStage( sat::Transaction::STEP_DONE );
+           continue;
+         }
+       }
+
+        if ( citem->isKind<Package>() )
         {
-          Package::constPtr p = (*it)->asKind<Package>();
-          if (it->status().isToBeInstalled())
+          Package::constPtr p = citem->asKind<Package>();
+          if ( citem.status().isToBeInstalled() )
           {
             ManagedFile localfile;
             try
             {
-              localfile = packageCache_r.get( it );
+             localfile = packageCache_r.get( citem );
             }
             catch ( const AbortRequestException &e )
             {
               WAR << "commit aborted by the user" << endl;
               abort = true;
-             result_r._errors.push_back( *it );
-             remaining.insert( remaining.end(), it, items_r.end() );
+             step->stepStage( sat::Transaction::STEP_ERROR );
              break;
             }
             catch ( const SkipRequestException &e )
             {
               ZYPP_CAUGHT( e );
               WAR << "Skipping package " << p << " in commit" << endl;
-             result_r._errors.push_back( *it );
-             remaining.push_back( *it );
+             step->stepStage( sat::Transaction::STEP_ERROR );
               continue;
             }
             catch ( const Exception &e )
@@ -1270,14 +1592,13 @@ namespace zypp
               // TODO see if packageCache fails to handle errors correctly.
               ZYPP_CAUGHT( e );
               INT << "Unexpected Error: Skipping package " << p << " in commit" << endl;
-             result_r._errors.push_back( *it );
-             remaining.push_back( *it );
+             step->stepStage( sat::Transaction::STEP_ERROR );
               continue;
             }
 
 #warning Exception handling
             // create a installation progress report proxy
-            RpmInstallPackageReceiver progress( it->resolvable() );
+            RpmInstallPackageReceiver progress( citem.resolvable() );
             progress.connect(); // disconnected on destruction.
 
             bool success = false;
@@ -1297,24 +1618,27 @@ namespace zypp
             if (policy_r.rpmExcludeDocs()) flags |= rpm::RPMINST_EXCLUDEDOCS;
             if (policy_r.rpmNoSignature()) flags |= rpm::RPMINST_NOSIGNATURE;
 
+           attemptToModify();
             try
             {
               progress.tryLevel( target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE );
-              rpm().installPackage( localfile, flags );
-              HistoryLog().install(*it);
+             if ( postTransCollector.collectScriptFromPackage( localfile ) )
+               flags |= rpm::RPMINST_NOPOSTTRANS;
+             rpm().installPackage( localfile, flags );
+              HistoryLog().install(citem);
 
               if ( progress.aborted() )
               {
                 WAR << "commit aborted by the user" << endl;
                 localfile.resetDispose(); // keep the package file in the cache
                 abort = true;
-               result_r._errors.push_back( *it );
-               remaining.insert( remaining.end(), it, items_r.end() );
+               step->stepStage( sat::Transaction::STEP_ERROR );
                 break;
               }
               else
               {
                 success = true;
+               step->stepStage( sat::Transaction::STEP_DONE );
               }
             }
             catch ( Exception & excpt_r )
@@ -1325,8 +1649,7 @@ namespace zypp
               if ( policy_r.dryRun() )
               {
                 WAR << "dry run failed" << endl;
-               result_r._errors.push_back( *it );
-               remaining.insert( remaining.end(), it, items_r.end() );
+               step->stepStage( sat::Transaction::STEP_ERROR );
                 break;
               }
               // else
@@ -1339,42 +1662,44 @@ namespace zypp
               {
                 WAR << "Install failed" << endl;
               }
-             result_r._errors.push_back( *it );
-             remaining.insert( remaining.end(), it, items_r.end() );
+              step->stepStage( sat::Transaction::STEP_ERROR );
               break; // stop
             }
 
             if ( success && !policy_r.dryRun() )
             {
-              it->status().resetTransact( ResStatus::USER );
-              // Remember to check this package for presence of patch scripts.
-              successfullyInstalledPackages.push_back( it->satSolvable() );
+              citem.status().resetTransact( ResStatus::USER );
+              successfullyInstalledPackages.push_back( citem.satSolvable() );
+             step->stepStage( sat::Transaction::STEP_DONE );
             }
           }
           else
           {
-            RpmRemovePackageReceiver progress( it->resolvable() );
+            RpmRemovePackageReceiver progress( citem.resolvable() );
             progress.connect(); // disconnected on destruction.
 
             bool success = false;
             rpm::RpmInstFlags flags( policy_r.rpmInstFlags() & rpm::RPMINST_JUSTDB );
             flags |= rpm::RPMINST_NODEPS;
             if (policy_r.dryRun()) flags |= rpm::RPMINST_TEST;
+
+           attemptToModify();
             try
             {
-              rpm().removePackage( p, flags );
-              HistoryLog().remove(*it);
+             rpm().removePackage( p, flags );
+              HistoryLog().remove(citem);
 
               if ( progress.aborted() )
               {
                 WAR << "commit aborted by the user" << endl;
                 abort = true;
-               result_r._errors.push_back( *it );
+               step->stepStage( sat::Transaction::STEP_ERROR );
                 break;
               }
               else
               {
                 success = true;
+               step->stepStage( sat::Transaction::STEP_DONE );
               }
             }
             catch (Exception & excpt_r)
@@ -1384,16 +1709,17 @@ namespace zypp
               {
                 WAR << "commit aborted by the user" << endl;
                 abort = true;
-               result_r._errors.push_back( *it );
+               step->stepStage( sat::Transaction::STEP_ERROR );
                 break;
               }
               // else
               WAR << "removal of " << p << " failed";
-             result_r._errors.push_back( *it );
+             step->stepStage( sat::Transaction::STEP_ERROR );
             }
             if ( success && !policy_r.dryRun() )
             {
-              it->status().resetTransact( ResStatus::USER );
+              citem.status().resetTransact( ResStatus::USER );
+             step->stepStage( sat::Transaction::STEP_DONE );
             }
           }
         }
@@ -1401,14 +1727,14 @@ namespace zypp
         {
           // Status is changed as the buddy package buddy
           // gets installed/deleted. Handle non-buddies only.
-          if ( ! it->buddy() )
+          if ( ! citem.buddy() )
           {
-            if ( (*it)->isKind<Product>() )
+            if ( citem->isKind<Product>() )
             {
-              Product::constPtr p = (*it)->asKind<Product>();
-              if ( it->status().isToBeInstalled() )
+              Product::constPtr p = citem->asKind<Product>();
+              if ( citem.status().isToBeInstalled() )
               {
-                ERR << "Can't install orphan product without release-package! " << (*it) << endl;
+                ERR << "Can't install orphan product without release-package! " << citem << endl;
               }
               else
               {
@@ -1417,7 +1743,7 @@ namespace zypp
                 std::string referenceFilename( p->referenceFilename() );
                 if ( referenceFilename.empty() )
                 {
-                  ERR << "Can't remove orphan product without 'referenceFilename'! " << (*it) << endl;
+                  ERR << "Can't remove orphan product without 'referenceFilename'! " << citem << endl;
                 }
                 else
                 {
@@ -1429,19 +1755,27 @@ namespace zypp
                 }
               }
             }
-            else if ( (*it)->isKind<SrcPackage>() && it->status().isToBeInstalled() )
+            else if ( citem->isKind<SrcPackage>() && citem.status().isToBeInstalled() )
             {
               // SrcPackage is install-only
-              SrcPackage::constPtr p = (*it)->asKind<SrcPackage>();
+              SrcPackage::constPtr p = citem->asKind<SrcPackage>();
               installSrcPackage( p );
             }
 
-            it->status().resetTransact( ResStatus::USER );
+            citem.status().resetTransact( ResStatus::USER );
+           step->stepStage( sat::Transaction::STEP_DONE );
           }
+
         }  // other resolvables
 
       } // for
 
+      // process all remembered posttrans scripts.
+      if ( !abort )
+       postTransCollector.executeScripts();
+      else
+       postTransCollector.discardScripts();
+
       // Check presence of update scripts/messages. If aborting,
       // at least log omitted scripts.
       if ( ! successfullyInstalledPackages.empty() )
@@ -1455,18 +1789,18 @@ namespace zypp
         // send messages after scripts in case some script generates output,
         // that should be kept in t %ghost message file.
         RunUpdateMessages( _root, ZConfig::instance().update_messagesPath(),
-                           successfullyInstalledPackages,
-                           result_r );
+                          successfullyInstalledPackages,
+                          result_r );
       }
 
       if ( abort )
       {
         ZYPP_THROW( TargetAbortedException( N_("Installation has been aborted as directed.") ) );
       }
-
-     return remaining;
     }
 
+    ///////////////////////////////////////////////////////////////////
+
     rpm::RpmDb & TargetImpl::rpm()
     {
       return _rpm;
@@ -1484,38 +1818,29 @@ namespace zypp
     }
 
     ///////////////////////////////////////////////////////////////////
-
-    Product::constPtr TargetImpl::baseProduct() const
-    {
-      ResPool pool(ResPool::instance());
-      for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
-      {
-        Product::constPtr p = (*it)->asKind<Product>();
-        if ( p->isTargetDistribution() )
-          return p;
-      }
-      return 0L;
-    }
-
-    ///////////////////////////////////////////////////////////////////
-
     namespace
     {
       parser::ProductFileData baseproductdata( const Pathname & root_r )
       {
+       parser::ProductFileData ret;
         PathInfo baseproduct( Pathname::assertprefix( root_r, "/etc/products.d/baseproduct" ) );
+
         if ( baseproduct.isFile() )
         {
           try
           {
-            return parser::ProductFileReader::scanFile( baseproduct.path() );
+            ret = parser::ProductFileReader::scanFile( baseproduct.path() );
           }
           catch ( const Exception & excpt )
           {
             ZYPP_CAUGHT( excpt );
           }
         }
-        return parser::ProductFileData();
+       else if ( PathInfo( Pathname::assertprefix( root_r, "/etc/products.d" ) ).isDir() )
+       {
+         ERR << "baseproduct symlink is dangling or missing: " << baseproduct << endl;
+       }
+        return ret;
       }
 
       inline Pathname staticGuessRoot( const Pathname & root_r )
@@ -1542,6 +1867,28 @@ namespace zypp
         }
         return std::string();
       }
+    } // namescpace
+    ///////////////////////////////////////////////////////////////////
+
+    Product::constPtr TargetImpl::baseProduct() const
+    {
+      ResPool pool(ResPool::instance());
+      for_( it, pool.byKindBegin<Product>(), pool.byKindEnd<Product>() )
+      {
+        Product::constPtr p = (*it)->asKind<Product>();
+        if ( p->isTargetDistribution() )
+          return p;
+      }
+      return nullptr;
+    }
+
+    LocaleSet TargetImpl::requestedLocales( const Pathname & root_r )
+    {
+      const Pathname needroot( staticGuessRoot(root_r) );
+      const Target_constPtr target( getZYpp()->getTarget() );
+      if ( target && target->root() == needroot )
+       return target->requestedLocales();
+      return RequestedLocalesFile( home(needroot) / "RequestedLocales" ).locales();
     }
 
     std::string TargetImpl::targetDistribution() const
@@ -1556,6 +1903,12 @@ namespace zypp
     std::string TargetImpl::targetDistributionRelease( const Pathname & root_r )
     { return baseproductdata( staticGuessRoot(root_r) ).registerRelease();}
 
+    std::string TargetImpl::targetDistributionFlavor() const
+    { return baseproductdata( _root ).registerFlavor(); }
+    // static version:
+    std::string TargetImpl::targetDistributionFlavor( const Pathname & root_r )
+    { return baseproductdata( staticGuessRoot(root_r) ).registerFlavor();}
+
     Target::DistributionLabel TargetImpl::distributionLabel() const
     {
       Target::DistributionLabel ret;
@@ -1642,14 +1995,19 @@ namespace zypp
     void TargetImpl::installSrcPackage( const SrcPackage_constPtr & srcPackage_r )
     {
       // provide on local disk
-      repo::RepoMediaAccess access_r;
-      repo::SrcPackageProvider prov( access_r );
-      ManagedFile localfile = prov.provideSrcPackage( srcPackage_r );
+      ManagedFile localfile = provideSrcPackage(srcPackage_r);
       // install it
       rpm().installPackage ( localfile );
     }
 
-    /////////////////////////////////////////////////////////////////
+    ManagedFile TargetImpl::provideSrcPackage( const SrcPackage_constPtr & srcPackage_r )
+    {
+      // provide on local disk
+      repo::RepoMediaAccess access_r;
+      repo::SrcPackageProvider prov( access_r );
+      return prov.provideSrcPackage( srcPackage_r );
+    }
+    ////////////////////////////////////////////////////////////////
   } // namespace target
   ///////////////////////////////////////////////////////////////////
   /////////////////////////////////////////////////////////////////