8b63a45ae946df0a69e7d9727550ed46be674514
[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::detail::IdType id : decisionq )
441           {
442             if ( id < 0 )
443               continue;
444             sat::Solvable slv { id };
445             // get product buddies (they carry the weakremover)...
446             static const Capability productCap { "product()" };
447             if ( slv && slv.provides().matches( productCap ) )
448             {
449               CapabilitySet droplist { slv.valuesOfNamespace( "weakremover" ) };
450               MIL << "Droplist for " << slv << ": size " << droplist.size() << endl;
451               if ( !droplist.empty() )
452               {
453                 for ( const auto & cap : droplist )
454                 {
455                   INT << "  => " << cap << endl;
456                   queue_push( &_jobQueue, SOLVER_DROP_ORPHANED | SOLVER_SOLVABLE_NAME );
457                   queue_push( &_jobQueue, cap.id() );
458                 }
459                 // PIN product - a safety net to prevent cleanup from changing the decision for this product
460                 queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE );
461                 queue_push( &(_jobQueue), id );
462                 resolve = true;
463               }
464             }
465           }
466           if ( resolve )
467             solver_solve( _satSolver, &(_jobQueue) );
468         }
469       }
470     }
471     MIL << "....Solver end" << endl;
472
473     // copying solution back to zypp pool
474     //-----------------------------------------
475     _result_items_to_install.clear();
476     _result_items_to_remove.clear();
477
478     /*  solvables to be installed */
479     Queue decisionq;
480     queue_init(&decisionq);
481     solver_get_decisionqueue(_satSolver, &decisionq);
482     for ( int i = 0; i < decisionq.count; ++i )
483     {
484       Id p = decisionq.elements[i];
485       if ( p < 0 )
486         continue;
487
488       sat::Solvable slv { p };
489       if ( ! slv || slv.isSystem() )
490         continue;
491
492       PoolItem poolItem( slv );
493       SATSolutionToPool (poolItem, ResStatus::toBeInstalled, ResStatus::SOLVER);
494       _result_items_to_install.push_back( poolItem );
495     }
496     queue_free(&decisionq);
497
498     /* solvables to be erased */
499     Repository systemRepo( sat::Pool::instance().findSystemRepo() ); // don't create if it does not exist
500     if ( systemRepo && ! systemRepo.solvablesEmpty() )
501     {
502       bool mustCheckObsoletes = false;
503       for_( it, systemRepo.solvablesBegin(), systemRepo.solvablesEnd() )
504       {
505         if (solver_get_decisionlevel(_satSolver, it->id()) > 0)
506           continue;
507
508         // Check if this is an update
509         CheckIfUpdate info( *it );
510         PoolItem poolItem( *it );
511         invokeOnEach( _pool.byIdentBegin( poolItem ),
512                       _pool.byIdentEnd( poolItem ),
513                       resfilter::ByUninstalled(),                       // ByUninstalled
514                       functor::functorRef<bool,PoolItem> (info) );
515
516         if (info.is_updated) {
517           SATSolutionToPool( poolItem, ResStatus::toBeUninstalledDueToUpgrade, ResStatus::SOLVER );
518         } else {
519           SATSolutionToPool( poolItem, ResStatus::toBeUninstalled, ResStatus::SOLVER );
520           if ( ! mustCheckObsoletes )
521             mustCheckObsoletes = true; // lazy check for UninstalledDueToObsolete
522         }
523         _result_items_to_remove.push_back (poolItem);
524       }
525       if ( mustCheckObsoletes )
526       {
527         sat::WhatObsoletes obsoleted( _result_items_to_install.begin(), _result_items_to_install.end() );
528         for_( it, obsoleted.poolItemBegin(), obsoleted.poolItemEnd() )
529         {
530           ResStatus & status( it->status() );
531           // WhatObsoletes contains installed items only!
532           if ( status.transacts() && ! status.isToBeUninstalledDueToUpgrade() )
533             status.setToBeUninstalledDueToObsolete();
534         }
535       }
536     }
537
538     Queue recommendations;
539     Queue suggestions;
540     Queue orphaned;
541     Queue unneeded;
542     queue_init(&recommendations);
543     queue_init(&suggestions);
544     queue_init(&orphaned);
545     queue_init(&unneeded);
546     solver_get_recommendations(_satSolver, &recommendations, &suggestions, 0);
547     solver_get_orphaned(_satSolver, &orphaned);
548     solver_get_unneeded(_satSolver, &unneeded, 1);
549     /*  solvables which are recommended */
550     for ( int i = 0; i < recommendations.count; ++i )
551     {
552       PoolItem poolItem( getPoolItem( recommendations.elements[i] ) );
553       poolItem.status().setRecommended( true );
554     }
555
556     /*  solvables which are suggested */
557     for ( int i = 0; i < suggestions.count; ++i )
558     {
559       PoolItem poolItem( getPoolItem( suggestions.elements[i] ) );
560       poolItem.status().setSuggested( true );
561     }
562
563     _problem_items.clear();
564     /*  solvables which are orphaned */
565     for ( int i = 0; i < orphaned.count; ++i )
566     {
567       PoolItem poolItem( getPoolItem( orphaned.elements[i] ) );
568       poolItem.status().setOrphaned( true );
569       _problem_items.push_back( poolItem );
570     }
571
572     /*  solvables which are unneeded */
573     for ( int i = 0; i < unneeded.count; ++i )
574     {
575       PoolItem poolItem( getPoolItem( unneeded.elements[i] ) );
576       poolItem.status().setUnneeded( true );
577     }
578
579     queue_free(&recommendations);
580     queue_free(&suggestions);
581     queue_free(&orphaned);
582     queue_free(&unneeded);
583
584     /* Write validation state back to pool */
585     Queue flags, solvableQueue;
586
587     queue_init(&flags);
588     queue_init(&solvableQueue);
589
590     CollectPseudoInstalled collectPseudoInstalled(&solvableQueue);
591     invokeOnEach( _pool.begin(),
592                   _pool.end(),
593                   functor::functorRef<bool,PoolItem> (collectPseudoInstalled) );
594     solver_trivial_installable(_satSolver, &solvableQueue, &flags );
595     for (int i = 0; i < solvableQueue.count; i++) {
596         PoolItem item = _pool.find (sat::Solvable(solvableQueue.elements[i]));
597         item.status().setUndetermined();
598
599         if (flags.elements[i] == -1) {
600             item.status().setNonRelevant();
601             XDEBUG("SATSolutionToPool(" << item << " ) nonRelevant !");
602         } else if (flags.elements[i] == 1) {
603             item.status().setSatisfied();
604             XDEBUG("SATSolutionToPool(" << item << " ) satisfied !");
605         } else if (flags.elements[i] == 0) {
606             item.status().setBroken();
607             XDEBUG("SATSolutionToPool(" << item << " ) broken !");
608         }
609     }
610     queue_free(&(solvableQueue));
611     queue_free(&flags);
612
613
614     // Solvables which were selected due requirements which have been made by the user will
615     // be selected by APPL_LOW. We can't use any higher level, because this setting must
616     // not serve as a request for the next solver run. APPL_LOW is reset before solving.
617     for (CapabilitySet::const_iterator iter = requires_caps.begin(); iter != requires_caps.end(); iter++) {
618         sat::WhatProvides rpmProviders(*iter);
619         for_( iter2, rpmProviders.begin(), rpmProviders.end() ) {
620             PoolItem poolItem(*iter2);
621             if (poolItem.status().isToBeInstalled()) {
622                 MIL << "User requirement " << *iter << " sets " << poolItem << endl;
623                 poolItem.status().setTransactByValue (ResStatus::APPL_LOW);
624             }
625         }
626     }
627     for (CapabilitySet::const_iterator iter = conflict_caps.begin(); iter != conflict_caps.end(); iter++) {
628         sat::WhatProvides rpmProviders(*iter);
629         for_( iter2, rpmProviders.begin(), rpmProviders.end() ) {
630             PoolItem poolItem(*iter2);
631             if (poolItem.status().isToBeUninstalled()) {
632                 MIL << "User conflict " << *iter << " sets " << poolItem << endl;
633                 poolItem.status().setTransactByValue (ResStatus::APPL_LOW);
634             }
635         }
636     }
637
638     if (solver_problem_count(_satSolver) > 0 )
639     {
640         ERR << "Solverrun finished with an ERROR" << endl;
641         return false;
642     }
643
644     return true;
645 }
646
647
648 void
649 SATResolver::solverInit(const PoolItemList & weakItems)
650 {
651
652     MIL << "SATResolver::solverInit()" << endl;
653
654     // remove old stuff
655     solverEnd();
656     queue_init( &_jobQueue );
657
658     // clear and rebuild: _items_to_install, _items_to_remove, _items_to_lock, _items_to_keep
659     {
660       SATCollectTransact collector( _items_to_install, _items_to_remove, _items_to_lock, _items_to_keep, solveSrcPackages() );
661       invokeOnEach ( _pool.begin(), _pool.end(), functor::functorRef<bool,PoolItem>( collector ) );
662     }
663
664     for (PoolItemList::const_iterator iter = weakItems.begin(); iter != weakItems.end(); iter++) {
665         Id id = (*iter)->satSolvable().id();
666         if (id == ID_NULL) {
667             ERR << "Weaken: " << *iter << " not found" << endl;
668         }
669         MIL << "Weaken dependencies of " << *iter << endl;
670         queue_push( &(_jobQueue), SOLVER_WEAKENDEPS | SOLVER_SOLVABLE );
671         queue_push( &(_jobQueue), id );
672     }
673
674     // Ad rules for retracted patches and packages
675     {
676       queue_push( &(_jobQueue), SOLVER_BLACKLIST|SOLVER_SOLVABLE_PROVIDES );
677       queue_push( &(_jobQueue), sat::Solvable::retractedToken.id() );
678       queue_push( &(_jobQueue), SOLVER_BLACKLIST|SOLVER_SOLVABLE_PROVIDES );
679       queue_push( &(_jobQueue), sat::Solvable::ptfToken.id() );
680     }
681
682     // Ad rules for changed requestedLocales
683     {
684       const auto & trackedLocaleIds( myPool().trackedLocaleIds() );
685
686       // just track changed locakes
687       for ( const auto & locale : trackedLocaleIds.added() )
688       {
689         queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE_PROVIDES );
690         queue_push( &(_jobQueue), Capability( ResolverNamespace::language, IdString(locale) ).id() );
691       }
692
693       for ( const auto & locale : trackedLocaleIds.removed() )
694       {
695         queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE_PROVIDES | SOLVER_CLEANDEPS ); // needs uncond. SOLVER_CLEANDEPS!
696         queue_push( &(_jobQueue), Capability( ResolverNamespace::language, IdString(locale) ).id() );
697       }
698     }
699
700     // Add rules for parallel installable resolvables with different versions
701     for ( const sat::Solvable & solv : myPool().multiversionList() )
702     {
703       queue_push( &(_jobQueue), SOLVER_NOOBSOLETES | SOLVER_SOLVABLE );
704       queue_push( &(_jobQueue), solv.id() );
705     }
706
707     ::pool_add_userinstalled_jobs(_satPool, sat::Pool::instance().autoInstalled(), &(_jobQueue), GET_USERINSTALLED_NAMES|GET_USERINSTALLED_INVERTED);
708 }
709
710 void
711 SATResolver::solverEnd()
712 {
713   // cleanup
714   if ( _satSolver )
715   {
716     solver_free(_satSolver);
717     _satSolver = NULL;
718     queue_free( &(_jobQueue) );
719   }
720 }
721
722
723 bool
724 SATResolver::resolvePool(const CapabilitySet & requires_caps,
725                          const CapabilitySet & conflict_caps,
726                          const PoolItemList & weakItems,
727                          const std::set<Repository> & upgradeRepos)
728 {
729     MIL << "SATResolver::resolvePool()" << endl;
730
731     // initialize
732     solverInit(weakItems);
733
734     for (PoolItemList::const_iterator iter = _items_to_install.begin(); iter != _items_to_install.end(); iter++) {
735         Id id = (*iter)->satSolvable().id();
736         if (id == ID_NULL) {
737             ERR << "Install: " << *iter << " not found" << endl;
738         } else {
739             MIL << "Install " << *iter << endl;
740             queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE );
741             queue_push( &(_jobQueue), id );
742         }
743     }
744
745     for (PoolItemList::const_iterator iter = _items_to_remove.begin(); iter != _items_to_remove.end(); iter++) {
746         Id id = (*iter)->satSolvable().id();
747         if (id == ID_NULL) {
748             ERR << "Delete: " << *iter << " not found" << endl;
749         } else {
750             MIL << "Delete " << *iter << endl;
751             queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE | MAYBE_CLEANDEPS );
752             queue_push( &(_jobQueue), id);
753         }
754     }
755
756     for_( iter, upgradeRepos.begin(), upgradeRepos.end() )
757     {
758         queue_push( &(_jobQueue), SOLVER_DISTUPGRADE | SOLVER_SOLVABLE_REPO );
759         queue_push( &(_jobQueue), iter->get()->repoid );
760         MIL << "Upgrade repo " << *iter << endl;
761     }
762
763     for (CapabilitySet::const_iterator iter = requires_caps.begin(); iter != requires_caps.end(); iter++) {
764         queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE_PROVIDES );
765         queue_push( &(_jobQueue), iter->id() );
766         MIL << "Requires " << *iter << endl;
767     }
768
769     for (CapabilitySet::const_iterator iter = conflict_caps.begin(); iter != conflict_caps.end(); iter++) {
770         queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE_PROVIDES | MAYBE_CLEANDEPS );
771         queue_push( &(_jobQueue), iter->id() );
772         MIL << "Conflicts " << *iter << endl;
773     }
774
775     // set requirements for a running system
776     setSystemRequirements();
777
778     // set locks for the solver
779     setLocks();
780
781     // solving
782     bool ret = solving(requires_caps, conflict_caps);
783
784     (ret?MIL:WAR) << "SATResolver::resolvePool() done. Ret:" << ret <<  endl;
785     return ret;
786 }
787
788
789 bool
790 SATResolver::resolveQueue(const SolverQueueItemList &requestQueue,
791                           const PoolItemList & weakItems)
792 {
793     MIL << "SATResolver::resolvQueue()" << endl;
794
795     // initialize
796     solverInit(weakItems);
797
798     // generate solver queue
799     for (SolverQueueItemList::const_iterator iter = requestQueue.begin(); iter != requestQueue.end(); iter++) {
800         (*iter)->addRule(_jobQueue);
801     }
802
803     // Add addition item status to the resolve-queue cause these can be set by problem resolutions
804     for (PoolItemList::const_iterator iter = _items_to_install.begin(); iter != _items_to_install.end(); iter++) {
805         Id id = (*iter)->satSolvable().id();
806         if (id == ID_NULL) {
807             ERR << "Install: " << *iter << " not found" << endl;
808         } else {
809             MIL << "Install " << *iter << endl;
810             queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE );
811             queue_push( &(_jobQueue), id );
812         }
813     }
814     for (PoolItemList::const_iterator iter = _items_to_remove.begin(); iter != _items_to_remove.end(); iter++) {
815         sat::detail::IdType ident( (*iter)->satSolvable().ident().id() );
816         MIL << "Delete " << *iter << ident << endl;
817         queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE_NAME | MAYBE_CLEANDEPS );
818         queue_push( &(_jobQueue), ident);
819     }
820
821     // set requirements for a running system
822     setSystemRequirements();
823
824     // set locks for the solver
825     setLocks();
826
827     // solving
828     bool ret = solving();
829
830     MIL << "SATResolver::resolveQueue() done. Ret:" << ret <<  endl;
831     return ret;
832 }
833
834 /** \todo duplicate code to be joined with \ref solving. */
835 void SATResolver::doUpdate()
836 {
837     MIL << "SATResolver::doUpdate()" << endl;
838
839     // initialize
840     solverInit(PoolItemList());
841
842     // set requirements for a running system
843     setSystemRequirements();
844
845     // set locks for the solver
846     setLocks();
847
848     _satSolver = solver_create( _satPool );
849     ::pool_set_custom_vendorcheck( _satPool, &vendorCheck );
850     if (_fixsystem) {
851         queue_push( &(_jobQueue), SOLVER_VERIFY|SOLVER_SOLVABLE_ALL);
852         queue_push( &(_jobQueue), 0 );
853     }
854     if (1) {
855         queue_push( &(_jobQueue), SOLVER_UPDATE|SOLVER_SOLVABLE_ALL);
856         queue_push( &(_jobQueue), 0 );
857     }
858     if (_distupgrade) {
859         queue_push( &(_jobQueue), SOLVER_DISTUPGRADE|SOLVER_SOLVABLE_ALL);
860         queue_push( &(_jobQueue), 0 );
861     }
862     if (_distupgrade_removeunsupported) {
863         queue_push( &(_jobQueue), SOLVER_DROP_ORPHANED|SOLVER_SOLVABLE_ALL);
864         queue_push( &(_jobQueue), 0 );
865     }
866     solverSetFocus( *_satSolver, _focus );
867     solver_set_flag(_satSolver, SOLVER_FLAG_ADD_ALREADY_RECOMMENDED, !_ignorealreadyrecommended);
868     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_DOWNGRADE,            _allowdowngrade);
869     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_NAMECHANGE,           _allownamechange);
870     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_ARCHCHANGE,           _allowarchchange);
871     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_VENDORCHANGE,         _allowvendorchange);
872     solver_set_flag(_satSolver, SOLVER_FLAG_ALLOW_UNINSTALL,            _allowuninstall);
873     solver_set_flag(_satSolver, SOLVER_FLAG_NO_UPDATEPROVIDE,           _noupdateprovide);
874     solver_set_flag(_satSolver, SOLVER_FLAG_SPLITPROVIDES,              _dosplitprovides);
875     solver_set_flag(_satSolver, SOLVER_FLAG_IGNORE_RECOMMENDED,         false);         // resolve recommended namespaces
876     solver_set_flag(_satSolver, SOLVER_FLAG_ONLY_NAMESPACE_RECOMMENDED, _onlyRequires); //
877
878     sat::Pool::instance().prepare();
879
880     // Solve !
881     MIL << "Starting solving for update...." << endl;
882     MIL << *this;
883     solver_solve( _satSolver, &(_jobQueue) );
884     MIL << "....Solver end" << endl;
885
886     // copying solution back to zypp pool
887     //-----------------------------------------
888
889     /*  solvables to be installed */
890     Queue decisionq;
891     queue_init(&decisionq);
892     solver_get_decisionqueue(_satSolver, &decisionq);
893     for (int i = 0; i < decisionq.count; i++)
894     {
895       Id p = decisionq.elements[i];
896       if ( p < 0 )
897         continue;
898
899       sat::Solvable solv { p };
900       if ( ! solv || solv.isSystem() )
901         continue;
902
903       SATSolutionToPool( PoolItem(solv), ResStatus::toBeInstalled, ResStatus::SOLVER );
904     }
905     queue_free(&decisionq);
906
907     /* solvables to be erased */
908     for (int i = _satSolver->pool->installed->start; i < _satSolver->pool->installed->start + _satSolver->pool->installed->nsolvables; i++)
909     {
910       if (solver_get_decisionlevel(_satSolver, i) > 0)
911           continue;
912
913       PoolItem poolItem( _pool.find( sat::Solvable(i) ) );
914       if (poolItem) {
915           // Check if this is an update
916           CheckIfUpdate info( (sat::Solvable(i)) );
917           invokeOnEach( _pool.byIdentBegin( poolItem ),
918                         _pool.byIdentEnd( poolItem ),
919                         resfilter::ByUninstalled(),                     // ByUninstalled
920                         functor::functorRef<bool,PoolItem> (info) );
921
922           if (info.is_updated) {
923               SATSolutionToPool (poolItem, ResStatus::toBeUninstalledDueToUpgrade , ResStatus::SOLVER);
924           } else {
925               SATSolutionToPool (poolItem, ResStatus::toBeUninstalled, ResStatus::SOLVER);
926           }
927       } else {
928           ERR << "id " << i << " not found in ZYPP pool." << endl;
929       }
930     }
931     MIL << "SATResolver::doUpdate() done" << endl;
932 }
933
934
935
936 //----------------------------------------------------------------------------
937 //----------------------------------------------------------------------------
938 // error handling
939 //----------------------------------------------------------------------------
940 //----------------------------------------------------------------------------
941
942 //----------------------------------------------------------------------------
943 // helper function
944 //----------------------------------------------------------------------------
945
946 struct FindPackage : public resfilter::ResObjectFilterFunctor
947 {
948     ProblemSolutionCombi *problemSolution;
949     TransactionKind action;
950     FindPackage (ProblemSolutionCombi *p, const TransactionKind act)
951        : problemSolution (p)
952        , action (act)
953         {
954         }
955
956     bool operator()( PoolItem p)
957    {
958        problemSolution->addSingleAction (p, action);
959        return true;
960    }
961 };
962
963
964 //----------------------------------------------------------------------------
965 // Checking if this solvable/item has a buddy which reflect the real
966 // user visible description of an item
967 // e.g. The release package has a buddy to the concerning product item.
968 // This user want's the message "Product foo conflicts with product bar" and
969 // NOT "package release-foo conflicts with package release-bar"
970 // (ma: that's why we should map just packages to buddies, not vice versa)
971 //----------------------------------------------------------------------------
972 inline sat::Solvable mapBuddy( const PoolItem & item_r )
973 {
974   if ( item_r.satSolvable().isKind<Package>() )
975   {
976     sat::Solvable buddy = item_r.buddy();
977     if ( buddy )
978       return buddy;
979   }
980   return item_r.satSolvable();
981 }
982 inline sat::Solvable mapBuddy( sat::Solvable item_r )
983 { return mapBuddy( PoolItem( item_r ) ); }
984
985 PoolItem SATResolver::mapItem ( const PoolItem & item )
986 { return PoolItem( mapBuddy( item ) ); }
987
988 sat::Solvable SATResolver::mapSolvable ( const Id & id )
989 { return mapBuddy( sat::Solvable(id) ); }
990
991 std::vector<std::string> SATResolver::SATgetCompleteProblemInfoStrings ( Id problem )
992 {
993   std::vector<std::string> ret;
994   sat::Queue problems;
995   solver_findallproblemrules( _satSolver, problem, problems );
996
997   bool nobad = false;
998
999   //filter out generic rule information if more explicit ones are available
1000   for ( sat::Queue::size_type i = 0; i < problems.size(); i++ ) {
1001     SolverRuleinfo ruleClass = solver_ruleclass( _satSolver, problems[i]);
1002     if ( ruleClass != SolverRuleinfo::SOLVER_RULE_UPDATE && ruleClass != SolverRuleinfo::SOLVER_RULE_JOB ) {
1003       nobad = true;
1004       break;
1005     }
1006   }
1007   for ( sat::Queue::size_type i = 0; i < problems.size(); i++ ) {
1008     SolverRuleinfo ruleClass = solver_ruleclass( _satSolver, problems[i]);
1009     if ( nobad && ( ruleClass == SolverRuleinfo::SOLVER_RULE_UPDATE || ruleClass == SolverRuleinfo::SOLVER_RULE_JOB ) ) {
1010       continue;
1011     }
1012
1013     std::string detail;
1014     Id ignore = 0;
1015     std::string pInfo = SATproblemRuleInfoString( problems[i], detail, ignore );
1016
1017     //we get the same string multiple times, reduce the noise
1018     if ( std::find( ret.begin(), ret.end(), pInfo ) == ret.end() )
1019       ret.push_back( pInfo );
1020   }
1021   return ret;
1022 }
1023
1024 string SATResolver::SATprobleminfoString(Id problem, string &detail, Id &ignoreId)
1025 {
1026   // FIXME: solver_findallproblemrules to get all rules for this problem
1027   // (the 'most relevabt' one returned by solver_findproblemrule is embedded
1028   Id probr = solver_findproblemrule(_satSolver, problem);
1029   return SATproblemRuleInfoString( probr, detail, ignoreId );
1030 }
1031
1032 std::string SATResolver::SATproblemRuleInfoString (Id probr, std::string &detail, Id &ignoreId)
1033 {
1034   string ret;
1035   sat::detail::CPool *pool = _satSolver->pool;
1036   Id dep, source, target;
1037   SolverRuleinfo type = solver_ruleinfo(_satSolver, probr, &source, &target, &dep);
1038
1039   ignoreId = 0;
1040
1041   sat::Solvable s = mapSolvable( source );
1042   sat::Solvable s2 = mapSolvable( target );
1043
1044   // @FIXME, these strings are a duplicate copied from the libsolv library
1045   // to provide translations. Instead of having duplicate code we should
1046   // translate those strings directly in libsolv
1047   switch ( type )
1048   {
1049       case SOLVER_RULE_DISTUPGRADE:
1050           ret = str::form (_("%s does not belong to a distupgrade repository"), s.asString().c_str());
1051           break;
1052       case SOLVER_RULE_INFARCH:
1053           ret = str::form (_("%s has inferior architecture"), s.asString().c_str());
1054           break;
1055       case SOLVER_RULE_UPDATE:
1056           ret = str::form (_("problem with installed package %s"), s.asString().c_str());
1057           break;
1058       case SOLVER_RULE_JOB:
1059           ret = _("conflicting requests");
1060           break;
1061       case SOLVER_RULE_PKG:
1062           ret = _("some dependency problem");
1063           break;
1064       case SOLVER_RULE_JOB_NOTHING_PROVIDES_DEP:
1065           ret = str::form (_("nothing provides requested %s"), pool_dep2str(pool, dep));
1066           detail += _("Have you enabled all requested repositories?");
1067           break;
1068       case SOLVER_RULE_JOB_UNKNOWN_PACKAGE:
1069           ret = str::form (_("package %s does not exist"), pool_dep2str(pool, dep));
1070           detail += _("Have you enabled all requested repositories?");
1071           break;
1072       case SOLVER_RULE_JOB_UNSUPPORTED:
1073           ret = _("unsupported request");
1074           break;
1075       case SOLVER_RULE_JOB_PROVIDED_BY_SYSTEM:
1076           ret = str::form (_("%s is provided by the system and cannot be erased"), pool_dep2str(pool, dep));
1077           break;
1078       case SOLVER_RULE_PKG_NOT_INSTALLABLE:
1079           ret = str::form (_("%s is not installable"), s.asString().c_str());
1080           break;
1081       case SOLVER_RULE_PKG_NOTHING_PROVIDES_DEP:
1082           ignoreId = source; // for setting weak dependencies
1083           ret = str::form (_("nothing provides %s needed by %s"), pool_dep2str(pool, dep), s.asString().c_str());
1084           break;
1085       case SOLVER_RULE_PKG_SAME_NAME:
1086           ret = str::form (_("cannot install both %s and %s"), s.asString().c_str(), s2.asString().c_str());
1087           break;
1088       case SOLVER_RULE_PKG_CONFLICTS:
1089           ret = str::form (_("%s conflicts with %s provided by %s"), s.asString().c_str(), pool_dep2str(pool, dep), s2.asString().c_str());
1090           break;
1091       case SOLVER_RULE_PKG_OBSOLETES:
1092           ret = str::form (_("%s obsoletes %s provided by %s"), s.asString().c_str(), pool_dep2str(pool, dep), s2.asString().c_str());
1093           break;
1094       case SOLVER_RULE_PKG_INSTALLED_OBSOLETES:
1095           ret = str::form (_("installed %s obsoletes %s provided by %s"), s.asString().c_str(), pool_dep2str(pool, dep), s2.asString().c_str());
1096           break;
1097       case SOLVER_RULE_PKG_SELF_CONFLICT:
1098           ret = str::form (_("solvable %s conflicts with %s provided by itself"), s.asString().c_str(), pool_dep2str(pool, dep));
1099           break;
1100       case SOLVER_RULE_PKG_REQUIRES: {
1101           ignoreId = source; // for setting weak dependencies
1102           Capability cap(dep);
1103           sat::WhatProvides possibleProviders(cap);
1104
1105           // check, if a provider will be deleted
1106           typedef list<PoolItem> ProviderList;
1107           ProviderList providerlistInstalled, providerlistUninstalled;
1108           for_( iter1, possibleProviders.begin(), possibleProviders.end() ) {
1109               PoolItem provider1 = ResPool::instance().find( *iter1 );
1110               // find pair of an installed/uninstalled item with the same NVR
1111               bool found = false;
1112               for_( iter2, possibleProviders.begin(), possibleProviders.end() ) {
1113                   PoolItem provider2 = ResPool::instance().find( *iter2 );
1114                   if (compareByNVR (provider1,provider2) == 0
1115                       && ( (provider1.status().isInstalled() && provider2.status().isUninstalled())
1116                           || (provider2.status().isInstalled() && provider1.status().isUninstalled()) ))  {
1117                       found = true;
1118                       break;
1119                   }
1120               }
1121               if (!found) {
1122                   if (provider1.status().isInstalled())
1123                       providerlistInstalled.push_back(provider1);
1124                   else
1125                       providerlistUninstalled.push_back(provider1);
1126               }
1127           }
1128
1129           ret = str::form (_("%s requires %s, but this requirement cannot be provided"), s.asString().c_str(), pool_dep2str(pool, dep));
1130           if (providerlistInstalled.size() > 0) {
1131               detail += _("deleted providers: ");
1132               for (ProviderList::const_iterator iter = providerlistInstalled.begin(); iter != providerlistInstalled.end(); iter++) {
1133                   if (iter == providerlistInstalled.begin())
1134                       detail += itemToString( *iter );
1135                   else
1136                       detail += "\n                   " + itemToString( mapItem(*iter) );
1137               }
1138           }
1139           if (providerlistUninstalled.size() > 0) {
1140               if (detail.size() > 0)
1141                   detail += _("\nnot installable providers: ");
1142               else
1143                   detail = _("not installable providers: ");
1144               for (ProviderList::const_iterator iter = providerlistUninstalled.begin(); iter != providerlistUninstalled.end(); iter++) {
1145                   if (iter == providerlistUninstalled.begin())
1146                       detail += itemToString( *iter );
1147                   else
1148                       detail += "\n                   " + itemToString( mapItem(*iter) );
1149               }
1150           }
1151           break;
1152       }
1153       default: {
1154           DBG << "Unknown rule type(" << type << ") going to query libsolv for rule information." << endl;
1155           ret = str::asString( ::solver_problemruleinfo2str( _satSolver, type, static_cast<Id>(s.id()), static_cast<Id>(s2.id()), dep ) );
1156           break;
1157       }
1158   }
1159   return ret;
1160 }
1161
1162 ResolverProblemList
1163 SATResolver::problems ()
1164 {
1165     ResolverProblemList resolverProblems;
1166     if (_satSolver && solver_problem_count(_satSolver)) {
1167         sat::detail::CPool *pool = _satSolver->pool;
1168         int pcnt;
1169         Id p, rp, what;
1170         Id problem, solution, element;
1171         sat::Solvable s, sd;
1172
1173         CapabilitySet system_requires = SystemCheck::instance().requiredSystemCap();
1174         CapabilitySet system_conflicts = SystemCheck::instance().conflictSystemCap();
1175
1176         MIL << "Encountered problems! Here are the solutions:\n" << endl;
1177         pcnt = 1;
1178         problem = 0;
1179         while ((problem = solver_next_problem(_satSolver, problem)) != 0) {
1180             MIL << "Problem " <<  pcnt++ << ":" << endl;
1181             MIL << "====================================" << endl;
1182             string detail;
1183             Id ignoreId;
1184             string whatString = SATprobleminfoString (problem,detail,ignoreId);
1185             MIL << whatString << endl;
1186             MIL << "------------------------------------" << endl;
1187             ResolverProblem_Ptr resolverProblem = new ResolverProblem (whatString, detail, SATgetCompleteProblemInfoStrings( problem ));
1188
1189             solution = 0;
1190             while ((solution = solver_next_solution(_satSolver, problem, solution)) != 0) {
1191                 element = 0;
1192                 ProblemSolutionCombi *problemSolution = new ProblemSolutionCombi;
1193                 while ((element = solver_next_solutionelement(_satSolver, problem, solution, element, &p, &rp)) != 0) {
1194                     if (p == SOLVER_SOLUTION_JOB) {
1195                         /* job, rp is index into job queue */
1196                         what = _jobQueue.elements[rp];
1197                         switch (_jobQueue.elements[rp-1]&(SOLVER_SELECTMASK|SOLVER_JOBMASK))
1198                         {
1199                             case SOLVER_INSTALL | SOLVER_SOLVABLE: {
1200                                 s = mapSolvable (what);
1201                                 PoolItem poolItem = _pool.find (s);
1202                                 if (poolItem) {
1203                                     if (pool->installed && s.get()->repo == pool->installed) {
1204                                         problemSolution->addSingleAction (poolItem, REMOVE);
1205                                         string description = str::form (_("remove lock to allow removal of %s"),  s.asString().c_str() );
1206                                         MIL << description << endl;
1207                                         problemSolution->addDescription (description);
1208                                     } else {
1209                                         problemSolution->addSingleAction (poolItem, KEEP);
1210                                         string description = str::form (_("do not install %s"), s.asString().c_str());
1211                                         MIL << description << endl;
1212                                         problemSolution->addDescription (description);
1213                                     }
1214                                 } else {
1215                                     ERR << "SOLVER_INSTALL_SOLVABLE: No item found for " << s.asString() << endl;
1216                                 }
1217                             }
1218                                 break;
1219                             case SOLVER_ERASE | SOLVER_SOLVABLE: {
1220                                 s = mapSolvable (what);
1221                                 PoolItem poolItem = _pool.find (s);
1222                                 if (poolItem) {
1223                                     if (pool->installed && s.get()->repo == pool->installed) {
1224                                         problemSolution->addSingleAction (poolItem, KEEP);
1225                                         string description = str::form (_("keep %s"), s.asString().c_str());
1226                                         MIL << description << endl;
1227                                         problemSolution->addDescription (description);
1228                                     } else {
1229                                         problemSolution->addSingleAction (poolItem, UNLOCK);
1230                                         string description = str::form (_("remove lock to allow installation of %s"), itemToString( poolItem ).c_str());
1231                                         MIL << description << endl;
1232                                         problemSolution->addDescription (description);
1233                                     }
1234                                 } else {
1235                                     ERR << "SOLVER_ERASE_SOLVABLE: No item found for " << s.asString() << endl;
1236                                 }
1237                             }
1238                                 break;
1239                             case SOLVER_INSTALL | SOLVER_SOLVABLE_NAME:
1240                                 {
1241                                 IdString ident( what );
1242                                 SolverQueueItemInstall_Ptr install =
1243                                     new SolverQueueItemInstall(_pool, ident.asString(), false );
1244                                 problemSolution->addSingleAction (install, REMOVE_SOLVE_QUEUE_ITEM);
1245
1246                                 string description = str::form (_("do not install %s"), ident.c_str() );
1247                                 MIL << description << endl;
1248                                 problemSolution->addDescription (description);
1249                                 }
1250                                 break;
1251                             case SOLVER_ERASE | SOLVER_SOLVABLE_NAME:
1252                                 {
1253                                 // As we do not know, if this request has come from resolvePool or
1254                                 // resolveQueue we will have to take care for both cases.
1255                                 IdString ident( what );
1256                                 FindPackage info (problemSolution, KEEP);
1257                                 invokeOnEach( _pool.byIdentBegin( ident ),
1258                                               _pool.byIdentEnd( ident ),
1259                                               functor::chain (resfilter::ByInstalled (),                        // ByInstalled
1260                                                               resfilter::ByTransact ()),                        // will be deinstalled
1261                                               functor::functorRef<bool,PoolItem> (info) );
1262
1263                                 SolverQueueItemDelete_Ptr del =
1264                                     new SolverQueueItemDelete(_pool, ident.asString(), false );
1265                                 problemSolution->addSingleAction (del, REMOVE_SOLVE_QUEUE_ITEM);
1266
1267                                 string description = str::form (_("keep %s"), ident.c_str());
1268                                 MIL << description << endl;
1269                                 problemSolution->addDescription (description);
1270                                 }
1271                                 break;
1272                             case SOLVER_INSTALL | SOLVER_SOLVABLE_PROVIDES:
1273                                 {
1274                                 problemSolution->addSingleAction (Capability(what), REMOVE_EXTRA_REQUIRE);
1275                                 string description = "";
1276
1277                                 // Checking if this problem solution would break your system
1278                                 if (system_requires.find(Capability(what)) != system_requires.end()) {
1279                                     // Show a better warning
1280                                     resolverProblem->setDetails( resolverProblem->description() + "\n" + resolverProblem->details() );
1281                                     resolverProblem->setDescription(_("This request will break your system!"));
1282                                     description = _("ignore the warning of a broken system");
1283                                     description += string(" (requires:")+pool_dep2str(pool, what)+")";
1284                                     MIL << description << endl;
1285                                     problemSolution->addFrontDescription (description);
1286                                 } else {
1287                                     description = str::form (_("do not ask to install a solvable providing %s"), pool_dep2str(pool, what));
1288                                     MIL << description << endl;
1289                                     problemSolution->addDescription (description);
1290                                 }
1291                                 }
1292                                 break;
1293                             case SOLVER_ERASE | SOLVER_SOLVABLE_PROVIDES:
1294                                 {
1295                                 problemSolution->addSingleAction (Capability(what), REMOVE_EXTRA_CONFLICT);
1296                                 string description = "";
1297
1298                                 // Checking if this problem solution would break your system
1299                                 if (system_conflicts.find(Capability(what)) != system_conflicts.end()) {
1300                                     // Show a better warning
1301                                     resolverProblem->setDetails( resolverProblem->description() + "\n" + resolverProblem->details() );
1302                                     resolverProblem->setDescription(_("This request will break your system!"));
1303                                     description = _("ignore the warning of a broken system");
1304                                     description += string(" (conflicts:")+pool_dep2str(pool, what)+")";
1305                                     MIL << description << endl;
1306                                     problemSolution->addFrontDescription (description);
1307
1308                                 } else {
1309                                     description = str::form (_("do not ask to delete all solvables providing %s"), pool_dep2str(pool, what));
1310                                     MIL << description << endl;
1311                                     problemSolution->addDescription (description);
1312                                 }
1313                                 }
1314                                 break;
1315                             case SOLVER_UPDATE | SOLVER_SOLVABLE:
1316                                 {
1317                                 s = mapSolvable (what);
1318                                 PoolItem poolItem = _pool.find (s);
1319                                 if (poolItem) {
1320                                     if (pool->installed && s.get()->repo == pool->installed) {
1321                                         problemSolution->addSingleAction (poolItem, KEEP);
1322                                         string description = str::form (_("do not install most recent version of %s"), s.asString().c_str());
1323                                         MIL << description << endl;
1324                                         problemSolution->addDescription (description);
1325                                     } else {
1326                                         ERR << "SOLVER_INSTALL_SOLVABLE_UPDATE " << poolItem << " is not selected for installation" << endl;
1327                                     }
1328                                 } else {
1329                                     ERR << "SOLVER_INSTALL_SOLVABLE_UPDATE: No item found for " << s.asString() << endl;
1330                                 }
1331                                 }
1332                                 break;
1333                             default:
1334                                 MIL << "- do something different" << endl;
1335                                 ERR << "No valid solution available" << endl;
1336                                 break;
1337                         }
1338                     } else if (p == SOLVER_SOLUTION_INFARCH) {
1339                         s = mapSolvable (rp);
1340                         PoolItem poolItem = _pool.find (s);
1341                         if (pool->installed && s.get()->repo == pool->installed) {
1342                             problemSolution->addSingleAction (poolItem, LOCK);
1343                             string description = str::form (_("keep %s despite the inferior architecture"), s.asString().c_str());
1344                             MIL << description << endl;
1345                             problemSolution->addDescription (description);
1346                         } else {
1347                             problemSolution->addSingleAction (poolItem, INSTALL);
1348                             string description = str::form (_("install %s despite the inferior architecture"), s.asString().c_str());
1349                             MIL << description << endl;
1350                             problemSolution->addDescription (description);
1351                         }
1352                     } else if (p == SOLVER_SOLUTION_DISTUPGRADE) {
1353                         s = mapSolvable (rp);
1354                         PoolItem poolItem = _pool.find (s);
1355                         if (pool->installed && s.get()->repo == pool->installed) {
1356                             problemSolution->addSingleAction (poolItem, LOCK);
1357                             string description = str::form (_("keep obsolete %s"), s.asString().c_str());
1358                             MIL << description << endl;
1359                             problemSolution->addDescription (description);
1360                         } else {
1361                             problemSolution->addSingleAction (poolItem, INSTALL);
1362                             string description = str::form (_("install %s from excluded repository"), s.asString().c_str());
1363                             MIL << description << endl;
1364                             problemSolution->addDescription (description);
1365                         }
1366                     } else if ( p == SOLVER_SOLUTION_BLACK ) {
1367                         // Allow to install a blacklisted package (PTF, retracted,...).
1368                         // For not-installed items only
1369                         s = mapSolvable (rp);
1370                         PoolItem poolItem = _pool.find (s);
1371
1372                         problemSolution->addSingleAction (poolItem, INSTALL);
1373                         string description;
1374                         if ( s.isRetracted() ) {
1375                           // translator: %1% is a package name
1376                           description = str::Format(_("install %1% although it has been retracted")) % s.asString();
1377                         } else if ( s.isPtf() ) {
1378                           // translator: %1% is a package name
1379                           description = str::Format(_("allow to install the PTF %1%")) % s.asString();
1380                         } else {
1381                           // translator: %1% is a package name
1382                           description = str::Format(_("install %1% although it is blacklisted")) % s.asString();
1383                         }
1384                         MIL << description << endl;
1385                         problemSolution->addDescription( description );
1386                     } else if ( p > 0 ) {
1387                         /* policy, replace p with rp */
1388                         s = mapSolvable (p);
1389                         PoolItem itemFrom = _pool.find (s);
1390                         if (rp)
1391                         {
1392                             int gotone = 0;
1393
1394                             sd = mapSolvable (rp);
1395                             PoolItem itemTo = _pool.find (sd);
1396                             if (itemFrom && itemTo) {
1397                                 problemSolution->addSingleAction (itemTo, INSTALL);
1398                                 int illegal = policy_is_illegal(_satSolver, s.get(), sd.get(), 0);
1399
1400                                 if ((illegal & POLICY_ILLEGAL_DOWNGRADE) != 0)
1401                                 {
1402                                     string description = str::form (_("downgrade of %s to %s"), s.asString().c_str(), sd.asString().c_str());
1403                                     MIL << description << endl;
1404                                     problemSolution->addDescription (description);
1405                                     gotone = 1;
1406                                 }
1407                                 if ((illegal & POLICY_ILLEGAL_ARCHCHANGE) != 0)
1408                                 {
1409                                     string description = str::form (_("architecture change of %s to %s"), s.asString().c_str(), sd.asString().c_str());
1410                                     MIL << description << endl;
1411                                     problemSolution->addDescription (description);
1412                                     gotone = 1;
1413                                 }
1414                                 if ((illegal & POLICY_ILLEGAL_VENDORCHANGE) != 0)
1415                                 {
1416                                     IdString s_vendor( s.vendor() );
1417                                     IdString sd_vendor( sd.vendor() );
1418                                     string description = str::form (_("install %s (with vendor change)\n  %s  -->  %s") ,
1419                                                                     sd.asString().c_str(),
1420                                                                     ( s_vendor ? s_vendor.c_str() : " (no vendor) " ),
1421                                                                     ( sd_vendor ? sd_vendor.c_str() : " (no vendor) " ) );
1422                                     MIL << description << endl;
1423                                     problemSolution->addDescription (description);
1424                                     gotone = 1;
1425                                 }
1426                                 if (!gotone) {
1427                                     string description = str::form (_("replacement of %s with %s"), s.asString().c_str(), sd.asString().c_str());
1428                                     MIL << description << endl;
1429                                     problemSolution->addDescription (description);
1430                                 }
1431                             } else {
1432                                 ERR << s.asString() << " or "  << sd.asString() << " not found" << endl;
1433                             }
1434                         }
1435                         else
1436                         {
1437                             if (itemFrom) {
1438                                 string description = str::form (_("deinstallation of %s"), s.asString().c_str());
1439                                 MIL << description << endl;
1440                                 problemSolution->addDescription (description);
1441                                 problemSolution->addSingleAction (itemFrom, REMOVE);
1442                             }
1443                         }
1444                     }
1445                     else
1446                     {
1447                       INT << "Unknown solution " << p << endl;
1448                     }
1449
1450                 }
1451                 resolverProblem->addSolution (problemSolution,
1452                                               problemSolution->actionCount() > 1 ? true : false); // Solutions with more than 1 action will be shown first.
1453                 MIL << "------------------------------------" << endl;
1454             }
1455
1456             if (ignoreId > 0) {
1457                 // There is a possibility to ignore this error by setting weak dependencies
1458                 PoolItem item = _pool.find (sat::Solvable(ignoreId));
1459                 ProblemSolutionIgnore *problemSolution = new ProblemSolutionIgnore(item);
1460                 resolverProblem->addSolution (problemSolution,
1461                                               false); // Solutions will be shown at the end
1462                 MIL << "ignore some dependencies of " << item << endl;
1463                 MIL << "------------------------------------" << endl;
1464             }
1465
1466             // save problem
1467             resolverProblems.push_back (resolverProblem);
1468         }
1469     }
1470     return resolverProblems;
1471 }
1472
1473 void SATResolver::applySolutions( const ProblemSolutionList & solutions )
1474 { Resolver( _pool ).applySolutions( solutions ); }
1475
1476 void SATResolver::setLocks()
1477 {
1478     unsigned icnt = 0;
1479     unsigned acnt = 0;
1480
1481     for (PoolItemList::const_iterator iter = _items_to_lock.begin(); iter != _items_to_lock.end(); ++iter) {
1482         sat::detail::SolvableIdType ident( (*iter)->satSolvable().id() );
1483         if (iter->status().isInstalled()) {
1484             ++icnt;
1485             queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE );
1486             queue_push( &(_jobQueue), ident );
1487         } else {
1488             ++acnt;
1489             queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE | MAYBE_CLEANDEPS );
1490             queue_push( &(_jobQueue), ident );
1491         }
1492     }
1493     MIL << "Locked " << icnt << " installed items and " << acnt << " NOT installed items." << endl;
1494
1495     ///////////////////////////////////////////////////////////////////
1496     // Weak locks: Ignore if an item with this name is already installed.
1497     // If it's not installed try to keep it this way using a weak delete
1498     ///////////////////////////////////////////////////////////////////
1499     std::set<IdString> unifiedByName;
1500     for (PoolItemList::const_iterator iter = _items_to_keep.begin(); iter != _items_to_keep.end(); ++iter) {
1501       IdString ident( (*iter)->satSolvable().ident() );
1502       if ( unifiedByName.insert( ident ).second )
1503       {
1504         if ( ! ui::Selectable::get( *iter )->hasInstalledObj() )
1505         {
1506           MIL << "Keep NOT installed name " << ident << " (" << *iter << ")" << endl;
1507           queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE_NAME | SOLVER_WEAK | MAYBE_CLEANDEPS );
1508           queue_push( &(_jobQueue), ident.id() );
1509         }
1510       }
1511     }
1512 }
1513
1514 void SATResolver::setSystemRequirements()
1515 {
1516     CapabilitySet system_requires = SystemCheck::instance().requiredSystemCap();
1517     CapabilitySet system_conflicts = SystemCheck::instance().conflictSystemCap();
1518
1519     for (CapabilitySet::const_iterator iter = system_requires.begin(); iter != system_requires.end(); ++iter) {
1520         queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE_PROVIDES );
1521         queue_push( &(_jobQueue), iter->id() );
1522         MIL << "SYSTEM Requires " << *iter << endl;
1523     }
1524
1525     for (CapabilitySet::const_iterator iter = system_conflicts.begin(); iter != system_conflicts.end(); ++iter) {
1526         queue_push( &(_jobQueue), SOLVER_ERASE | SOLVER_SOLVABLE_PROVIDES | MAYBE_CLEANDEPS );
1527         queue_push( &(_jobQueue), iter->id() );
1528         MIL << "SYSTEM Conflicts " << *iter << endl;
1529     }
1530
1531     // Lock the architecture of the running systems rpm
1532     // package on distupgrade.
1533     if ( _distupgrade && ZConfig::instance().systemRoot() == "/" )
1534     {
1535       ResPool pool( ResPool::instance() );
1536       IdString rpm( "rpm" );
1537       for_( it, pool.byIdentBegin(rpm), pool.byIdentEnd(rpm) )
1538       {
1539         if ( (*it)->isSystem() )
1540         {
1541           Capability archrule( (*it)->arch(), rpm.c_str(), Capability::PARSED );
1542           queue_push( &(_jobQueue), SOLVER_INSTALL | SOLVER_SOLVABLE_NAME | SOLVER_ESSENTIAL );
1543           queue_push( &(_jobQueue), archrule.id() );
1544
1545         }
1546       }
1547     }
1548 }
1549
1550 sat::StringQueue SATResolver::autoInstalled() const
1551 {
1552   sat::StringQueue ret;
1553   if ( _satSolver )
1554     ::solver_get_userinstalled( _satSolver, ret, GET_USERINSTALLED_NAMES|GET_USERINSTALLED_INVERTED );
1555   return ret;
1556 }
1557
1558 sat::StringQueue SATResolver::userInstalled() const
1559 {
1560   sat::StringQueue ret;
1561   if ( _satSolver )
1562     ::solver_get_userinstalled( _satSolver, ret, GET_USERINSTALLED_NAMES );
1563   return ret;
1564 }
1565
1566
1567 ///////////////////////////////////////////////////////////////////
1568 };// namespace detail
1569     /////////////////////////////////////////////////////////////////////
1570     /////////////////////////////////////////////////////////////////////
1571   };// namespace solver
1572   ///////////////////////////////////////////////////////////////////////
1573   ///////////////////////////////////////////////////////////////////////
1574 };// namespace zypp
1575 /////////////////////////////////////////////////////////////////////////
1576