3035202298fa7977e95a0881a5e50090bca621ec
[platform/upstream/libzypp.git] / zypp / sat / 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 #include <sstream>
22 #include "zypp/solver/detail/Helper.h"
23 #include "zypp/base/String.h"
24 #include "zypp/Capability.h"
25 #include "zypp/ResStatus.h"
26 #include "zypp/VendorAttr.h"
27 #include "zypp/base/Logger.h"
28 #include "zypp/base/String.h"
29 #include "zypp/base/Gettext.h"
30 #include "zypp/base/Algorithm.h"
31 #include "zypp/ResPool.h"
32 #include "zypp/ResFilters.h"
33 #include "zypp/ZConfig.h"
34 #include "zypp/sat/SATResolver.h"
35 #include "zypp/sat/Pool.h"
36 #include "zypp/sat/WhatProvides.h"
37 #include "zypp/solver/detail/ProblemSolutionCombi.h"
38
39 extern "C" {
40 #include "satsolver/repo_solv.h"
41 #include "satsolver/poolarch.h"
42 #include "satsolver/evr.h"
43 #include "satsolver/poolvendor.h"
44 #include "satsolver/policy.h"
45 #include "satsolver/bitmap.h"    
46 }
47
48 /////////////////////////////////////////////////////////////////////////
49 namespace zypp
50 { ///////////////////////////////////////////////////////////////////////
51   ///////////////////////////////////////////////////////////////////////
52   namespace solver
53   { /////////////////////////////////////////////////////////////////////
54     /////////////////////////////////////////////////////////////////////
55     namespace detail
56     { ///////////////////////////////////////////////////////////////////
57
58 using namespace std;
59
60 IMPL_PTR_TYPE(SATResolver);
61
62 //---------------------------------------------------------------------------
63 // Callbacks for SAT policies
64 //---------------------------------------------------------------------------
65
66 int vendorCheck (Pool *pool, Solvable *solvable1, Solvable *solvable2) {
67 //    DBG << "vendorCheck: " << id2str(pool, solvable1->vendor) << " <--> " << id2str(pool, solvable1->vendor) << endl;
68     return VendorAttr::instance().equivalent(id2str(pool, solvable1->vendor), id2str(pool, solvable2->vendor)) ? 0:1;
69 }
70
71
72 string
73 itemToString (PoolItem item, bool shortVersion)
74 {
75     ostringstream os;
76     if (!item) return "";
77
78     if (item->kind() != ResTraits<zypp::Package>::kind)
79         os << item->kind() << ':';
80     os  << item->name();
81     if (!shortVersion) {
82         os << '-' << item->edition();
83         if (item->arch() != "") {
84             os << '.' << item->arch();
85         }
86         Repository s = item->repository();
87         if (s) {
88             string alias = s.info().alias();
89             if (!alias.empty()
90                 && alias != "@system")
91             {
92                 os << '[' << s.info().alias() << ']';
93             }
94         }
95     }
96     return os.str();
97 }
98         
99
100 //---------------------------------------------------------------------------
101
102 std::ostream &
103 SATResolver::dumpOn( std::ostream & os ) const
104 {
105     os << "<resolver>";     
106     os << "  fixsystem = " << _fixsystem << endl;
107     os << "  allowdowngrade = " << _allowdowngrade << endl;
108     os << "  allowarchchange = " << _allowarchchange << endl;
109     os << "  allowvendorchange = " <<  _allowvendorchange << endl;
110     os << "  allowuninstall = " << _allowuninstall << endl;
111     os << "  updatesystem = " << _updatesystem << endl;
112     os << "  allowvirtualconflicts = " <<  _allowvirtualconflicts << endl;
113     os << "  noupdateprovide = " << _noupdateprovide << endl;
114     os << "  dosplitprovides = " << _dosplitprovides << endl;
115     os << "  onlyRequires = " << _onlyRequires << endl;
116     return os << "<resolver/>" << endl;
117 }
118
119 //---------------------------------------------------------------------------
120
121 SATResolver::SATResolver (const ResPool & pool, Pool *SATPool)
122     : _pool (pool)
123     , _SATPool (SATPool)
124     , _solv(NULL)
125     , _fixsystem(false)
126     , _allowdowngrade(false)
127     , _allowarchchange(false)
128     , _allowvendorchange(false)
129     , _allowuninstall(false)
130     , _updatesystem(false)
131     , _allowvirtualconflicts(false)
132     , _noupdateprovide(false)
133     , _dosplitprovides(false)
134     , _onlyRequires(ZConfig::instance().solver_onlyRequires())
135
136 {
137 }
138
139
140 SATResolver::~SATResolver()
141 {
142 }
143
144 //---------------------------------------------------------------------------
145
146
147 ResPool
148 SATResolver::pool (void) const
149 {
150     return _pool;
151 }
152
153
154 void
155 SATResolver::resetItemTransaction (PoolItem item)
156 {
157     bool found = false;
158     for (PoolItemList::const_iterator iter = _items_to_remove.begin();
159          iter != _items_to_remove.end(); iter++) {
160         if (*iter == item) {
161             _items_to_remove.remove(*iter);
162             found = true;
163             break;
164         }
165     }
166     if (!found) {
167         for (PoolItemList::const_iterator iter = _items_to_install.begin();
168              iter != _items_to_install.end(); iter++) {
169             if (*iter == item) {
170                 _items_to_install.remove(*iter);
171                 found = true;
172                 break;
173             }
174         }
175     }
176     if (!found) {
177         for (PoolItemList::const_iterator iter = _items_to_keep.begin();
178              iter != _items_to_keep.end(); iter++) {
179             if (*iter == item) {
180                 _items_to_keep.remove(*iter);
181                 found = true;
182                 break;
183             }
184         }
185     }
186     if (!found) {
187         for (PoolItemList::const_iterator iter = _items_to_lock.begin();
188              iter != _items_to_lock.end(); iter++) {
189             if (*iter == item) {
190                 _items_to_lock.remove(*iter);
191                 found = true;
192                 break;
193             }
194         }
195     }        
196     if (!found) {
197         for (PoolItemList::const_iterator iter = _items_to_update.begin();
198              iter != _items_to_update.end(); iter++) {
199             if (*iter == item) {
200                 _items_to_update.remove(*iter);
201                 found = true;
202                 break;
203             }
204         }
205     }        
206 }
207
208
209 void
210 SATResolver::addPoolItemToInstall (PoolItem item)
211 {
212     resetItemTransaction (item);
213     _items_to_install.push_back (item);
214     _items_to_install.unique ();
215 }
216
217
218 void
219 SATResolver::addPoolItemsToInstallFromList (PoolItemList & rl)
220 {
221     for (PoolItemList::const_iterator iter = rl.begin(); iter != rl.end(); iter++) {
222         addPoolItemToInstall (*iter);
223     }
224 }
225
226
227 void
228 SATResolver::addPoolItemToRemove (PoolItem item)
229 {
230     resetItemTransaction (item);    
231     _items_to_remove.push_back (item);
232     _items_to_remove.unique ();
233 }
234
235
236 void
237 SATResolver::addPoolItemsToRemoveFromList (PoolItemList & rl)
238 {
239     for (PoolItemList::const_iterator iter = rl.begin(); iter != rl.end(); iter++) {
240         addPoolItemToRemove (*iter);
241     }
242 }
243
244 void
245 SATResolver::addPoolItemToLock (PoolItem item)
246 {
247     resetItemTransaction (item);    
248     _items_to_lock.push_back (item);
249     _items_to_lock.unique ();
250 }
251
252 void
253 SATResolver::addPoolItemToKeep (PoolItem item)
254 {
255     resetItemTransaction (item);    
256     _items_to_keep.push_back (item);
257     _items_to_keep.unique ();
258 }
259
260 //---------------------------------------------------------------------------
261
262 // copy marked item from solution back to pool
263 // if data != NULL, set as APPL_LOW (from establishPool())
264
265 static void
266 SATSolutionToPool (PoolItem item, const ResStatus & status, const ResStatus::TransactByValue causer)
267 {
268     // resetting 
269     item.status().resetTransact (causer);
270     item.status().resetWeak ();
271
272     bool r;
273
274     // installation/deletion
275     if (status.isToBeInstalled()) {
276         r = item.status().setToBeInstalled (causer);
277         _XDEBUG("SATSolutionToPool(" << item << ", " << status << ") install !" << r);
278     }
279     else if (status.isToBeUninstalledDueToUpgrade()) {
280         r = item.status().setToBeUninstalledDueToUpgrade (causer);
281         _XDEBUG("SATSolutionToPool(" << item << ", " << status << ") upgrade !" << r);
282     }
283     else if (status.isToBeUninstalled()) {
284         r = item.status().setToBeUninstalled (causer);
285         _XDEBUG("SATSolutionToPool(" << item << ", " << status << ") remove !" << r);
286     }
287
288     // recommend/suggest
289     if (status.isRecommended()) {
290         item.status().setRecommended(true);
291         _XDEBUG("SATSolutionToPool(" << item << ", " << status << ") recommended !" << r);
292     }
293     else if (status.isSuggested()) {
294         item.status().setSuggested(true);
295         _XDEBUG("SATSolutionToPool(" << item << ", " << status << ") suggested !" << r);        
296     }
297
298     return;
299 }
300
301
302 //----------------------------------------------------------------------------
303 // helper functions for distupgrade 
304 //----------------------------------------------------------------------------
305
306 bool SATResolver::doesObsoleteItem (PoolItem candidate, PoolItem installed) {
307   Solvable *sCandidate = _SATPool->solvables + candidate.satSolvable().id();
308   ::_Repo *installedRepo = sat::Pool::instance().systemRepo().get();
309   
310   Id p, *pp, obsolete, *obsoleteIt;
311   
312   if ((!installedRepo || sCandidate->repo != installedRepo) && sCandidate->obsoletes) {
313       obsoleteIt = sCandidate->repo->idarraydata + sCandidate->obsoletes;
314       while ((obsolete = *obsoleteIt++) != 0)
315       {
316           for (pp = pool_whatprovides(_SATPool, obsolete) ; (p = *pp++) != 0; ) {
317               if (p > 0 &&  installed.satSolvable().id() == (sat::detail::SolvableIdType)p) {
318                   MIL << candidate << " obsoletes " << installed << endl;
319                   return true;
320               }
321           }
322       }
323   }
324   return false;
325 }
326
327 //----------------------------------------------------------------------------
328 //----------------------------------------------------------------------------
329 // resolvePool
330 //----------------------------------------------------------------------------
331 //----------------------------------------------------------------------------
332
333 //----------------------------------------------------------------------------
334 // Helper functions for the ZYPP-Pool
335 //----------------------------------------------------------------------------
336
337
338 //------------------------------------------------------------------------------------------------------------
339 //  This function loops over the pool and grabs all items
340 //  It clears all previous bySolver() states also
341 //
342 //  Every toBeInstalled is passed to zypp::solver:detail::Resolver.addPoolItemToInstall()
343 //  Every toBeUninstalled is passed to zypp::solver:detail::Resolver.addPoolItemToRemove()
344 //
345 //  Solver results must be written back to the pool.
346 //------------------------------------------------------------------------------------------------------------
347
348
349 struct SATCollectTransact : public resfilter::PoolItemFilterFunctor
350 {
351     SATResolver & resolver;
352
353     SATCollectTransact (SATResolver & r)
354         : resolver (r)
355     { }
356
357     bool operator()( PoolItem item )            // only transacts() items go here
358     {
359         ResStatus status = item.status();
360         bool by_solver = (status.isBySolver() || status.isByApplLow());
361
362         if (by_solver) {
363             _XDEBUG("Resetting " << item );
364             item.status().resetTransact( ResStatus::APPL_LOW );// clear any solver/establish transactions
365             return true;                                // back out here, dont re-queue former solver result
366         }
367
368         if (status.isToBeInstalled()) {
369             resolver.addPoolItemToInstall(item);        // -> install!
370         }
371         else if (status.isToBeUninstalled()) {
372             resolver.addPoolItemToRemove(item);         // -> remove !
373         }
374         else if (status.isLocked()
375                  && !by_solver) {
376             resolver.addPoolItemToLock (item);
377         }
378         else if (status.isKept()
379                  && !by_solver) {
380             resolver.addPoolItemToKeep (item);
381         }       
382
383         return true;
384     }
385 };
386
387
388 //----------------------------------------------------------------------------
389 //----------------------------------------------------------------------------
390 // solving.....
391 //----------------------------------------------------------------------------
392 //----------------------------------------------------------------------------
393
394
395 class CheckIfUpdate : public resfilter::PoolItemFilterFunctor
396 {
397   public:
398     bool is_updated;
399
400     CheckIfUpdate()
401         : is_updated( false )
402     {}
403
404     // check this item will be installed
405
406     bool operator()( PoolItem item )
407     {
408         if (item.status().isToBeInstalled())
409         {
410             is_updated = true;
411             return false;
412         }
413         return true;
414     }
415 };
416
417
418 class SetValidate : public resfilter::PoolItemFilterFunctor
419 {
420   public:
421     Map installedmap, conflictsmap;    
422
423     SetValidate(Solver *solv)
424     {
425         solver_create_state_maps(solv, &installedmap, &conflictsmap);
426     }
427
428     // set validation 
429
430     bool operator()( PoolItem item )
431     {
432         int ret = solvable_trivial_installable_map(item.satSolvable().get(), &installedmap, &conflictsmap);
433         item.status().setUndetermined();        
434     
435         if (ret == -1) {
436             item.status().setNonRelevant();
437             _XDEBUG("SATSolutionToPool(" << item << " ) nonRelevant !");
438         } else if (ret == 1) {
439             item.status().setSatisfied();
440             _XDEBUG("SATSolutionToPool(" << item << " ) satisfied !");
441         } else if (ret == 0) {
442             item.status().setBroken();
443             _XDEBUG("SATSolutionToPool(" << item << " ) broken !");                 
444         }
445         return true;
446     }
447 };
448
449
450 bool
451 SATResolver::resolvePool(const CapabilitySet & requires_caps,
452                          const CapabilitySet & conflict_caps)
453 {
454     SATCollectTransact info (*this);
455     
456     MIL << "SATResolver::resolvePool()" << endl;
457
458     if (_solv) {
459         // remove old stuff
460         solver_free(_solv);
461         _solv = NULL;
462         queue_free( &(_jobQueue) );
463     }
464
465     queue_init( &_jobQueue );
466     _items_to_install.clear();
467     _items_to_remove.clear();
468     _items_to_lock.clear();
469     _items_to_keep.clear();    
470
471     invokeOnEach ( _pool.begin(), _pool.end(),
472                    functor::functorRef<bool,PoolItem>(info) );
473
474     for (PoolItemList::const_iterator iter = _items_to_install.begin(); iter != _items_to_install.end(); iter++) {
475         PoolItem r = *iter;
476
477         Id id = (*iter)->satSolvable().id();
478         if (id == ID_NULL) {
479             ERR << "Install: " << *iter << " not found" << endl;
480         }
481         MIL << "Install " << *iter << " with the SAT-Pool ID: " << id << endl;
482         queue_push( &(_jobQueue), SOLVER_INSTALL_SOLVABLE );
483         queue_push( &(_jobQueue), id );
484     }
485
486     for (PoolItemList::const_iterator iter = _items_to_update.begin(); iter != _items_to_update.end(); iter++) {
487         PoolItem r = *iter;
488
489         Id id = (*iter)->satSolvable().id();
490         if (id == ID_NULL) {
491             ERR << "Update explicit: " << *iter << " not found" << endl;
492         }
493         MIL << "Update explicit " << *iter << " with the SAT-Pool ID: " << id << endl;
494         queue_push( &(_jobQueue), SOLVER_INSTALL_SOLVABLE_UPDATE );
495         queue_push( &(_jobQueue), id );
496     }    
497
498     for (PoolItemList::const_iterator iter = _items_to_remove.begin(); iter != _items_to_remove.end(); iter++) {
499         sat::detail::IdType ident( (*iter)->satSolvable().ident().id() );
500         MIL << "Delete " << *iter << " with the string ID: " << ident << endl;
501         queue_push( &(_jobQueue), SOLVER_ERASE_SOLVABLE_NAME );
502         queue_push( &(_jobQueue), ident);
503     }
504
505     for (CapabilitySet::const_iterator iter = requires_caps.begin(); iter != requires_caps.end(); iter++) {
506         queue_push( &(_jobQueue), SOLVER_INSTALL_SOLVABLE_PROVIDES );
507         queue_push( &(_jobQueue), iter->id() );
508         MIL << "Requires " << *iter << endl;
509     }
510
511     for (CapabilitySet::const_iterator iter = conflict_caps.begin(); iter != conflict_caps.end(); iter++) {
512         queue_push( &(_jobQueue), SOLVER_ERASE_SOLVABLE_PROVIDES);
513         queue_push( &(_jobQueue), iter->id() );
514         MIL << "Conflicts " << *iter << endl;
515     }
516
517     for (PoolItemList::const_iterator iter = _items_to_lock.begin(); iter != _items_to_lock.end(); iter++) {
518         sat::detail::SolvableIdType ident( (*iter)->satSolvable().id() );
519         if (iter->status().isInstalled()) {
520             MIL << "Lock installed item " << *iter << " with the string ID: " << ident << endl;
521             queue_push( &(_jobQueue), SOLVER_INSTALL_SOLVABLE );
522             queue_push( &(_jobQueue), ident );
523         } else {
524             MIL << "Lock NOT installed item " << *iter << " with the string ID: " << ident << endl;
525             queue_push( &(_jobQueue), SOLVER_ERASE_SOLVABLE );
526             queue_push( &(_jobQueue), ident );
527         }
528     }
529
530     for (PoolItemList::const_iterator iter = _items_to_keep.begin(); iter != _items_to_keep.end(); iter++) {
531         sat::detail::SolvableIdType ident( (*iter)->satSolvable().id() );
532         if (iter->status().isInstalled()) {
533             MIL << "Keep installed item " << *iter << " with the string ID: " << ident << endl;
534             queue_push( &(_jobQueue), SOLVER_INSTALL_SOLVABLE | SOLVER_WEAK);
535             queue_push( &(_jobQueue), ident );
536         } else {
537             MIL << "Keep NOT installed item " << *iter << " with the string ID: " << ident << endl;
538             queue_push( &(_jobQueue), SOLVER_ERASE_SOLVABLE | SOLVER_WEAK);
539             queue_push( &(_jobQueue), ident );
540         }
541     }    
542
543     _solv = solver_create( _SATPool, sat::Pool::instance().systemRepo().get() );
544     _solv->vendorCheckCb = &vendorCheck;
545     _solv->fixsystem = _fixsystem;
546     _solv->updatesystem = _updatesystem;
547     _solv->allowdowngrade = _allowdowngrade;
548     _solv->allowuninstall = _allowuninstall;
549     _solv->allowarchchange = _allowarchchange;
550     _solv->dosplitprovides = _dosplitprovides;
551     _solv->noupdateprovide = _noupdateprovide;
552     _solv->dontinstallrecommended = _onlyRequires;
553     
554     sat::Pool::instance().prepare();
555
556     // Solve !
557     MIL << "Starting solving...." << endl;
558     MIL << *this;
559     solver_solve( _solv, &(_jobQueue) );
560     MIL << "....Solver end" << endl;
561
562     // copying solution back to zypp pool
563     //-----------------------------------------
564
565     if (_solv->problems.count > 0 )
566     {
567         ERR << "Solverrun finished with an ERROR" << endl;
568         return false;
569     }
570
571     /*  solvables to be installed */
572     for (int i = 0; i < _solv->decisionq.count; i++)
573     {
574       Id p;
575       p = _solv->decisionq.elements[i];
576       if (p < 0 || !sat::Solvable(p))
577         continue;
578       if (sat::Solvable(p).repository().get() == _solv->installed)
579         continue;
580
581       PoolItem poolItem = _pool.find (sat::Solvable(p));
582       if (poolItem) {
583           SATSolutionToPool (poolItem, ResStatus::toBeInstalled, ResStatus::SOLVER);
584       } else {
585           ERR << "id " << p << " not found in ZYPP pool." << endl;
586       }
587     }
588
589     /* solvables to be erased */
590     for (int i = _solv->installed->start; i < _solv->installed->start + _solv->installed->nsolvables; i++)
591     {
592       if (_solv->decisionmap[i] > 0)
593         continue;
594
595       PoolItem poolItem = _pool.find (sat::Solvable(i));
596       if (poolItem) {
597           // Check if this is an update
598           CheckIfUpdate info;
599           invokeOnEach( _pool.byIdentBegin( poolItem ),
600                         _pool.byIdentEnd( poolItem ),
601                         resfilter::ByUninstalled(),                     // ByUninstalled
602                         functor::functorRef<bool,PoolItem> (info) );
603
604           if (info.is_updated) {
605               SATSolutionToPool (poolItem, ResStatus::toBeUninstalledDueToUpgrade , ResStatus::SOLVER);
606           } else {
607               SATSolutionToPool (poolItem, ResStatus::toBeUninstalled, ResStatus::SOLVER);
608           }
609       } else {
610           ERR << "id " << i << " not found in ZYPP pool." << endl;
611       }
612     }
613
614     /*  solvables which are recommended */
615     for (int i = 0; i < _solv->recommendations.count; i++)
616     {
617       Id p;
618       p = _solv->recommendations.elements[i];
619       if (p < 0 || !sat::Solvable(p))
620         continue;
621
622       PoolItem poolItem = _pool.find (sat::Solvable(p));
623       if (poolItem) {
624           ResStatus status = poolItem.status();
625           status.setRecommended (true);
626           SATSolutionToPool (poolItem, status, ResStatus::SOLVER);
627       } else {
628           ERR << "id " << p << " not found in ZYPP pool." << endl;
629       }
630     }
631
632     /*  solvables which are suggested */
633     for (int i = 0; i < _solv->suggestions.count; i++)
634     {
635       Id p;
636       p = _solv->suggestions.elements[i];
637       if (p < 0 || !sat::Solvable(p))
638         continue;
639
640       PoolItem poolItem = _pool.find (sat::Solvable(p));
641       if (poolItem) {
642           ResStatus status = poolItem.status();
643           status.setSuggested (true);
644           SATSolutionToPool (poolItem, status, ResStatus::SOLVER);
645       } else {
646           ERR << "id " << p << " not found in ZYPP pool." << endl;
647       }
648     }
649
650     /* Write validation state back to pool */
651     SetValidate infoValidate(_solv);
652     invokeOnEach( _pool.begin(),
653                   _pool.end(),
654                   functor::not_c(resfilter::byKind<Package>()), // every solvable BUT packages
655                   functor::functorRef<bool,PoolItem> (infoValidate) );
656     
657     // cleanup
658     solver_free(_solv);
659     _solv = NULL;
660     queue_free( &(_jobQueue) );    
661
662     MIL << "SATResolver::resolvePool() done" << endl;
663     return true;
664 }
665
666
667 bool SATResolver::doUpdate()
668 {
669     MIL << "SATResolver::doUpdate()" << endl;
670
671     if (_solv) {
672         // remove old stuff
673         solver_free(_solv);
674         _solv = NULL;
675         queue_free( &(_jobQueue) );
676     }
677
678     queue_init( &_jobQueue );
679
680     _solv = solver_create( _SATPool, sat::Pool::instance().systemRepo().get() );
681     _solv->vendorCheckCb = &vendorCheck;
682
683     _solv->updatesystem = true;
684     _solv->dontinstallrecommended = true; // #FIXME dontinstallrecommended maybe set to false if it works correctly
685     
686     sat::Pool::instance().prepare();
687
688     // Solve !
689     MIL << "Starting solving for update...." << endl;
690     MIL << *this;    
691     solver_solve( _solv, &(_jobQueue) );
692     MIL << "....Solver end" << endl;
693
694     // copying solution back to zypp pool
695     //-----------------------------------------
696
697     /*  solvables to be installed */
698     for (int i = 0; i < _solv->decisionq.count; i++)
699     {
700       Id p;
701       p = _solv->decisionq.elements[i];
702       if (p < 0 || !sat::Solvable(p))
703         continue;
704       if (sat::Solvable(p).repository().get() == _solv->installed)
705         continue;
706
707       PoolItem poolItem = _pool.find (sat::Solvable(p));
708       if (poolItem) {
709           SATSolutionToPool (poolItem, ResStatus::toBeInstalled, ResStatus::SOLVER);
710       } else {
711           ERR << "id " << p << " not found in ZYPP pool." << endl;
712       }
713     }
714
715     /* solvables to be erased */
716     for (int i = _solv->installed->start; i < _solv->installed->start + _solv->installed->nsolvables; i++)
717     {
718       if (_solv->decisionmap[i] > 0)
719         continue;
720
721       PoolItem poolItem = _pool.find (sat::Solvable(i));
722       if (poolItem) {
723           // Check if this is an update
724           CheckIfUpdate info;
725           invokeOnEach( _pool.byIdentBegin( poolItem ),
726                         _pool.byIdentEnd( poolItem ),
727                         resfilter::ByUninstalled(),                     // ByUninstalled
728                         functor::functorRef<bool,PoolItem> (info) );
729
730           if (info.is_updated) {
731               SATSolutionToPool (poolItem, ResStatus::toBeUninstalledDueToUpgrade , ResStatus::SOLVER);
732           } else {
733               SATSolutionToPool (poolItem, ResStatus::toBeUninstalled, ResStatus::SOLVER);
734           }
735       } else {
736           ERR << "id " << i << " not found in ZYPP pool." << endl;
737       }
738     }
739
740     // cleanup
741     solver_free(_solv);
742     _solv = NULL;
743     queue_free( &(_jobQueue) );    
744
745     MIL << "SATResolver::doUpdate() done" << endl;
746     return true;
747 }
748
749
750
751 //----------------------------------------------------------------------------
752 //----------------------------------------------------------------------------
753 // error handling
754 //----------------------------------------------------------------------------
755 //----------------------------------------------------------------------------
756
757 //----------------------------------------------------------------------------
758 // helper function
759 //----------------------------------------------------------------------------
760
761 struct FindPackage : public resfilter::ResObjectFilterFunctor
762 {
763     ProblemSolutionCombi *problemSolution;
764     TransactionKind action;
765     FindPackage (ProblemSolutionCombi *p, const TransactionKind act)
766        : problemSolution (p)
767          , action (act)
768     {
769     }
770
771     bool operator()( PoolItem p)
772     {
773         problemSolution->addSingleAction (p, action);
774         return true;
775     }
776 };
777
778
779 string SATResolver::SATprobleminfoString(Id problem, string &detail)
780 {
781   string ret;
782   Pool *pool = _solv->pool;
783   Id probr;
784   Id dep, source, target;
785   Solvable *s, *s2;
786
787   probr = solver_findproblemrule(_solv, problem);
788   switch (solver_problemruleinfo(_solv, &(_jobQueue), probr, &dep, &source, &target))
789   {
790       case SOLVER_PROBLEM_UPDATE_RULE:
791           s = pool_id2solvable(pool, source);
792           ret = str::form (_("problem with installed package %s"), solvable2str(pool, s));
793           break;
794       case SOLVER_PROBLEM_JOB_RULE:
795           ret = str::form (_("conflicting requests"));
796           break;
797       case SOLVER_PROBLEM_JOB_NOTHING_PROVIDES_DEP:
798           ret = str::form (_("nothing provides requested %s"), dep2str(pool, dep));
799           break;
800       case SOLVER_PROBLEM_NOT_INSTALLABLE:
801           s = pool_id2solvable(pool, source);
802           ret = str::form (_("%s is not installable"), solvable2str(pool, s));
803           break;
804       case SOLVER_PROBLEM_NOTHING_PROVIDES_DEP:
805           s = pool_id2solvable(pool, source);
806           ret = str::form (_("nothing provides %s needed by %s"), dep2str(pool, dep), solvable2str(pool, s));
807           break;
808       case SOLVER_PROBLEM_SAME_NAME:
809           s = pool_id2solvable(pool, source);
810           s2 = pool_id2solvable(pool, target);
811           ret = str::form (_("cannot install both %s and %s"), solvable2str(pool, s), solvable2str(pool, s2));
812           break;
813       case SOLVER_PROBLEM_PACKAGE_CONFLICT:
814           s = pool_id2solvable(pool, source);
815           s2 = pool_id2solvable(pool, target);
816           ret = str::form (_("%s conflicts with %s provided by %s"), solvable2str(pool, s), dep2str(pool, dep), solvable2str(pool, s2));
817           break;
818       case SOLVER_PROBLEM_PACKAGE_OBSOLETES:
819           s = pool_id2solvable(pool, source);
820           s2 = pool_id2solvable(pool, target);
821           ret = str::form (_("%s obsoletes %s provided by %s"), solvable2str(pool, s), dep2str(pool, dep), solvable2str(pool, s2));
822           break;
823       case SOLVER_PROBLEM_DEP_PROVIDERS_NOT_INSTALLABLE:
824           s = pool_id2solvable(pool, source);
825           Capability cap(dep);
826           sat::WhatProvides possibleProviders(cap);
827
828           // check, if a provider will be deleted
829           typedef list<PoolItem> ProviderList;
830           ProviderList providerlistInstalled, providerlistUninstalled;
831           for_( iter1, possibleProviders.begin(), possibleProviders.end() ) {
832               PoolItem provider1 = ResPool::instance().find( *iter1 );
833               // find pair of an installed/uninstalled item with the same NVR
834               bool found = false;
835               for_( iter2, possibleProviders.begin(), possibleProviders.end() ) {
836                   PoolItem provider2 = ResPool::instance().find( *iter2 );                
837                   if (compareByNVR (provider1.resolvable(),provider2.resolvable()) == 0
838                       && ( (provider1.status().isInstalled() && provider2.status().isUninstalled())
839                           || (provider2.status().isInstalled() && provider1.status().isUninstalled()) ))  {
840                       found = true;
841                       break;
842                   }
843               }
844               if (!found) {
845                   if (provider1.status().isInstalled())
846                       providerlistInstalled.push_back(provider1);
847                   else
848                       providerlistUninstalled.push_back(provider1);
849               }
850           }
851
852           ret = str::form (_("%s requires %s, but this requirement cannot be provided"), solvable2str(pool, s), dep2str(pool, dep));
853           if (providerlistInstalled.size() > 0) {
854               detail += _("deleted providers: ");
855               for (ProviderList::const_iterator iter = providerlistInstalled.begin(); iter != providerlistInstalled.end(); iter++) {
856                   if (iter == providerlistInstalled.begin())
857                       detail += itemToString (*iter, false);
858                   else
859                       detail += "\n                   " + itemToString (*iter, false);
860               }
861           }
862           if (providerlistUninstalled.size() > 0) {
863               if (detail.size() > 0)
864                   detail += _("\nuninstallable providers: ");
865               else
866                   detail = _("uninstallable providers: ");                
867               for (ProviderList::const_iterator iter = providerlistUninstalled.begin(); iter != providerlistUninstalled.end(); iter++) {
868                   if (iter == providerlistUninstalled.begin())
869                       detail += itemToString (*iter, false);                  
870                   else
871                       detail += "\n                   " + itemToString (*iter, false);                
872               }
873           }       
874           break;
875   }
876
877   return ret;
878 }
879
880 ResolverProblemList
881 SATResolver::problems ()
882 {
883     ResolverProblemList resolverProblems;
884     if (_solv && _solv->problems.count) {
885         Pool *pool = _solv->pool;
886         int pcnt;
887         Id p, rp, what;
888         Id problem, solution, element;
889         Solvable *s, *sd;
890
891         MIL << "Encountered problems! Here are the solutions:\n" << endl;
892         pcnt = 1;
893         problem = 0;
894         while ((problem = solver_next_problem(_solv, problem)) != 0) {
895             MIL << "Problem " <<  pcnt++ << ":" << endl;
896             MIL << "====================================" << endl;
897             string detail;
898             string whatString = SATprobleminfoString (problem,detail);
899             MIL << whatString << endl;
900             MIL << "------------------------------------" << endl;
901             ResolverProblem_Ptr resolverProblem = new ResolverProblem (whatString, detail);
902             solution = 0;
903             while ((solution = solver_next_solution(_solv, problem, solution)) != 0) {
904                 element = 0;
905                 ProblemSolutionCombi *problemSolution = new ProblemSolutionCombi(resolverProblem);
906                 while ((element = solver_next_solutionelement(_solv, problem, solution, element, &p, &rp)) != 0) {
907                     if (p == 0) {
908                         /* job, rp is index into job queue */
909                         what = _jobQueue.elements[rp];
910                         switch (_jobQueue.elements[rp-1])
911                         {
912                             case SOLVER_INSTALL_SOLVABLE: {
913                                 s = pool->solvables + what;
914                                 PoolItem poolItem = _pool.find (sat::Solvable(what));
915                                 if (poolItem) {
916                                     if (_solv->installed && s->repo == _solv->installed) {
917                                         problemSolution->addSingleAction (poolItem, REMOVE);
918                                         string description = str::form (_("do not keep %s installed"),  solvable2str(pool, s) );
919                                         MIL << description << endl;
920                                         problemSolution->addDescription (description);
921                                     } else {
922                                         problemSolution->addSingleAction (poolItem, REMOVE);
923                                         string description = str::form (_("do not install %s"), solvable2str(pool, s));
924                                         MIL << description << endl;
925                                         problemSolution->addDescription (description);
926                                     }
927                                 } else {
928                                     ERR << "SOLVER_INSTALL_SOLVABLE: No item found for " << id2str(pool, s->name) << "-"
929                                         <<  id2str(pool, s->evr) << "." <<  id2str(pool, s->arch) << endl;
930                                 }
931                             }
932                                 break;
933                             case SOLVER_ERASE_SOLVABLE: {
934                                 s = pool->solvables + what;
935                                 PoolItem poolItem = _pool.find (sat::Solvable(what));
936                                 if (poolItem) {
937                                     if (_solv->installed && s->repo == _solv->installed) {
938                                         problemSolution->addSingleAction (poolItem, KEEP);
939                                         string description = str::form (_("keep %s"), solvable2str(pool, s));
940                                         MIL << description << endl;
941                                         problemSolution->addDescription (description);
942                                     } else {
943                                         problemSolution->addSingleAction (poolItem, INSTALL);
944                                         string description = str::form (_("do not forbid installation of %s"), solvable2str(pool, s));
945                                         MIL << description << endl;
946                                         problemSolution->addDescription (description);
947                                     }
948                                 } else {
949                                     ERR << "SOLVER_ERASE_SOLVABLE: No item found for " << id2str(pool, s->name) << "-" <<  id2str(pool, s->evr) << "." <<
950                                         id2str(pool, s->arch) << endl;
951                                 }
952                             }
953                                 break;
954                             case SOLVER_INSTALL_SOLVABLE_NAME:
955                                 {
956                                 FindPackage info (problemSolution, KEEP);
957                                 IdString ident( what );
958                                 invokeOnEach( _pool.byIdentBegin( ident ),
959                                               _pool.byIdentEnd( ident ),
960                                               resfilter::ByUninstalled (),
961                                               functor::functorRef<bool,PoolItem> (info) );
962                                 string description = str::form (_("do not install %s"), ident.c_str() );
963                                 MIL << description << endl;
964                                 problemSolution->addDescription (description);
965                                 }
966                                 break;
967                             case SOLVER_ERASE_SOLVABLE_NAME:
968                                 {
969                                 FindPackage info (problemSolution, KEEP);
970                                 IdString ident( what );
971                                 invokeOnEach( _pool.byIdentBegin( ident ),
972                                               _pool.byIdentEnd( ident ),
973                                               functor::chain (resfilter::ByInstalled (),                        // ByInstalled
974                                                               resfilter::ByTransact ()),                        // will be deinstalled
975                                               functor::functorRef<bool,PoolItem> (info) );
976                                 string description = str::form (_("keep %s"), ident.c_str());
977                                 MIL << description << endl;
978                                 problemSolution->addDescription (description);
979                                 }
980                                 break;
981                             case SOLVER_INSTALL_SOLVABLE_PROVIDES:
982                                 {
983                                 Id p, *pp;
984                                 FOR_PROVIDES(p, pp, what);
985                                 {
986                                     PoolItem poolItem = _pool.find (sat::Solvable(p));
987                                     if (poolItem.status().isToBeInstalled()
988                                         || poolItem.status().staysUninstalled())
989                                         problemSolution->addSingleAction (poolItem, KEEP);
990                                 }
991                                 string description = str::form (_("do not ask to install a solvable providing %s"), dep2str(pool, what));
992                                 MIL << description << endl;
993                                 problemSolution->addDescription (description);
994                                 }
995                                 break;
996                             case SOLVER_ERASE_SOLVABLE_PROVIDES:
997                                 {
998                                 Id p, *pp;
999                                 FOR_PROVIDES(p, pp, what);
1000                                 {
1001                                     PoolItem poolItem = _pool.find (sat::Solvable(p));
1002                                     if (poolItem.status().isToBeUninstalled()
1003                                         || poolItem.status().staysInstalled())
1004                                         problemSolution->addSingleAction (poolItem, KEEP);
1005                                 }
1006                                 string description = str::form (_("do not ask to delete all solvables providing %s"), dep2str(pool, what));
1007                                 MIL << description << endl;
1008                                 problemSolution->addDescription (description);
1009                                 }
1010                                 break;
1011                             case SOLVER_INSTALL_SOLVABLE_UPDATE:
1012                                 {
1013                                 PoolItem poolItem = _pool.find (sat::Solvable(what));
1014                                 s = pool->solvables + what;
1015                                 if (poolItem) {
1016                                     if (_solv->installed && s->repo == _solv->installed) {
1017                                         problemSolution->addSingleAction (poolItem, KEEP);
1018                                         string description = str::form (_("do not install most recent version of %s"), solvable2str(pool, s));
1019                                         MIL << description << endl;
1020                                         problemSolution->addDescription (description);
1021                                     } else {
1022                                         ERR << "SOLVER_INSTALL_SOLVABLE_UPDATE " << poolItem << " is not selected for installation" << endl;
1023                                     }
1024                                 } else {
1025                                     ERR << "SOLVER_INSTALL_SOLVABLE_UPDATE: No item found for " << id2str(pool, s->name) << "-" <<  id2str(pool, s->evr) << "." <<
1026                                         id2str(pool, s->arch) << endl;
1027                                 }
1028                                 }
1029                                 break;
1030                             default:
1031                                 MIL << "- do something different" << endl;
1032                                 ERR << "No valid solution available" << endl;
1033                                 break;
1034                         }
1035                     } else {
1036                         /* policy, replace p with rp */
1037                         s = pool->solvables + p;
1038                         sd = rp ? pool->solvables + rp : 0;
1039
1040                         PoolItem itemFrom = _pool.find (sat::Solvable(p));
1041                         if (rp)
1042                         {
1043                             int gotone = 0;
1044
1045                             PoolItem itemTo = _pool.find (sat::Solvable(rp));
1046                             if (itemFrom && itemTo) {
1047                                 problemSolution->addSingleAction (itemTo, INSTALL);
1048
1049                                 if (evrcmp(pool, s->evr, sd->evr, EVRCMP_COMPARE ) > 0)
1050                                 {
1051                                     string description = str::form (_("downgrade of %s to %s"), solvable2str(pool, s), solvable2str(pool, sd));
1052                                     MIL << description << endl;
1053                                     problemSolution->addDescription (description);
1054                                     gotone = 1;
1055                                 }
1056                                 if (!_solv->allowarchchange && s->name == sd->name && s->arch != sd->arch && policy_illegal_archchange(_solv, s, sd))
1057                                 {
1058                                     string description = str::form (_("architecture change of %s to %s"), solvable2str(pool, s), solvable2str(pool, sd));
1059                                     MIL << description << endl;
1060                                     problemSolution->addDescription (description);
1061                                     gotone = 1;
1062                                 }
1063                                 if (!_solv->allowvendorchange && s->name == sd->name && s->vendor != sd->vendor && policy_illegal_vendorchange(_solv, s, sd))
1064                                 {
1065                                     string description = str::form (_("install %s (with vendor change)\n  %s\n-->\n  %s") ,
1066                                                                     solvable2str(pool, sd) , id2str(pool, s->vendor),
1067                                                                     string(sd->vendor ?  id2str(pool, sd->vendor) : " (no vendor) ").c_str() );
1068                                     MIL << description << endl;
1069                                     problemSolution->addDescription (description);
1070                                     gotone = 1;
1071                                 }
1072                                 if (!gotone) {
1073                                     string description = str::form (_("replacement of %s with %s"), solvable2str(pool, s), solvable2str(pool, sd));
1074                                     MIL << description << endl;
1075                                     problemSolution->addDescription (description);
1076                                 }
1077                             } else {
1078                                 ERR << id2str(pool, s->name) << "-" <<  id2str(pool, s->evr) << "." <<  id2str(pool, s->arch)
1079                                     << " or "  << id2str(pool, sd->name) << "-" <<  id2str(pool, sd->evr) << "." <<  id2str(pool, sd->arch) << " not found" << endl;
1080                             }
1081                         }
1082                         else
1083                         {
1084                             if (itemFrom) {
1085                                 string description = str::form (_("deinstallation of %s"), solvable2str(pool, s));
1086                                 MIL << description << endl;
1087                                 problemSolution->addDescription (description);
1088                                 problemSolution->addSingleAction (itemFrom, REMOVE);
1089                             }
1090                         }
1091                     }
1092                 }
1093                 resolverProblem->addSolution (problemSolution,
1094                                               problemSolution->actionCount() > 1 ? true : false); // Solutions with more than 1 action will be shown first.
1095                 MIL << "------------------------------------" << endl;
1096             }
1097             // save problem
1098             resolverProblems.push_back (resolverProblem);
1099         }
1100     }
1101     return resolverProblems;
1102 }
1103
1104 void
1105 SATResolver::applySolutions (const ProblemSolutionList & solutions)
1106 {
1107     for (ProblemSolutionList::const_iterator iter = solutions.begin();
1108          iter != solutions.end(); ++iter) {
1109         ProblemSolution_Ptr solution = *iter;
1110         Resolver dummyResolver(_pool);
1111         if (!solution->apply (dummyResolver))
1112             break;
1113     }
1114 }
1115
1116
1117
1118 ///////////////////////////////////////////////////////////////////
1119 };// namespace detail
1120     /////////////////////////////////////////////////////////////////////
1121     /////////////////////////////////////////////////////////////////////
1122   };// namespace solver
1123   ///////////////////////////////////////////////////////////////////////
1124   ///////////////////////////////////////////////////////////////////////
1125 };// namespace zypp
1126 /////////////////////////////////////////////////////////////////////////
1127