737cdc41cdb950a84e59495deff9cf36a2fd2268
[platform/upstream/libzypp.git] / zypp / solver / detail / SATResolver.cc
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 4 -*- */
2 /* SATResolver.cc
3  *
4  * Copyright (C) 2000-2002 Ximian, Inc.
5  * Copyright (C) 2005 SUSE Linux Products GmbH
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License,
9  * version 2, as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19  * 02111-1307, USA.
20  */
21 extern "C"
22 {
23 #include <solv/repo_solv.h>
24 #include <solv/poolarch.h>
25 #include <solv/evr.h>
26 #include <solv/poolvendor.h>
27 #include <solv/policy.h>
28 #include <solv/bitmap.h>
29 #include <solv/queue.h>
30 }
31
32 #define ZYPP_USE_RESOLVER_INTERNALS
33
34 #include "zypp/base/LogTools.h"
35 #include "zypp/base/Gettext.h"
36 #include "zypp/base/Algorithm.h"
37
38 #include "zypp/ZConfig.h"
39 #include "zypp/Product.h"
40 #include "zypp/sat/WhatProvides.h"
41 #include "zypp/sat/WhatObsoletes.h"
42 #include "zypp/sat/detail/PoolImpl.h"
43
44 #include "zypp/solver/detail/Resolver.h"
45 #include "zypp/solver/detail/SATResolver.h"
46
47 #include "zypp/solver/detail/ProblemSolutionCombi.h"
48 #include "zypp/solver/detail/ProblemSolutionIgnore.h"
49 #include "zypp/solver/detail/SolverQueueItemInstall.h"
50 #include "zypp/solver/detail/SolverQueueItemDelete.h"
51 #include "zypp/solver/detail/SystemCheck.h"
52 #include "zypp/solver/detail/SolutionAction.h"
53 #include "zypp/solver/detail/SolverQueueItem.h"
54
55 #define XDEBUG(x) do { if (base::logger::isExcessive()) XXX << x << std::endl;} while (0)
56
57 #undef ZYPP_BASE_LOGGER_LOGGROUP
58 #define ZYPP_BASE_LOGGER_LOGGROUP "zypp::solver"
59
60 /////////////////////////////////////////////////////////////////////////
61 namespace zypp
62 { ///////////////////////////////////////////////////////////////////////
63   ///////////////////////////////////////////////////////////////////////
64   namespace solver
65   { /////////////////////////////////////////////////////////////////////
66     /////////////////////////////////////////////////////////////////////
67     namespace detail
68     { ///////////////////////////////////////////////////////////////////
69
70       ///////////////////////////////////////////////////////////////////////
71       namespace
72       {
73         inline void solverSetFocus( sat::detail::CSolver & satSolver_r, const ResolverFocus & focus_r )
74         {
75           switch ( focus_r )
76           {
77             case ResolverFocus::Default:        // fallthrough to Job
78             case ResolverFocus::Job:
79               solver_set_flag( &satSolver_r, SOLVER_FLAG_FOCUS_INSTALLED, 0 );
80               solver_set_flag( &satSolver_r, SOLVER_FLAG_FOCUS_BEST,      0 );
81               break;
82             case ResolverFocus::Installed:
83               solver_set_flag( &satSolver_r, SOLVER_FLAG_FOCUS_INSTALLED, 1 );
84               solver_set_flag( &satSolver_r, SOLVER_FLAG_FOCUS_BEST,      0 );
85               break;
86             case ResolverFocus::Update:
87               solver_set_flag( &satSolver_r, SOLVER_FLAG_FOCUS_INSTALLED, 0 );
88               solver_set_flag( &satSolver_r, SOLVER_FLAG_FOCUS_BEST,      1 );
89               break;
90           }
91         }
92
93       } //namespace
94       ///////////////////////////////////////////////////////////////////////
95
96
97 using namespace std;
98
99 IMPL_PTR_TYPE(SATResolver);
100
101 #define MAYBE_CLEANDEPS (cleandepsOnRemove()?SOLVER_CLEANDEPS:0)
102
103 //---------------------------------------------------------------------------
104 // Callbacks for SAT policies
105 //---------------------------------------------------------------------------
106
107 int vendorCheck( sat::detail::CPool *pool, Solvable *solvable1, Solvable *solvable2 )
108 {
109   return VendorAttr::instance().equivalent( IdString(solvable1->vendor),
110                                             IdString(solvable2->vendor) ) ? 0 : 1;
111 }
112
113
114 inline std::string itemToString( const PoolItem & item )
115 {
116   if ( !item )
117     return std::string();
118
119   sat::Solvable slv( item.satSolvable() );
120   std::string ret( slv.asString() ); // n-v-r.a
121   if ( ! slv.isSystem() )
122   {
123     ret += "[";
124     ret += slv.repository().alias();
125     ret += "]";
126   }
127   return ret;
128 }
129
130 inline PoolItem getPoolItem( Id id_r )
131 {
132   PoolItem ret( (sat::Solvable( id_r )) );
133   if ( !ret && id_r )
134     INT << "id " << id_r << " not found in ZYPP pool." << endl;
135   return ret;
136 }
137
138 //---------------------------------------------------------------------------
139
140 std::ostream &
141 SATResolver::dumpOn( std::ostream & os ) const
142 {
143     os << "<resolver>" << endl;
144     if (_satSolver) {
145 #define OUTS(X) os << "  " << #X << "\t= " << solver_get_flag(_satSolver, SOLVER_FLAG_##X) << endl
146         OUTS( ALLOW_DOWNGRADE );
147         OUTS( ALLOW_ARCHCHANGE );
148         OUTS( ALLOW_VENDORCHANGE );
149         OUTS( ALLOW_NAMECHANGE );
150         OUTS( ALLOW_UNINSTALL );
151         OUTS( NO_UPDATEPROVIDE );
152         OUTS( SPLITPROVIDES );
153         OUTS( IGNORE_RECOMMENDED );
154         OUTS( ADD_ALREADY_RECOMMENDED );
155         OUTS( NO_INFARCHCHECK );
156         OUTS( KEEP_EXPLICIT_OBSOLETES );
157         OUTS( BEST_OBEY_POLICY );
158         OUTS( NO_AUTOTARGET );
159         OUTS( DUP_ALLOW_DOWNGRADE );
160         OUTS( DUP_ALLOW_ARCHCHANGE );
161         OUTS( DUP_ALLOW_VENDORCHANGE );
162         OUTS( DUP_ALLOW_NAMECHANGE );
163         OUTS( KEEP_ORPHANS );
164         OUTS( BREAK_ORPHANS );
165         OUTS( YUM_OBSOLETES );
166 #undef OUTS
167         os << "  focus  = "     << _focus << endl;
168         os << "  distupgrade    = "     << _distupgrade << endl;
169         os << "  distupgrade_removeunsupported  = " << _distupgrade_removeunsupported << endl;
170         os << "  solveSrcPackages       = "     << _solveSrcPackages << endl;
171         os << "  cleandepsOnRemove      = "     << _cleandepsOnRemove << endl;
172         os << "  fixsystem              = "     << _fixsystem << endl;
173     } else {
174         os << "<NULL>";
175     }
176     return os << "<resolver/>" << endl;
177 }
178
179 //---------------------------------------------------------------------------
180
181 // NOTE: flag defaults must be in sync with ZVARDEFAULT in Resolver.cc
182 SATResolver::SATResolver (const ResPool & pool, sat::detail::CPool *satPool)
183     : _pool(pool)
184     , _satPool(satPool)
185     , _satSolver(NULL)
186     , _focus                    ( ZConfig::instance().solver_focus() )
187     , _fixsystem(false)
188     , _allowdowngrade           ( false )
189     , _allownamechange          ( true )        // bsc#1071466
190     , _allowarchchange          ( false )
191     , _allowvendorchange        ( ZConfig::instance().solver_allowVendorChange() )
192     , _allowuninstall           ( false )
193     , _updatesystem(false)
194     , _noupdateprovide          ( false )
195     , _dosplitprovides          ( true )
196     , _onlyRequires             (ZConfig::instance().solver_onlyRequires())
197     , _ignorealreadyrecommended(true)
198     , _distupgrade(false)
199     , _distupgrade_removeunsupported(false)
200     , _dup_allowdowngrade       ( ZConfig::instance().solver_dupAllowDowngrade() )
201     , _dup_allownamechange      ( ZConfig::instance().solver_dupAllowNameChange() )
202     , _dup_allowarchchange      ( ZConfig::instance().solver_dupAllowArchChange() )
203     , _dup_allowvendorchange    ( ZConfig::instance().solver_dupAllowVendorChange() )
204     , _solveSrcPackages(false)
205     , _cleandepsOnRemove(ZConfig::instance().solver_cleandepsOnRemove())
206 {
207 }
208
209
210 SATResolver::~SATResolver()
211 {
212   solverEnd();
213 }
214
215 //---------------------------------------------------------------------------
216
217 ResPool
218 SATResolver::pool (void) const
219 {
220     return _pool;
221 }
222
223 //---------------------------------------------------------------------------
224
225 // copy marked item from solution back to pool
226 // if data != NULL, set as APPL_LOW (from establishPool())
227
228 static void
229 SATSolutionToPool (PoolItem item, const ResStatus & status, const ResStatus::TransactByValue causer)
230 {
231     // resetting
232     item.status().resetTransact (causer);
233     item.status().resetWeak ();
234
235     bool r;
236
237     // installation/deletion
238     if (status.isToBeInstalled()) {
239         r = item.status().setToBeInstalled (causer);
240         XDEBUG("SATSolutionToPool install returns " << item << ", " << r);
241     }
242     else if (status.isToBeUninstalledDueToUpgrade()) {
243         r = item.status().setToBeUninstalledDueToUpgrade (causer);
244         XDEBUG("SATSolutionToPool upgrade returns " << item << ", " <<  r);
245     }
246     else if (status.isToBeUninstalled()) {
247         r = item.status().setToBeUninstalled (causer);
248         XDEBUG("SATSolutionToPool remove returns " << item << ", " <<  r);
249     }
250
251     return;
252 }
253
254 //----------------------------------------------------------------------------
255 //----------------------------------------------------------------------------
256 // resolvePool
257 //----------------------------------------------------------------------------
258 //----------------------------------------------------------------------------
259 /////////////////////////////////////////////////////////////////////////
260 /// \class SATCollectTransact
261 /// \brief Commit helper functor distributing PoolItem by status into lists
262 ///
263 /// On the fly it clears all PoolItem bySolver/ByApplLow status.
264 /// The lists are cleared in the Ctor, populated by \ref operator().
265 /////////////////////////////////////////////////////////////////////////
266 struct SATCollectTransact : public resfilter::PoolItemFilterFunctor
267 {
268   SATCollectTransact( PoolItemList & items_to_install_r,
269                       PoolItemList & items_to_remove_r,
270                       PoolItemList & items_to_lock_r,
271                       PoolItemList & items_to_keep_r,
272                       bool solveSrcPackages_r )
273   : _items_to_install( items_to_install_r )
274   , _items_to_remove( items_to_remove_r )
275   , _items_to_lock( items_to_lock_r )
276   , _items_to_keep( items_to_keep_r )
277   , _solveSrcPackages( solveSrcPackages_r )
278   {
279     _items_to_install.clear();
280     _items_to_remove.clear();
281     _items_to_lock.clear();
282     _items_to_keep.clear();
283   }
284
285   bool operator()( const PoolItem & item_r )
286   {
287
288     ResStatus & itemStatus( item_r.status() );
289     bool by_solver = ( itemStatus.isBySolver() || itemStatus.isByApplLow() );
290
291     if ( by_solver )
292     {
293       // Clear former solver/establish resultd
294       itemStatus.resetTransact( ResStatus::APPL_LOW );
295       return true;      // -> back out here, don't re-queue former results
296     }
297
298     if ( !_solveSrcPackages && item_r.isKind<SrcPackage>() )
299     {
300       // Later we may continue on a per source package base.
301       return true; // dont process this source package.
302     }
303
304     switch ( itemStatus.getTransactValue() )
305     {
306       case ResStatus::TRANSACT:
307         itemStatus.isUninstalled() ?    _items_to_install.push_back( item_r )
308                                    :    _items_to_remove.push_back( item_r );   break;
309       case ResStatus::LOCKED:           _items_to_lock.push_back( item_r );     break;
310       case ResStatus::KEEP_STATE:       _items_to_keep.push_back( item_r );     break;
311     }
312     return true;
313   }
314
315 private:
316   PoolItemList & _items_to_install;
317   PoolItemList & _items_to_remove;
318   PoolItemList & _items_to_lock;
319   PoolItemList & _items_to_keep;
320   bool _solveSrcPackages;
321
322 };
323 /////////////////////////////////////////////////////////////////////////
324
325
326 //----------------------------------------------------------------------------
327 //----------------------------------------------------------------------------
328 // solving.....
329 //----------------------------------------------------------------------------
330 //----------------------------------------------------------------------------
331
332
333 class CheckIfUpdate : public resfilter::PoolItemFilterFunctor
334 {
335   public:
336     bool is_updated;
337     sat::Solvable _installed;
338
339     CheckIfUpdate( const sat::Solvable & installed_r )
340     : is_updated( false )
341     , _installed( installed_r )
342     {}
343
344     // check this item will be updated
345
346     bool operator()( const PoolItem & item )
347     {
348         if ( item.status().isToBeInstalled() )
349         {
350           if ( ! item.multiversionInstall() || sameNVRA( _installed, item ) )
351           {
352             is_updated = true;
353             return false;
354           }
355         }
356         return true;
357     }
358 };
359
360
361 class CollectPseudoInstalled : public resfilter::PoolItemFilterFunctor
362 {
363   public:
364     Queue *solvableQueue;
365
366     CollectPseudoInstalled( Queue *queue )
367         :solvableQueue (queue)
368     {}
369
370     // collecting PseudoInstalled items
371     bool operator()( PoolItem item )
372     {
373       if ( traits::isPseudoInstalled( item.satSolvable().kind() ) )
374         queue_push( solvableQueue, item.satSolvable().id() );
375       return true;
376     }
377 };
378
379 bool
380 SATResolver::solving(const CapabilitySet & requires_caps,
381                      const CapabilitySet & conflict_caps)
382 {
383     _satSolver = solver_create( _satPool );
384     ::pool_set_custom_vendorcheck( _satPool, &vendorCheck );
385     if (_fixsystem) {
386         queue_push( &(_jobQueue), SOLVER_VERIFY|SOLVER_SOLVABLE_ALL);
387         queue_push( &(_jobQueue), 0 );
388     }
389     if (_updatesystem) {
390         queue_push( &(_jobQueue), SOLVER_UPDATE|SOLVER_SOLVABLE_ALL);
391         queue_push( &(_jobQueue), 0 );
392     }
393     if (_distupgrade) {
394         queue_push( &(_jobQueue), SOLVER_DISTUPGRADE|SOLVER_SOLVABLE_ALL);
395         queue_push( &(_jobQueue), 0 );
396     }
397     if (_distupgrade_removeunsupported) {
398         queue_push( &(_jobQueue), SOLVER_DROP_ORPHANED|SOLVER_SOLVABLE_ALL);
399         queue_push( &(_jobQueue), 0 );
400     }
401     solverSetFocus( *_satSolver, _focus );
402     solver_set_flag(_satSolver, SOLVER_FLAG_ADD_ALREADY_RECOMMENDED, !_ignorealreadyrecommended);
403     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_DOWNGRADE,            _allowdowngrade);
404     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_NAMECHANGE,           _allownamechange);
405     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_ARCHCHANGE,           _allowarchchange);
406     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_VENDORCHANGE,         _allowvendorchange);
407     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_UNINSTALL,            _allowuninstall);
408     solver_set_flag(_satSolver, SOLVER_FLAG_NO_UPDATEPROVIDE,           _noupdateprovide);
409     solver_set_flag(_satSolver, SOLVER_FLAG_SPLITPROVIDES,              _dosplitprovides);
410     solver_set_flag(_satSolver, SOLVER_FLAG_IGNORE_RECOMMENDED,         false);         // resolve recommended namespaces
411     solver_set_flag(_satSolver, SOLVER_FLAG_ONLY_NAMESPACE_RECOMMENDED, _onlyRequires); //
412     solver_set_flag(_satSolver, SOLVER_FLAG_DUP_ALLOW_DOWNGRADE,        _dup_allowdowngrade );
413     solver_set_flag(_satSolver, SOLVER_FLAG_DUP_ALLOW_NAMECHANGE,       _dup_allownamechange );
414     solver_set_flag(_satSolver, SOLVER_FLAG_DUP_ALLOW_ARCHCHANGE,       _dup_allowarchchange );
415     solver_set_flag(_satSolver, SOLVER_FLAG_DUP_ALLOW_VENDORCHANGE,     _dup_allowvendorchange );
416
417     sat::Pool::instance().prepare();
418
419     // Solve !
420     MIL << "Starting solving...." << endl;
421     MIL << *this;
422     if ( solver_solve( _satSolver, &(_jobQueue) ) == 0 )
423     {
424       // bsc#1155819: Weakremovers of future product not evaluated.
425       // Do a 2nd run to cleanup weakremovers() of to be installed
426       // Produtcs unless removeunsupported is active (cleans up all).
427       if ( _distupgrade )
428       {
429         if ( _distupgrade_removeunsupported )
430           MIL << "Droplist processing not needed. RemoveUnsupported is On." << endl;
431         else if ( ! ZConfig::instance().solverUpgradeRemoveDroppedPackages() )
432           MIL << "Droplist processing is disabled in ZConfig." << endl;
433         else
434         {
435           bool resolve = false;
436           MIL << "Checking droplists ..." << endl;
437           // get Solvables to be installed...
438           sat::SolvableQueue decisionq;
439           solver_get_decisionqueue( _satSolver, decisionq );
440           for ( sat::Solvable::IdType slvid : decisionq )
441           {
442             sat::Solvable slv { slvid };
443             // get product buddies (they carry the weakremover)...
444             static const Capability productCap { "product()" };
445             if ( slv && slv.provides().matches( productCap ) )
446             {
447               CapabilitySet droplist { slv.valuesOfNamespace( "weakremover" ) };
448               MIL << "Droplist for " << slv << ": size " << droplist.size() << endl;
449               if ( !droplist.empty() )
450               {
451                 for ( const auto & cap : droplist )
452                 {
453                   INT << "  => " << cap << endl;
454                   queue_push( &_jobQueue, SOLVER_DROP_ORPHANED | SOLVER_SOLVABLE_NAME );
455                   queue_push( &_jobQueue, cap.id() );
456                 }
457                 // PIN product - a safety net to prevent cleanup from changing the decision for this product
458                 queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE );
459                 queue_push( &(_jobQueue), slvid );
460                 resolve = true;
461               }
462             }
463           }
464           if ( resolve )
465             solver_solve( _satSolver, &(_jobQueue) );
466         }
467       }
468     }
469     MIL << "....Solver end" << endl;
470
471     // copying solution back to zypp pool
472     //-----------------------------------------
473     _result_items_to_install.clear();
474     _result_items_to_remove.clear();
475
476     /*  solvables to be installed */
477     Queue decisionq;
478     queue_init(&decisionq);
479     solver_get_decisionqueue(_satSolver, &decisionq);
480     for ( int i = 0; i < decisionq.count; ++i )
481     {
482       sat::Solvable slv( decisionq.elements[i] );
483       if ( !slv || slv.isSystem() )
484         continue;
485
486       PoolItem poolItem( slv );
487       SATSolutionToPool (poolItem, ResStatus::toBeInstalled, ResStatus::SOLVER);
488       _result_items_to_install.push_back( poolItem );
489     }
490     queue_free(&decisionq);
491
492     /* solvables to be erased */
493     Repository systemRepo( sat::Pool::instance().findSystemRepo() ); // don't create if it does not exist
494     if ( systemRepo && ! systemRepo.solvablesEmpty() )
495     {
496       bool mustCheckObsoletes = false;
497       for_( it, systemRepo.solvablesBegin(), systemRepo.solvablesEnd() )
498       {
499         if (solver_get_decisionlevel(_satSolver, it->id()) > 0)
500           continue;
501
502         // Check if this is an update
503         CheckIfUpdate info( *it );
504         PoolItem poolItem( *it );
505         invokeOnEach( _pool.byIdentBegin( poolItem ),
506                       _pool.byIdentEnd( poolItem ),
507                       resfilter::ByUninstalled(),                       // ByUninstalled
508                       functor::functorRef<bool,PoolItem> (info) );
509
510         if (info.is_updated) {
511           SATSolutionToPool( poolItem, ResStatus::toBeUninstalledDueToUpgrade, ResStatus::SOLVER );
512         } else {
513           SATSolutionToPool( poolItem, ResStatus::toBeUninstalled, ResStatus::SOLVER );
514           if ( ! mustCheckObsoletes )
515             mustCheckObsoletes = true; // lazy check for UninstalledDueToObsolete
516         }
517         _result_items_to_remove.push_back (poolItem);
518       }
519       if ( mustCheckObsoletes )
520       {
521         sat::WhatObsoletes obsoleted( _result_items_to_install.begin(), _result_items_to_install.end() );
522         for_( it, obsoleted.poolItemBegin(), obsoleted.poolItemEnd() )
523         {
524           ResStatus & status( it->status() );
525           // WhatObsoletes contains installed items only!
526           if ( status.transacts() && ! status.isToBeUninstalledDueToUpgrade() )
527             status.setToBeUninstalledDueToObsolete();
528         }
529       }
530     }
531
532     Queue recommendations;
533     Queue suggestions;
534     Queue orphaned;
535     Queue unneeded;
536     queue_init(&recommendations);
537     queue_init(&suggestions);
538     queue_init(&orphaned);
539     queue_init(&unneeded);
540     solver_get_recommendations(_satSolver, &recommendations, &suggestions, 0);
541     solver_get_orphaned(_satSolver, &orphaned);
542     solver_get_unneeded(_satSolver, &unneeded, 1);
543     /*  solvables which are recommended */
544     for ( int i = 0; i < recommendations.count; ++i )
545     {
546       PoolItem poolItem( getPoolItem( recommendations.elements[i] ) );
547       poolItem.status().setRecommended( true );
548     }
549
550     /*  solvables which are suggested */
551     for ( int i = 0; i < suggestions.count; ++i )
552     {
553       PoolItem poolItem( getPoolItem( suggestions.elements[i] ) );
554       poolItem.status().setSuggested( true );
555     }
556
557     _problem_items.clear();
558     /*  solvables which are orphaned */
559     for ( int i = 0; i < orphaned.count; ++i )
560     {
561       PoolItem poolItem( getPoolItem( orphaned.elements[i] ) );
562       poolItem.status().setOrphaned( true );
563       _problem_items.push_back( poolItem );
564     }
565
566     /*  solvables which are unneeded */
567     for ( int i = 0; i < unneeded.count; ++i )
568     {
569       PoolItem poolItem( getPoolItem( unneeded.elements[i] ) );
570       poolItem.status().setUnneeded( true );
571     }
572
573     queue_free(&recommendations);
574     queue_free(&suggestions);
575     queue_free(&orphaned);
576     queue_free(&unneeded);
577
578     /* Write validation state back to pool */
579     Queue flags, solvableQueue;
580
581     queue_init(&flags);
582     queue_init(&solvableQueue);
583
584     CollectPseudoInstalled collectPseudoInstalled(&solvableQueue);
585     invokeOnEach( _pool.begin(),
586                   _pool.end(),
587                   functor::functorRef<bool,PoolItem> (collectPseudoInstalled) );
588     solver_trivial_installable(_satSolver, &solvableQueue, &flags );
589     for (int i = 0; i < solvableQueue.count; i++) {
590         PoolItem item = _pool.find (sat::Solvable(solvableQueue.elements[i]));
591         item.status().setUndetermined();
592
593         if (flags.elements[i] == -1) {
594             item.status().setNonRelevant();
595             XDEBUG("SATSolutionToPool(" << item << " ) nonRelevant !");
596         } else if (flags.elements[i] == 1) {
597             item.status().setSatisfied();
598             XDEBUG("SATSolutionToPool(" << item << " ) satisfied !");
599         } else if (flags.elements[i] == 0) {
600             item.status().setBroken();
601             XDEBUG("SATSolutionToPool(" << item << " ) broken !");
602         }
603     }
604     queue_free(&(solvableQueue));
605     queue_free(&flags);
606
607
608     // Solvables which were selected due requirements which have been made by the user will
609     // be selected by APPL_LOW. We can't use any higher level, because this setting must
610     // not serve as a request for the next solver run. APPL_LOW is reset before solving.
611     for (CapabilitySet::const_iterator iter = requires_caps.begin(); iter != requires_caps.end(); iter++) {
612         sat::WhatProvides rpmProviders(*iter);
613         for_( iter2, rpmProviders.begin(), rpmProviders.end() ) {
614             PoolItem poolItem(*iter2);
615             if (poolItem.status().isToBeInstalled()) {
616                 MIL << "User requirement " << *iter << " sets " << poolItem << endl;
617                 poolItem.status().setTransactByValue (ResStatus::APPL_LOW);
618             }
619         }
620     }
621     for (CapabilitySet::const_iterator iter = conflict_caps.begin(); iter != conflict_caps.end(); iter++) {
622         sat::WhatProvides rpmProviders(*iter);
623         for_( iter2, rpmProviders.begin(), rpmProviders.end() ) {
624             PoolItem poolItem(*iter2);
625             if (poolItem.status().isToBeUninstalled()) {
626                 MIL << "User conflict " << *iter << " sets " << poolItem << endl;
627                 poolItem.status().setTransactByValue (ResStatus::APPL_LOW);
628             }
629         }
630     }
631
632     if (solver_problem_count(_satSolver) > 0 )
633     {
634         ERR << "Solverrun finished with an ERROR" << endl;
635         return false;
636     }
637
638     return true;
639 }
640
641
642 void
643 SATResolver::solverInit(const PoolItemList & weakItems)
644 {
645
646     MIL << "SATResolver::solverInit()" << endl;
647
648     // remove old stuff
649     solverEnd();
650     queue_init( &_jobQueue );
651
652     // clear and rebuild: _items_to_install, _items_to_remove, _items_to_lock, _items_to_keep
653     {
654       SATCollectTransact collector( _items_to_install, _items_to_remove, _items_to_lock, _items_to_keep, solveSrcPackages() );
655       invokeOnEach ( _pool.begin(), _pool.end(), functor::functorRef<bool,PoolItem>( collector ) );
656     }
657
658     for (PoolItemList::const_iterator iter = weakItems.begin(); iter != weakItems.end(); iter++) {
659         Id id = (*iter)->satSolvable().id();
660         if (id == ID_NULL) {
661             ERR << "Weaken: " << *iter << " not found" << endl;
662         }
663         MIL << "Weaken dependencies of " << *iter << endl;
664         queue_push( &(_jobQueue), SOLVER_WEAKENDEPS | SOLVER_SOLVABLE );
665         queue_push( &(_jobQueue), id );
666     }
667
668     // Ad rules for retracted patches and packages
669     {
670       queue_push( &(_jobQueue), SOLVER_BLACKLIST|SOLVER_SOLVABLE_PROVIDES );
671       queue_push( &(_jobQueue), sat::Solvable::retractedToken.id() );
672       queue_push( &(_jobQueue), SOLVER_BLACKLIST|SOLVER_SOLVABLE_PROVIDES );
673       queue_push( &(_jobQueue), sat::Solvable::ptfToken.id() );
674     }
675
676     // Ad rules for changed requestedLocales
677     {
678       const auto & trackedLocaleIds( myPool().trackedLocaleIds() );
679
680       // just track changed locakes
681       for ( const auto & locale : trackedLocaleIds.added() )
682       {
683         queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE_PROVIDES );
684         queue_push( &(_jobQueue), Capability( ResolverNamespace::language, IdString(locale) ).id() );
685       }
686
687       for ( const auto & locale : trackedLocaleIds.removed() )
688       {
689         queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE_PROVIDES | SOLVER_CLEANDEPS ); // needs uncond. SOLVER_CLEANDEPS!
690         queue_push( &(_jobQueue), Capability( ResolverNamespace::language, IdString(locale) ).id() );
691       }
692     }
693
694     // Add rules for parallel installable resolvables with different versions
695     for ( const sat::Solvable & solv : myPool().multiversionList() )
696     {
697       queue_push( &(_jobQueue), SOLVER_NOOBSOLETES | SOLVER_SOLVABLE );
698       queue_push( &(_jobQueue), solv.id() );
699     }
700
701     ::pool_add_userinstalled_jobs(_satPool, sat::Pool::instance().autoInstalled(), &(_jobQueue), GET_USERINSTALLED_NAMES|GET_USERINSTALLED_INVERTED);
702 }
703
704 void
705 SATResolver::solverEnd()
706 {
707   // cleanup
708   if ( _satSolver )
709   {
710     solver_free(_satSolver);
711     _satSolver = NULL;
712     queue_free( &(_jobQueue) );
713   }
714 }
715
716
717 bool
718 SATResolver::resolvePool(const CapabilitySet & requires_caps,
719                          const CapabilitySet & conflict_caps,
720                          const PoolItemList & weakItems,
721                          const std::set<Repository> & upgradeRepos)
722 {
723     MIL << "SATResolver::resolvePool()" << endl;
724
725     // initialize
726     solverInit(weakItems);
727
728     for (PoolItemList::const_iterator iter = _items_to_install.begin(); iter != _items_to_install.end(); iter++) {
729         Id id = (*iter)->satSolvable().id();
730         if (id == ID_NULL) {
731             ERR << "Install: " << *iter << " not found" << endl;
732         } else {
733             MIL << "Install " << *iter << endl;
734             queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE );
735             queue_push( &(_jobQueue), id );
736         }
737     }
738
739     for (PoolItemList::const_iterator iter = _items_to_remove.begin(); iter != _items_to_remove.end(); iter++) {
740         Id id = (*iter)->satSolvable().id();
741         if (id == ID_NULL) {
742             ERR << "Delete: " << *iter << " not found" << endl;
743         } else {
744             MIL << "Delete " << *iter << endl;
745             queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE | MAYBE_CLEANDEPS );
746             queue_push( &(_jobQueue), id);
747         }
748     }
749
750     for_( iter, upgradeRepos.begin(), upgradeRepos.end() )
751     {
752         queue_push( &(_jobQueue), SOLVER_DISTUPGRADE | SOLVER_SOLVABLE_REPO );
753         queue_push( &(_jobQueue), iter->get()->repoid );
754         MIL << "Upgrade repo " << *iter << endl;
755     }
756
757     for (CapabilitySet::const_iterator iter = requires_caps.begin(); iter != requires_caps.end(); iter++) {
758         queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE_PROVIDES );
759         queue_push( &(_jobQueue), iter->id() );
760         MIL << "Requires " << *iter << endl;
761     }
762
763     for (CapabilitySet::const_iterator iter = conflict_caps.begin(); iter != conflict_caps.end(); iter++) {
764         queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE_PROVIDES | MAYBE_CLEANDEPS );
765         queue_push( &(_jobQueue), iter->id() );
766         MIL << "Conflicts " << *iter << endl;
767     }
768
769     // set requirements for a running system
770     setSystemRequirements();
771
772     // set locks for the solver
773     setLocks();
774
775     // solving
776     bool ret = solving(requires_caps, conflict_caps);
777
778     (ret?MIL:WAR) << "SATResolver::resolvePool() done. Ret:" << ret <<  endl;
779     return ret;
780 }
781
782
783 bool
784 SATResolver::resolveQueue(const SolverQueueItemList &requestQueue,
785                           const PoolItemList & weakItems)
786 {
787     MIL << "SATResolver::resolvQueue()" << endl;
788
789     // initialize
790     solverInit(weakItems);
791
792     // generate solver queue
793     for (SolverQueueItemList::const_iterator iter = requestQueue.begin(); iter != requestQueue.end(); iter++) {
794         (*iter)->addRule(_jobQueue);
795     }
796
797     // Add addition item status to the resolve-queue cause these can be set by problem resolutions
798     for (PoolItemList::const_iterator iter = _items_to_install.begin(); iter != _items_to_install.end(); iter++) {
799         Id id = (*iter)->satSolvable().id();
800         if (id == ID_NULL) {
801             ERR << "Install: " << *iter << " not found" << endl;
802         } else {
803             MIL << "Install " << *iter << endl;
804             queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE );
805             queue_push( &(_jobQueue), id );
806         }
807     }
808     for (PoolItemList::const_iterator iter = _items_to_remove.begin(); iter != _items_to_remove.end(); iter++) {
809         sat::detail::IdType ident( (*iter)->satSolvable().ident().id() );
810         MIL << "Delete " << *iter << ident << endl;
811         queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE_NAME | MAYBE_CLEANDEPS );
812         queue_push( &(_jobQueue), ident);
813     }
814
815     // set requirements for a running system
816     setSystemRequirements();
817
818     // set locks for the solver
819     setLocks();
820
821     // solving
822     bool ret = solving();
823
824     MIL << "SATResolver::resolveQueue() done. Ret:" << ret <<  endl;
825     return ret;
826 }
827
828 /** \todo duplicate code to be joined with \ref solving. */
829 void SATResolver::doUpdate()
830 {
831     MIL << "SATResolver::doUpdate()" << endl;
832
833     // initialize
834     solverInit(PoolItemList());
835
836     // set requirements for a running system
837     setSystemRequirements();
838
839     // set locks for the solver
840     setLocks();
841
842     _satSolver = solver_create( _satPool );
843     ::pool_set_custom_vendorcheck( _satPool, &vendorCheck );
844     if (_fixsystem) {
845         queue_push( &(_jobQueue), SOLVER_VERIFY|SOLVER_SOLVABLE_ALL);
846         queue_push( &(_jobQueue), 0 );
847     }
848     if (1) {
849         queue_push( &(_jobQueue), SOLVER_UPDATE|SOLVER_SOLVABLE_ALL);
850         queue_push( &(_jobQueue), 0 );
851     }
852     if (_distupgrade) {
853         queue_push( &(_jobQueue), SOLVER_DISTUPGRADE|SOLVER_SOLVABLE_ALL);
854         queue_push( &(_jobQueue), 0 );
855     }
856     if (_distupgrade_removeunsupported) {
857         queue_push( &(_jobQueue), SOLVER_DROP_ORPHANED|SOLVER_SOLVABLE_ALL);
858         queue_push( &(_jobQueue), 0 );
859     }
860     solverSetFocus( *_satSolver, _focus );
861     solver_set_flag(_satSolver, SOLVER_FLAG_ADD_ALREADY_RECOMMENDED, !_ignorealreadyrecommended);
862     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_DOWNGRADE,            _allowdowngrade);
863     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_NAMECHANGE,           _allownamechange);
864     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_ARCHCHANGE,           _allowarchchange);
865     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_VENDORCHANGE,         _allowvendorchange);
866     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_UNINSTALL,            _allowuninstall);
867     solver_set_flag(_satSolver, SOLVER_FLAG_NO_UPDATEPROVIDE,           _noupdateprovide);
868     solver_set_flag(_satSolver, SOLVER_FLAG_SPLITPROVIDES,              _dosplitprovides);
869     solver_set_flag(_satSolver, SOLVER_FLAG_IGNORE_RECOMMENDED,         false);         // resolve recommended namespaces
870     solver_set_flag(_satSolver, SOLVER_FLAG_ONLY_NAMESPACE_RECOMMENDED, _onlyRequires); //
871
872     sat::Pool::instance().prepare();
873
874     // Solve !
875     MIL << "Starting solving for update...." << endl;
876     MIL << *this;
877     solver_solve( _satSolver, &(_jobQueue) );
878     MIL << "....Solver end" << endl;
879
880     // copying solution back to zypp pool
881     //-----------------------------------------
882
883     /*  solvables to be installed */
884     Queue decisionq;
885     queue_init(&decisionq);
886     solver_get_decisionqueue(_satSolver, &decisionq);
887     for (int i = 0; i < decisionq.count; i++)
888     {
889       Id p;
890       p = decisionq.elements[i];
891       if (p < 0 || !sat::Solvable(p))
892         continue;
893       if (sat::Solvable(p).repository().get() == _satSolver->pool->installed)
894         continue;
895
896       PoolItem poolItem = _pool.find (sat::Solvable(p));
897       if (poolItem) {
898           SATSolutionToPool (poolItem, ResStatus::toBeInstalled, ResStatus::SOLVER);
899       } else {
900           ERR << "id " << p << " not found in ZYPP pool." << endl;
901       }
902     }
903     queue_free(&decisionq);
904
905     /* solvables to be erased */
906     for (int i = _satSolver->pool->installed->start; i < _satSolver->pool->installed->start + _satSolver->pool->installed->nsolvables; i++)
907     {
908       if (solver_get_decisionlevel(_satSolver, i) > 0)
909           continue;
910
911       PoolItem poolItem( _pool.find( sat::Solvable(i) ) );
912       if (poolItem) {
913           // Check if this is an update
914           CheckIfUpdate info( (sat::Solvable(i)) );
915           invokeOnEach( _pool.byIdentBegin( poolItem ),
916                         _pool.byIdentEnd( poolItem ),
917                         resfilter::ByUninstalled(),                     // ByUninstalled
918                         functor::functorRef<bool,PoolItem> (info) );
919
920           if (info.is_updated) {
921               SATSolutionToPool (poolItem, ResStatus::toBeUninstalledDueToUpgrade , ResStatus::SOLVER);
922           } else {
923               SATSolutionToPool (poolItem, ResStatus::toBeUninstalled, ResStatus::SOLVER);
924           }
925       } else {
926           ERR << "id " << i << " not found in ZYPP pool." << endl;
927       }
928     }
929     MIL << "SATResolver::doUpdate() done" << endl;
930 }
931
932
933
934 //----------------------------------------------------------------------------
935 //----------------------------------------------------------------------------
936 // error handling
937 //----------------------------------------------------------------------------
938 //----------------------------------------------------------------------------
939
940 //----------------------------------------------------------------------------
941 // helper function
942 //----------------------------------------------------------------------------
943
944 struct FindPackage : public resfilter::ResObjectFilterFunctor
945 {
946     ProblemSolutionCombi *problemSolution;
947     TransactionKind action;
948     FindPackage (ProblemSolutionCombi *p, const TransactionKind act)
949        : problemSolution (p)
950        , action (act)
951         {
952         }
953
954     bool operator()( PoolItem p)
955    {
956        problemSolution->addSingleAction (p, action);
957        return true;
958    }
959 };
960
961
962 //----------------------------------------------------------------------------
963 // Checking if this solvable/item has a buddy which reflect the real
964 // user visible description of an item
965 // e.g. The release package has a buddy to the concerning product item.
966 // This user want's the message "Product foo conflicts with product bar" and
967 // NOT "package release-foo conflicts with package release-bar"
968 // (ma: that's why we should map just packages to buddies, not vice versa)
969 //----------------------------------------------------------------------------
970 inline sat::Solvable mapBuddy( const PoolItem & item_r )
971 {
972   if ( item_r.satSolvable().isKind<Package>() )
973   {
974     sat::Solvable buddy = item_r.buddy();
975     if ( buddy )
976       return buddy;
977   }
978   return item_r.satSolvable();
979 }
980 inline sat::Solvable mapBuddy( sat::Solvable item_r )
981 { return mapBuddy( PoolItem( item_r ) ); }
982
983 PoolItem SATResolver::mapItem ( const PoolItem & item )
984 { return PoolItem( mapBuddy( item ) ); }
985
986 sat::Solvable SATResolver::mapSolvable ( const Id & id )
987 { return mapBuddy( sat::Solvable(id) ); }
988
989 std::vector<std::string> SATResolver::SATgetCompleteProblemInfoStrings ( Id problem )
990 {
991   std::vector<std::string> ret;
992   sat::Queue problems;
993   solver_findallproblemrules( _satSolver, problem, problems );
994
995   bool nobad = false;
996
997   //filter out generic rule information if more explicit ones are available
998   for ( sat::Queue::size_type i = 0; i < problems.size(); i++ ) {
999     SolverRuleinfo ruleClass = solver_ruleclass( _satSolver, problems[i]);
1000     if ( ruleClass != SolverRuleinfo::SOLVER_RULE_UPDATE && ruleClass != SolverRuleinfo::SOLVER_RULE_JOB ) {
1001       nobad = true;
1002       break;
1003     }
1004   }
1005   for ( sat::Queue::size_type i = 0; i < problems.size(); i++ ) {
1006     SolverRuleinfo ruleClass = solver_ruleclass( _satSolver, problems[i]);
1007     if ( nobad && ( ruleClass == SolverRuleinfo::SOLVER_RULE_UPDATE || ruleClass == SolverRuleinfo::SOLVER_RULE_JOB ) ) {
1008       continue;
1009     }
1010
1011     std::string detail;
1012     Id ignore = 0;
1013     std::string pInfo = SATproblemRuleInfoString( problems[i], detail, ignore );
1014
1015     //we get the same string multiple times, reduce the noise
1016     if ( std::find( ret.begin(), ret.end(), pInfo ) == ret.end() )
1017       ret.push_back( pInfo );
1018   }
1019   return ret;
1020 }
1021
1022 string SATResolver::SATprobleminfoString(Id problem, string &detail, Id &ignoreId)
1023 {
1024   // FIXME: solver_findallproblemrules to get all rules for this problem
1025   // (the 'most relevabt' one returned by solver_findproblemrule is embedded
1026   Id probr = solver_findproblemrule(_satSolver, problem);
1027   return SATproblemRuleInfoString( probr, detail, ignoreId );
1028 }
1029
1030 std::string SATResolver::SATproblemRuleInfoString (Id probr, std::string &detail, Id &ignoreId)
1031 {
1032   string ret;
1033   sat::detail::CPool *pool = _satSolver->pool;
1034   Id dep, source, target;
1035   SolverRuleinfo type = solver_ruleinfo(_satSolver, probr, &source, &target, &dep);
1036
1037   ignoreId = 0;
1038
1039   sat::Solvable s = mapSolvable( source );
1040   sat::Solvable s2 = mapSolvable( target );
1041
1042   // @FIXME, these strings are a duplicate copied from the libsolv library
1043   // to provide translations. Instead of having duplicate code we should
1044   // translate those strings directly in libsolv
1045   switch ( type )
1046   {
1047       case SOLVER_RULE_DISTUPGRADE:
1048           ret = str::form (_("%s does not belong to a distupgrade repository"), s.asString().c_str());
1049           break;
1050       case SOLVER_RULE_INFARCH:
1051           ret = str::form (_("%s has inferior architecture"), s.asString().c_str());
1052           break;
1053       case SOLVER_RULE_UPDATE:
1054           ret = str::form (_("problem with installed package %s"), s.asString().c_str());
1055           break;
1056       case SOLVER_RULE_JOB:
1057           ret = _("conflicting requests");
1058           break;
1059       case SOLVER_RULE_PKG:
1060           ret = _("some dependency problem");
1061           break;
1062       case SOLVER_RULE_JOB_NOTHING_PROVIDES_DEP:
1063           ret = str::form (_("nothing provides requested %s"), pool_dep2str(pool, dep));
1064           detail += _("Have you enabled all requested repositories?");
1065           break;
1066       case SOLVER_RULE_JOB_UNKNOWN_PACKAGE:
1067           ret = str::form (_("package %s does not exist"), pool_dep2str(pool, dep));
1068           detail += _("Have you enabled all requested repositories?");
1069           break;
1070       case SOLVER_RULE_JOB_UNSUPPORTED:
1071           ret = _("unsupported request");
1072           break;
1073       case SOLVER_RULE_JOB_PROVIDED_BY_SYSTEM:
1074           ret = str::form (_("%s is provided by the system and cannot be erased"), pool_dep2str(pool, dep));
1075           break;
1076       case SOLVER_RULE_PKG_NOT_INSTALLABLE:
1077           ret = str::form (_("%s is not installable"), s.asString().c_str());
1078           break;
1079       case SOLVER_RULE_PKG_NOTHING_PROVIDES_DEP:
1080           ignoreId = source; // for setting weak dependencies
1081           ret = str::form (_("nothing provides %s needed by %s"), pool_dep2str(pool, dep), s.asString().c_str());
1082           break;
1083       case SOLVER_RULE_PKG_SAME_NAME:
1084           ret = str::form (_("cannot install both %s and %s"), s.asString().c_str(), s2.asString().c_str());
1085           break;
1086       case SOLVER_RULE_PKG_CONFLICTS:
1087           ret = str::form (_("%s conflicts with %s provided by %s"), s.asString().c_str(), pool_dep2str(pool, dep), s2.asString().c_str());
1088           break;
1089       case SOLVER_RULE_PKG_OBSOLETES:
1090           ret = str::form (_("%s obsoletes %s provided by %s"), s.asString().c_str(), pool_dep2str(pool, dep), s2.asString().c_str());
1091           break;
1092       case SOLVER_RULE_PKG_INSTALLED_OBSOLETES:
1093           ret = str::form (_("installed %s obsoletes %s provided by %s"), s.asString().c_str(), pool_dep2str(pool, dep), s2.asString().c_str());
1094           break;
1095       case SOLVER_RULE_PKG_SELF_CONFLICT:
1096           ret = str::form (_("solvable %s conflicts with %s provided by itself"), s.asString().c_str(), pool_dep2str(pool, dep));
1097           break;
1098       case SOLVER_RULE_PKG_REQUIRES: {
1099           ignoreId = source; // for setting weak dependencies
1100           Capability cap(dep);
1101           sat::WhatProvides possibleProviders(cap);
1102
1103           // check, if a provider will be deleted
1104           typedef list<PoolItem> ProviderList;
1105           ProviderList providerlistInstalled, providerlistUninstalled;
1106           for_( iter1, possibleProviders.begin(), possibleProviders.end() ) {
1107               PoolItem provider1 = ResPool::instance().find( *iter1 );
1108               // find pair of an installed/uninstalled item with the same NVR
1109               bool found = false;
1110               for_( iter2, possibleProviders.begin(), possibleProviders.end() ) {
1111                   PoolItem provider2 = ResPool::instance().find( *iter2 );
1112                   if (compareByNVR (provider1,provider2) == 0
1113                       && ( (provider1.status().isInstalled() && provider2.status().isUninstalled())
1114                           || (provider2.status().isInstalled() && provider1.status().isUninstalled()) ))  {
1115                       found = true;
1116                       break;
1117                   }
1118               }
1119               if (!found) {
1120                   if (provider1.status().isInstalled())
1121                       providerlistInstalled.push_back(provider1);
1122                   else
1123                       providerlistUninstalled.push_back(provider1);
1124               }
1125           }
1126
1127           ret = str::form (_("%s requires %s, but this requirement cannot be provided"), s.asString().c_str(), pool_dep2str(pool, dep));
1128           if (providerlistInstalled.size() > 0) {
1129               detail += _("deleted providers: ");
1130               for (ProviderList::const_iterator iter = providerlistInstalled.begin(); iter != providerlistInstalled.end(); iter++) {
1131                   if (iter == providerlistInstalled.begin())
1132                       detail += itemToString( *iter );
1133                   else
1134                       detail += "\n                   " + itemToString( mapItem(*iter) );
1135               }
1136           }
1137           if (providerlistUninstalled.size() > 0) {
1138               if (detail.size() > 0)
1139                   detail += _("\nnot installable providers: ");
1140               else
1141                   detail = _("not installable providers: ");
1142               for (ProviderList::const_iterator iter = providerlistUninstalled.begin(); iter != providerlistUninstalled.end(); iter++) {
1143                   if (iter == providerlistUninstalled.begin())
1144                       detail += itemToString( *iter );
1145                   else
1146                       detail += "\n                   " + itemToString( mapItem(*iter) );
1147               }
1148           }
1149           break;
1150       }
1151       default: {
1152           DBG << "Unknown rule type(" << type << ") going to query libsolv for rule information." << endl;
1153           ret = str::asString( ::solver_problemruleinfo2str( _satSolver, type, static_cast<Id>(s.id()), static_cast<Id>(s2.id()), dep ) );
1154           break;
1155       }
1156   }
1157   return ret;
1158 }
1159
1160 ResolverProblemList
1161 SATResolver::problems ()
1162 {
1163     ResolverProblemList resolverProblems;
1164     if (_satSolver && solver_problem_count(_satSolver)) {
1165         sat::detail::CPool *pool = _satSolver->pool;
1166         int pcnt;
1167         Id p, rp, what;
1168         Id problem, solution, element;
1169         sat::Solvable s, sd;
1170
1171         CapabilitySet system_requires = SystemCheck::instance().requiredSystemCap();
1172         CapabilitySet system_conflicts = SystemCheck::instance().conflictSystemCap();
1173
1174         MIL << "Encountered problems! Here are the solutions:\n" << endl;
1175         pcnt = 1;
1176         problem = 0;
1177         while ((problem = solver_next_problem(_satSolver, problem)) != 0) {
1178             MIL << "Problem " <<  pcnt++ << ":" << endl;
1179             MIL << "====================================" << endl;
1180             string detail;
1181             Id ignoreId;
1182             string whatString = SATprobleminfoString (problem,detail,ignoreId);
1183             MIL << whatString << endl;
1184             MIL << "------------------------------------" << endl;
1185             ResolverProblem_Ptr resolverProblem = new ResolverProblem (whatString, detail, SATgetCompleteProblemInfoStrings( problem ));
1186
1187             solution = 0;
1188             while ((solution = solver_next_solution(_satSolver, problem, solution)) != 0) {
1189                 element = 0;
1190                 ProblemSolutionCombi *problemSolution = new ProblemSolutionCombi;
1191                 while ((element = solver_next_solutionelement(_satSolver, problem, solution, element, &p, &rp)) != 0) {
1192                     if (p == SOLVER_SOLUTION_JOB) {
1193                         /* job, rp is index into job queue */
1194                         what = _jobQueue.elements[rp];
1195                         switch (_jobQueue.elements[rp-1]&(SOLVER_SELECTMASK|SOLVER_JOBMASK))
1196                         {
1197                             case SOLVER_INSTALL | SOLVER_SOLVABLE: {
1198                                 s = mapSolvable (what);
1199                                 PoolItem poolItem = _pool.find (s);
1200                                 if (poolItem) {
1201                                     if (pool->installed && s.get()->repo == pool->installed) {
1202                                         problemSolution->addSingleAction (poolItem, REMOVE);
1203                                         string description = str::form (_("remove lock to allow removal of %s"),  s.asString().c_str() );
1204                                         MIL << description << endl;
1205                                         problemSolution->addDescription (description);
1206                                     } else {
1207                                         problemSolution->addSingleAction (poolItem, KEEP);
1208                                         string description = str::form (_("do not install %s"), s.asString().c_str());
1209                                         MIL << description << endl;
1210                                         problemSolution->addDescription (description);
1211                                     }
1212                                 } else {
1213                                     ERR << "SOLVER_INSTALL_SOLVABLE: No item found for " << s.asString() << endl;
1214                                 }
1215                             }
1216                                 break;
1217                             case SOLVER_ERASE | SOLVER_SOLVABLE: {
1218                                 s = mapSolvable (what);
1219                                 PoolItem poolItem = _pool.find (s);
1220                                 if (poolItem) {
1221                                     if (pool->installed && s.get()->repo == pool->installed) {
1222                                         problemSolution->addSingleAction (poolItem, KEEP);
1223                                         string description = str::form (_("keep %s"), s.asString().c_str());
1224                                         MIL << description << endl;
1225                                         problemSolution->addDescription (description);
1226                                     } else {
1227                                         problemSolution->addSingleAction (poolItem, UNLOCK);
1228                                         string description = str::form (_("remove lock to allow installation of %s"), itemToString( poolItem ).c_str());
1229                                         MIL << description << endl;
1230                                         problemSolution->addDescription (description);
1231                                     }
1232                                 } else {
1233                                     ERR << "SOLVER_ERASE_SOLVABLE: No item found for " << s.asString() << endl;
1234                                 }
1235                             }
1236                                 break;
1237                             case SOLVER_INSTALL | SOLVER_SOLVABLE_NAME:
1238                                 {
1239                                 IdString ident( what );
1240                                 SolverQueueItemInstall_Ptr install =
1241                                     new SolverQueueItemInstall(_pool, ident.asString(), false );
1242                                 problemSolution->addSingleAction (install, REMOVE_SOLVE_QUEUE_ITEM);
1243
1244                                 string description = str::form (_("do not install %s"), ident.c_str() );
1245                                 MIL << description << endl;
1246                                 problemSolution->addDescription (description);
1247                                 }
1248                                 break;
1249                             case SOLVER_ERASE | SOLVER_SOLVABLE_NAME:
1250                                 {
1251                                 // As we do not know, if this request has come from resolvePool or
1252                                 // resolveQueue we will have to take care for both cases.
1253                                 IdString ident( what );
1254                                 FindPackage info (problemSolution, KEEP);
1255                                 invokeOnEach( _pool.byIdentBegin( ident ),
1256                                               _pool.byIdentEnd( ident ),
1257                                               functor::chain (resfilter::ByInstalled (),                        // ByInstalled
1258                                                               resfilter::ByTransact ()),                        // will be deinstalled
1259                                               functor::functorRef<bool,PoolItem> (info) );
1260
1261                                 SolverQueueItemDelete_Ptr del =
1262                                     new SolverQueueItemDelete(_pool, ident.asString(), false );
1263                                 problemSolution->addSingleAction (del, REMOVE_SOLVE_QUEUE_ITEM);
1264
1265                                 string description = str::form (_("keep %s"), ident.c_str());
1266                                 MIL << description << endl;
1267                                 problemSolution->addDescription (description);
1268                                 }
1269                                 break;
1270                             case SOLVER_INSTALL | SOLVER_SOLVABLE_PROVIDES:
1271                                 {
1272                                 problemSolution->addSingleAction (Capability(what), REMOVE_EXTRA_REQUIRE);
1273                                 string description = "";
1274
1275                                 // Checking if this problem solution would break your system
1276                                 if (system_requires.find(Capability(what)) != system_requires.end()) {
1277                                     // Show a better warning
1278                                     resolverProblem->setDetails( resolverProblem->description() + "\n" + resolverProblem->details() );
1279                                     resolverProblem->setDescription(_("This request will break your system!"));
1280                                     description = _("ignore the warning of a broken system");
1281                                     description += string(" (requires:")+pool_dep2str(pool, what)+")";
1282                                     MIL << description << endl;
1283                                     problemSolution->addFrontDescription (description);
1284                                 } else {
1285                                     description = str::form (_("do not ask to install a solvable providing %s"), pool_dep2str(pool, what));
1286                                     MIL << description << endl;
1287                                     problemSolution->addDescription (description);
1288                                 }
1289                                 }
1290                                 break;
1291                             case SOLVER_ERASE | SOLVER_SOLVABLE_PROVIDES:
1292                                 {
1293                                 problemSolution->addSingleAction (Capability(what), REMOVE_EXTRA_CONFLICT);
1294                                 string description = "";
1295
1296                                 // Checking if this problem solution would break your system
1297                                 if (system_conflicts.find(Capability(what)) != system_conflicts.end()) {
1298                                     // Show a better warning
1299                                     resolverProblem->setDetails( resolverProblem->description() + "\n" + resolverProblem->details() );
1300                                     resolverProblem->setDescription(_("This request will break your system!"));
1301                                     description = _("ignore the warning of a broken system");
1302                                     description += string(" (conflicts:")+pool_dep2str(pool, what)+")";
1303                                     MIL << description << endl;
1304                                     problemSolution->addFrontDescription (description);
1305
1306                                 } else {
1307                                     description = str::form (_("do not ask to delete all solvables providing %s"), pool_dep2str(pool, what));
1308                                     MIL << description << endl;
1309                                     problemSolution->addDescription (description);
1310                                 }
1311                                 }
1312                                 break;
1313                             case SOLVER_UPDATE | SOLVER_SOLVABLE:
1314                                 {
1315                                 s = mapSolvable (what);
1316                                 PoolItem poolItem = _pool.find (s);
1317                                 if (poolItem) {
1318                                     if (pool->installed && s.get()->repo == pool->installed) {
1319                                         problemSolution->addSingleAction (poolItem, KEEP);
1320                                         string description = str::form (_("do not install most recent version of %s"), s.asString().c_str());
1321                                         MIL << description << endl;
1322                                         problemSolution->addDescription (description);
1323                                     } else {
1324                                         ERR << "SOLVER_INSTALL_SOLVABLE_UPDATE " << poolItem << " is not selected for installation" << endl;
1325                                     }
1326                                 } else {
1327                                     ERR << "SOLVER_INSTALL_SOLVABLE_UPDATE: No item found for " << s.asString() << endl;
1328                                 }
1329                                 }
1330                                 break;
1331                             default:
1332                                 MIL << "- do something different" << endl;
1333                                 ERR << "No valid solution available" << endl;
1334                                 break;
1335                         }
1336                     } else if (p == SOLVER_SOLUTION_INFARCH) {
1337                         s = mapSolvable (rp);
1338                         PoolItem poolItem = _pool.find (s);
1339                         if (pool->installed && s.get()->repo == pool->installed) {
1340                             problemSolution->addSingleAction (poolItem, LOCK);
1341                             string description = str::form (_("keep %s despite the inferior architecture"), s.asString().c_str());
1342                             MIL << description << endl;
1343                             problemSolution->addDescription (description);
1344                         } else {
1345                             problemSolution->addSingleAction (poolItem, INSTALL);
1346                             string description = str::form (_("install %s despite the inferior architecture"), s.asString().c_str());
1347                             MIL << description << endl;
1348                             problemSolution->addDescription (description);
1349                         }
1350                     } else if (p == SOLVER_SOLUTION_DISTUPGRADE) {
1351                         s = mapSolvable (rp);
1352                         PoolItem poolItem = _pool.find (s);
1353                         if (pool->installed && s.get()->repo == pool->installed) {
1354                             problemSolution->addSingleAction (poolItem, LOCK);
1355                             string description = str::form (_("keep obsolete %s"), s.asString().c_str());
1356                             MIL << description << endl;
1357                             problemSolution->addDescription (description);
1358                         } else {
1359                             problemSolution->addSingleAction (poolItem, INSTALL);
1360                             string description = str::form (_("install %s from excluded repository"), s.asString().c_str());
1361                             MIL << description << endl;
1362                             problemSolution->addDescription (description);
1363                         }
1364                     } else if ( p == SOLVER_SOLUTION_BLACK ) {
1365                         // Allow to install a blacklisted package (PTF, retracted,...).
1366                         // For not-installed items only
1367                         s = mapSolvable (rp);
1368                         PoolItem poolItem = _pool.find (s);
1369
1370                         problemSolution->addSingleAction (poolItem, INSTALL);
1371                         string description;
1372                         if ( s.isRetracted() ) {
1373                           // translator: %1% is a package name
1374                           description = str::Format(_("install %1% although it has been retracted")) % s.asString();
1375                         } else if ( s.isPtf() ) {
1376                           // translator: %1% is a package name
1377                           description = str::Format(_("allow to install the PTF %1%")) % s.asString();
1378                         } else {
1379                           // translator: %1% is a package name
1380                           description = str::Format(_("install %1% although it is blacklisted")) % s.asString();
1381                         }
1382                         MIL << description << endl;
1383                         problemSolution->addDescription( description );
1384                     } else if ( p > 0 ) {
1385                         /* policy, replace p with rp */
1386                         s = mapSolvable (p);
1387                         PoolItem itemFrom = _pool.find (s);
1388                         if (rp)
1389                         {
1390                             int gotone = 0;
1391
1392                             sd = mapSolvable (rp);
1393                             PoolItem itemTo = _pool.find (sd);
1394                             if (itemFrom && itemTo) {
1395                                 problemSolution->addSingleAction (itemTo, INSTALL);
1396                                 int illegal = policy_is_illegal(_satSolver, s.get(), sd.get(), 0);
1397
1398                                 if ((illegal & POLICY_ILLEGAL_DOWNGRADE) != 0)
1399                                 {
1400                                     string description = str::form (_("downgrade of %s to %s"), s.asString().c_str(), sd.asString().c_str());
1401                                     MIL << description << endl;
1402                                     problemSolution->addDescription (description);
1403                                     gotone = 1;
1404                                 }
1405                                 if ((illegal & POLICY_ILLEGAL_ARCHCHANGE) != 0)
1406                                 {
1407                                     string description = str::form (_("architecture change of %s to %s"), s.asString().c_str(), sd.asString().c_str());
1408                                     MIL << description << endl;
1409                                     problemSolution->addDescription (description);
1410                                     gotone = 1;
1411                                 }
1412                                 if ((illegal & POLICY_ILLEGAL_VENDORCHANGE) != 0)
1413                                 {
1414                                     IdString s_vendor( s.vendor() );
1415                                     IdString sd_vendor( sd.vendor() );
1416                                     string description = str::form (_("install %s (with vendor change)\n  %s  -->  %s") ,
1417                                                                     sd.asString().c_str(),
1418                                                                     ( s_vendor ? s_vendor.c_str() : " (no vendor) " ),
1419                                                                     ( sd_vendor ? sd_vendor.c_str() : " (no vendor) " ) );
1420                                     MIL << description << endl;
1421                                     problemSolution->addDescription (description);
1422                                     gotone = 1;
1423                                 }
1424                                 if (!gotone) {
1425                                     string description = str::form (_("replacement of %s with %s"), s.asString().c_str(), sd.asString().c_str());
1426                                     MIL << description << endl;
1427                                     problemSolution->addDescription (description);
1428                                 }
1429                             } else {
1430                                 ERR << s.asString() << " or "  << sd.asString() << " not found" << endl;
1431                             }
1432                         }
1433                         else
1434                         {
1435                             if (itemFrom) {
1436                                 string description = str::form (_("deinstallation of %s"), s.asString().c_str());
1437                                 MIL << description << endl;
1438                                 problemSolution->addDescription (description);
1439                                 problemSolution->addSingleAction (itemFrom, REMOVE);
1440                             }
1441                         }
1442                     }
1443                     else
1444                     {
1445                       INT << "Unknown solution " << p << endl;
1446                     }
1447
1448                 }
1449                 resolverProblem->addSolution (problemSolution,
1450                                               problemSolution->actionCount() > 1 ? true : false); // Solutions with more than 1 action will be shown first.
1451                 MIL << "------------------------------------" << endl;
1452             }
1453
1454             if (ignoreId > 0) {
1455                 // There is a possibility to ignore this error by setting weak dependencies
1456                 PoolItem item = _pool.find (sat::Solvable(ignoreId));
1457                 ProblemSolutionIgnore *problemSolution = new ProblemSolutionIgnore(item);
1458                 resolverProblem->addSolution (problemSolution,
1459                                               false); // Solutions will be shown at the end
1460                 MIL << "ignore some dependencies of " << item << endl;
1461                 MIL << "------------------------------------" << endl;
1462             }
1463
1464             // save problem
1465             resolverProblems.push_back (resolverProblem);
1466         }
1467     }
1468     return resolverProblems;
1469 }
1470
1471 void SATResolver::applySolutions( const ProblemSolutionList & solutions )
1472 { Resolver( _pool ).applySolutions( solutions ); }
1473
1474 void SATResolver::setLocks()
1475 {
1476     unsigned icnt = 0;
1477     unsigned acnt = 0;
1478
1479     for (PoolItemList::const_iterator iter = _items_to_lock.begin(); iter != _items_to_lock.end(); ++iter) {
1480         sat::detail::SolvableIdType ident( (*iter)->satSolvable().id() );
1481         if (iter->status().isInstalled()) {
1482             ++icnt;
1483             queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE );
1484             queue_push( &(_jobQueue), ident );
1485         } else {
1486             ++acnt;
1487             queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE | MAYBE_CLEANDEPS );
1488             queue_push( &(_jobQueue), ident );
1489         }
1490     }
1491     MIL << "Locked " << icnt << " installed items and " << acnt << " NOT installed items." << endl;
1492
1493     ///////////////////////////////////////////////////////////////////
1494     // Weak locks: Ignore if an item with this name is already installed.
1495     // If it's not installed try to keep it this way using a weak delete
1496     ///////////////////////////////////////////////////////////////////
1497     std::set<IdString> unifiedByName;
1498     for (PoolItemList::const_iterator iter = _items_to_keep.begin(); iter != _items_to_keep.end(); ++iter) {
1499       IdString ident( (*iter)->satSolvable().ident() );
1500       if ( unifiedByName.insert( ident ).second )
1501       {
1502         if ( ! ui::Selectable::get( *iter )->hasInstalledObj() )
1503         {
1504           MIL << "Keep NOT installed name " << ident << " (" << *iter << ")" << endl;
1505           queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE_NAME | SOLVER_WEAK | MAYBE_CLEANDEPS );
1506           queue_push( &(_jobQueue), ident.id() );
1507         }
1508       }
1509     }
1510 }
1511
1512 void SATResolver::setSystemRequirements()
1513 {
1514     CapabilitySet system_requires = SystemCheck::instance().requiredSystemCap();
1515     CapabilitySet system_conflicts = SystemCheck::instance().conflictSystemCap();
1516
1517     for (CapabilitySet::const_iterator iter = system_requires.begin(); iter != system_requires.end(); ++iter) {
1518         queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE_PROVIDES );
1519         queue_push( &(_jobQueue), iter->id() );
1520         MIL << "SYSTEM Requires " << *iter << endl;
1521     }
1522
1523     for (CapabilitySet::const_iterator iter = system_conflicts.begin(); iter != system_conflicts.end(); ++iter) {
1524         queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE_PROVIDES | MAYBE_CLEANDEPS );
1525         queue_push( &(_jobQueue), iter->id() );
1526         MIL << "SYSTEM Conflicts " << *iter << endl;
1527     }
1528
1529     // Lock the architecture of the running systems rpm
1530     // package on distupgrade.
1531     if ( _distupgrade && ZConfig::instance().systemRoot() == "/" )
1532     {
1533       ResPool pool( ResPool::instance() );
1534       IdString rpm( "rpm" );
1535       for_( it, pool.byIdentBegin(rpm), pool.byIdentEnd(rpm) )
1536       {
1537         if ( (*it)->isSystem() )
1538         {
1539           Capability archrule( (*it)->arch(), rpm.c_str(), Capability::PARSED );
1540           queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE_NAME | SOLVER_ESSENTIAL );
1541           queue_push( &(_jobQueue), archrule.id() );
1542
1543         }
1544       }
1545     }
1546 }
1547
1548 sat::StringQueue SATResolver::autoInstalled() const
1549 {
1550   sat::StringQueue ret;
1551   if ( _satSolver )
1552     ::solver_get_userinstalled( _satSolver, ret, GET_USERINSTALLED_NAMES|GET_USERINSTALLED_INVERTED );
1553   return ret;
1554 }
1555
1556 sat::StringQueue SATResolver::userInstalled() const
1557 {
1558   sat::StringQueue ret;
1559   if ( _satSolver )
1560     ::solver_get_userinstalled( _satSolver, ret, GET_USERINSTALLED_NAMES );
1561   return ret;
1562 }
1563
1564
1565 ///////////////////////////////////////////////////////////////////
1566 };// namespace detail
1567     /////////////////////////////////////////////////////////////////////
1568     /////////////////////////////////////////////////////////////////////
1569   };// namespace solver
1570   ///////////////////////////////////////////////////////////////////////
1571   ///////////////////////////////////////////////////////////////////////
1572 };// namespace zypp
1573 /////////////////////////////////////////////////////////////////////////
1574