Pass arch to compare function in solver.
[zeroinstall/zeroinstall-mseaborn.git] / zeroinstall / injector / solver.py
blobdbea60353556db43e07ee91cbd7ec89841d779bb
1 """
2 Chooses a set of components to make a running program.
4 This class is intended to replace L{policy.Policy}.
5 """
7 import os
8 from logging import debug, warn, info
10 from zeroinstall.zerostore import BadDigest, NotStored
12 from zeroinstall.injector import selections
13 from zeroinstall.injector import model
15 # Copyright (C) 2008, Thomas Leonard
16 # See the README file for details, or visit http://0install.net.
18 class Solver(object):
19 """Chooses a set of implementations to satisfy the requirements of a program and its user.
20 Typical use:
21 1. Create a Solver object and configure it
22 2. Call L{solve}.
23 3. If any of the returned feeds_used are stale or missing, you may like to start downloading them
24 4. If it is 'ready' then you can download and run the chosen versions.
25 @ivar selections: the chosen implementation of each interface
26 @type selections: {L{model.Interface}: Implementation}
27 @ivar feeds_used: the feeds which contributed to the choice in L{selections}
28 @type feeds_used: set(str)
29 @ivar record_details: whether to record information about unselected implementations
30 @type record_details: {L{Interface}: [(L{Implementation}, str)]}
31 @ivar details: extra information, if record_details mode was used
32 @type details: {str: [(Implementation, comment)]}
33 """
34 __slots__ = ['selections', 'feeds_used', 'details', 'record_details']
36 def __init__(self):
37 self.selections = self.feeds_used = self.details = None
38 self.record_details = False
40 def solve(self, root_interface, arch):
41 """Get the best implementation of root_interface and all of its dependencies.
42 @param root_interface: the URI of the program to be solved
43 @type root_interface: str
44 @param arch: the desired target architecture
45 @type arch: L{arch.Architecture}
46 @return: whether we have a viable selection
47 @rtype: bool
48 @postcondition: self.selections and self.feeds_used are updated"""
49 raise NotImplementedError("Abstract")
51 class DefaultSolver(Solver):
52 def __init__(self, network_use, iface_cache, stores, root_restrictions = None):
53 """
54 @param network_use: how much use to make of the network
55 @type network_use: L{model.network_levels}
56 @param iface_cache: a cache of feeds containing information about available versions
57 @type iface_cache: L{iface_cache.IfaceCache}
58 @param stores: a cached of implementations (affects choice when offline or when minimising network use)
59 @type stores: L{zerostore.Stores}
60 @param root_restrictions: list of extra restrictions for the root interface
61 @type root_restrictions: [L{model.Restriction}]
62 """
63 Solver.__init__(self)
64 self.network_use = network_use
65 self.iface_cache = iface_cache
66 self.stores = stores
67 self.help_with_testing = False
68 self.root_restrictions = root_restrictions or []
70 def solve(self, root_interface, arch):
71 self.selections = {}
72 self.feeds_used = set()
73 self.details = self.record_details and {}
75 restrictions = {}
76 debug("Solve! root = %s", root_interface)
77 def process(dep, arch):
78 ready = True
79 iface = self.iface_cache.get_interface(dep.interface)
81 if iface in self.selections:
82 debug("Interface requested twice; skipping second %s", iface)
83 if dep.restrictions:
84 warn("Interface requested twice; I've already chosen an implementation "
85 "of '%s' but there are more restrictions! Ignoring the second set.", iface)
86 return
87 self.selections[iface] = None # Avoid cycles
89 assert iface not in restrictions
90 restrictions[iface] = dep.restrictions
92 impl = get_best_implementation(iface, arch)
93 if impl:
94 debug("Will use implementation %s (version %s)", impl, impl.get_version())
95 self.selections[iface] = impl
96 for d in impl.requires:
97 debug("Considering dependency %s", d)
98 if not process(d, arch.child_arch):
99 ready = False
100 else:
101 debug("No implementation chould be chosen yet");
102 ready = False
103 return ready
105 def get_best_implementation(iface, arch):
106 debug("get_best_implementation(%s), with feeds: %s", iface, iface.feeds)
108 impls = []
109 for f in usable_feeds(iface, arch):
110 self.feeds_used.add(f)
111 debug("Processing feed %s", f)
113 try:
114 feed = self.iface_cache.get_interface(f)._main_feed
115 if not feed.last_modified: continue # DummyFeed
116 if feed.name and iface.uri != feed.url and iface.uri not in feed.feed_for:
117 warn("Missing <feed-for> for '%s' in '%s'", iface.uri, f)
119 if feed.implementations:
120 impls.extend(feed.implementations.values())
121 except Exception, ex:
122 warn("Failed to load feed %s for %s: %s", f, iface, str(ex))
124 if not impls:
125 info("Interface %s has no implementations!", iface)
126 return None
128 if self.record_details:
129 # In details mode, rank all the implementations and then choose the best
130 impls.sort(lambda a, b: compare(iface, a, b, arch))
131 best = impls[0]
132 self.details[iface] = [(impl, get_unusable_reason(impl, restrictions.get(iface, []), arch)) for impl in impls]
133 else:
134 # Otherwise, just choose the best without sorting
135 best = impls[0]
136 for x in impls[1:]:
137 if compare(iface, x, best, arch) < 0:
138 best = x
139 unusable = get_unusable_reason(best, restrictions.get(iface, []), arch)
140 if unusable:
141 info("Best implementation of %s is %s, but unusable (%s)", iface, best, unusable)
142 return None
143 return best
145 def compare(interface, b, a, arch):
146 """Compare a and b to see which would be chosen first.
147 @param interface: The interface we are trying to resolve, which may
148 not be the interface of a or b if they are from feeds.
149 @rtype: int"""
150 iface_restrictions = restrictions.get(interface, [])
152 a_stab = a.get_stability()
153 b_stab = b.get_stability()
155 # Usable ones come first
156 r = cmp(is_unusable(b, iface_restrictions, arch), is_unusable(a, iface_restrictions, arch))
157 if r: return r
159 # Preferred versions come first
160 r = cmp(a_stab == model.preferred, b_stab == model.preferred)
161 if r: return r
163 if self.network_use != model.network_full:
164 r = cmp(get_cached(a), get_cached(b))
165 if r: return r
167 # Stability
168 stab_policy = interface.stability_policy
169 if not stab_policy:
170 if self.help_with_testing: stab_policy = model.testing
171 else: stab_policy = model.stable
173 if a_stab >= stab_policy: a_stab = model.preferred
174 if b_stab >= stab_policy: b_stab = model.preferred
176 r = cmp(a_stab, b_stab)
177 if r: return r
179 # Newer versions come before older ones
180 r = cmp(a.version, b.version)
181 if r: return r
183 # Get best OS
184 r = cmp(arch.os_ranks.get(a.os, None),
185 arch.os_ranks.get(b.os, None))
186 if r: return r
188 # Get best machine
189 r = cmp(arch.machine_ranks.get(a.machine, None),
190 arch.machine_ranks.get(b.machine, None))
191 if r: return r
193 # Slightly prefer cached versions
194 if self.network_use == model.network_full:
195 r = cmp(get_cached(a), get_cached(b))
196 if r: return r
198 return cmp(a.id, b.id)
200 def usable_feeds(iface, arch):
201 """Return all feeds for iface that support arch.
202 @rtype: generator(ZeroInstallFeed)"""
203 yield iface.uri
205 for f in iface.feeds:
206 if f.os in arch.os_ranks and f.machine in arch.machine_ranks:
207 yield f.uri
208 else:
209 debug("Skipping '%s'; unsupported architecture %s-%s",
210 f, f.os, f.machine)
212 def is_unusable(impl, restrictions, arch):
213 """@return: whether this implementation is unusable.
214 @rtype: bool"""
215 return get_unusable_reason(impl, restrictions, arch) != None
217 def get_unusable_reason(impl, restrictions, arch):
219 @param impl: Implementation to test.
220 @type restrictions: [L{model.Restriction}]
221 @return: The reason why this impl is unusable, or None if it's OK.
222 @rtype: str
223 @note: The restrictions are for the interface being requested, not the interface
224 of the implementation; they may be different when feeds are being used."""
225 for r in restrictions:
226 if not r.meets_restriction(impl):
227 return "Incompatible with another selected implementation"
228 stability = impl.get_stability()
229 if stability <= model.buggy:
230 return stability.name
231 if self.network_use == model.network_offline and not get_cached(impl):
232 return "Not cached and we are off-line"
233 if impl.os not in arch.os_ranks:
234 return "Unsupported OS"
235 # When looking for source code, we need to known if we're
236 # looking at an implementation of the root interface, even if
237 # it's from a feed, hence the sneaky restrictions identity check.
238 if impl.machine not in arch.machine_ranks:
239 if impl.machine == 'src':
240 return "Source code"
241 return "Unsupported machine type"
242 return None
244 def get_cached(impl):
245 """Check whether an implementation is available locally.
246 @type impl: model.Implementation
247 @rtype: bool
249 if isinstance(impl, model.DistributionImplementation):
250 return impl.installed
251 if impl.id.startswith('/'):
252 return os.path.exists(impl.id)
253 else:
254 try:
255 path = self.stores.lookup(impl.id)
256 assert path
257 return True
258 except BadDigest:
259 return False
260 except NotStored:
261 return False
263 return process(model.InterfaceDependency(root_interface, restrictions = self.root_restrictions), arch)