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