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