/usr/sbin/bcfg2-yum-helper is in bcfg2-server 1.2.2-2.
This file is owned by root:root, with mode 0o755.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 | #!/usr/bin/python
""" Helper script for the Packages plugin, used if yum library support
is enabled. The yum libs have horrific memory leaks, so apparently
the right way to get around that in long-running processes it to have
a short-lived helper. No, seriously -- check out the yum-updatesd
code. It's pure madness. """
__revision__ = '$Revision$'
import os
import sys
import yum
import logging
import Bcfg2.Logger
from optparse import OptionParser, OptionError
try:
import json
except ImportError:
import simplejson as json
LOGGER = None
def get_logger(verbose=0):
""" set up logging according to the verbose level given on the
command line """
global LOGGER
if LOGGER is None:
LOGGER = logging.getLogger(sys.argv[0])
stderr = logging.StreamHandler()
if verbose:
level = logging.DEBUG
else:
level = logging.WARNING
LOGGER.setLevel(level)
LOGGER.addHandler(stderr)
syslog = logging.handlers.SysLogHandler("/dev/log")
syslog.setFormatter(logging.Formatter("%(name)s: %(message)s"))
LOGGER.addHandler(syslog)
return LOGGER
class DepSolver(object):
def __init__(self, cfgfile, verbose=1):
self.cfgfile = cfgfile
self.yumbase = yum.YumBase()
try:
self.yumbase.preconf.debuglevel = verbose
self.yumbase.preconf.fn = cfgfile
self.yumbase._getConfig()
except AttributeError:
self.yumbase._getConfig(cfgfile, debuglevel=verbose)
self.logger = get_logger(verbose)
def get_groups(self):
try:
return self._groups
except AttributeError:
return ["noarch"]
def set_groups(self, groups):
self._groups = set(groups).union(["noarch"])
groups = property(get_groups, set_groups)
def is_package(self, package):
if isinstance(package, tuple):
if package[1] is None and package[2] == (None, None, None):
package = package[0]
else:
return None
return bool(self.get_package_object(package, silent=True))
def is_virtual_package(self, package):
return bool(self.get_provides(package, silent=True))
def get_package_object(self, package, silent=False):
try:
matches = self.yumbase.pkgSack.returnNewestByName(name=package)
except yum.Errors.PackageSackError:
if not silent:
self.logger.warning("Package '%s' not found" %
self.get_package_name(package))
matches = []
except yum.Errors.RepoError:
err = sys.exc_info()[1]
self.logger.error("Temporary failure loading metadata for %s: %s" %
(self.get_package_name(package), err))
matches = []
pkgs = self._filter_arch(matches)
if pkgs:
return pkgs[0]
else:
return None
def get_deps(self, package):
pkg = self.get_package_object(package)
deps = []
if pkg:
deps = set(pkg.requires)
# filter out things the package itself provides
deps.difference_update([dep for dep in deps
if pkg.checkPrco('provides', dep)])
else:
self.logger.error("No package available: %s" %
self.get_package_name(package))
return deps
def get_provides(self, required, all=False, silent=False):
if not isinstance(required, tuple):
required = (required, None, (None, None, None))
try:
prov = \
self.yumbase.whatProvides(*required).returnNewestByNameArch()
except yum.Errors.NoMoreMirrorsRepoError:
err = sys.exc_info()[1]
self.logger.error("Temporary failure loading metadata for %s: %s" %
(self.get_package_name(required), err))
return []
if prov and not all:
prov = self._filter_provides(required, prov)
elif not prov and not silent:
self.logger.error("No package provides %s" %
self.get_package_name(required))
return prov
def get_group(self, group, ptype="default"):
if group.startswith("@"):
group = group[1:]
try:
if self.yumbase.comps.has_group(group):
group = self.yumbase.comps.return_group(group)
else:
self.logger.warning("%s is not a valid group" % group)
return []
except yum.Errors.GroupsError:
err = sys.exc_info()[1]
self.logger.warning(err)
return []
if ptype == "default":
return [p
for p, d in list(group.default_packages.items())
if d]
elif ptype == "mandatory":
return [p
for p, m in list(group.mandatory_packages.items())
if m]
elif ptype == "optional" or ptype == "all":
return group.packages
else:
self.logger.warning("Unknown group package type '%s'" % ptype)
return []
def _filter_provides(self, package, providers):
providers = [pkg for pkg in self._filter_arch(providers)]
if len(providers) > 1:
# go through each provider and make sure it's the newest
# package of its name available. If we have multiple
# providers, avoid installing old packages.
#
# For instance: on Fedora 14,
# perl-Sub-WrapPackages-2.0-2.fc14 erroneously provided
# perl(lib), which should not have been provided;
# perl(lib) is provided by the "perl" package. The bogus
# provide was removed in perl-Sub-WrapPackages-2.0-4.fc14,
# but if we just queried to resolve the "perl(lib)"
# dependency, we'd get both packages. By performing this
# check, we learn that there's a newer
# perl-Sub-WrapPackages available, so it can't be the best
# provider of perl(lib).
rv = []
for pkg in providers:
found = self.get_package_object(pkg.name)
if found == pkg or found.pkgtup == pkg.pkgtup:
rv.append(pkg)
else:
self.logger.debug("Skipping %s, not newest (%s)" %
(pkg, found))
else:
rv = providers
return [p.name for p in rv]
def _filter_arch(self, packages):
matching = []
for pkg in packages:
if pkg.arch in self.groups:
matching.append(pkg)
else:
self.logger.debug("%s has non-matching architecture (%s)" %
(pkg, pkg.arch))
if matching:
return matching
else:
# no packages match architecture; we'll assume that the
# user knows what s/he is doing and this is a multiarch
# box.
return packages
def get_package_name(self, package):
""" get the name of a package or virtual package from the
internal representation used by this Collection class """
if isinstance(package, tuple):
return yum.misc.prco_tuple_to_string(package)
else:
return str(package)
def complete(self, packagelist):
packages = set()
pkgs = set(packagelist)
requires = set()
satisfied = set()
unknown = set()
final_pass = False
while requires or pkgs:
# infinite loop protection
start_reqs = len(requires)
while pkgs:
package = pkgs.pop()
if package in packages:
continue
if not self.is_package(package):
# try this package out as a requirement
self.logger.debug("Adding requirement %s" % package)
requires.add((package, None, (None, None, None)))
continue
packages.add(package)
reqs = set(self.get_deps(package)).difference(satisfied)
if reqs:
self.logger.debug("Adding requirements for %s: %s" %
(package,
",".join([self.get_package_name(r)
for r in reqs])))
requires.update(reqs)
reqs_satisfied = set()
for req in requires:
if req in satisfied:
reqs_satisfied.add(req)
continue
if req[1] is None and self.is_package(req[0]):
if req[0] not in packages:
pkgs.add(req[0])
reqs_satisfied.add(req)
continue
self.logger.debug("Handling requirement '%s'" %
self.get_package_name(req))
providers = list(set(self.get_provides(req)))
if len(providers) > 1:
# hopefully one of the providing packages is already
# included
best = [p for p in providers if p in packages]
if best:
providers = best
else:
# pick a provider whose name matches the requirement
best = [p for p in providers if p == req[0]]
if len(best) == 1:
providers = best
elif not final_pass:
self.logger.debug("%s has multiple providers: %s" %
(self.get_package_name(req),
providers))
self.logger.debug("No provider is obviously the "
"best; deferring")
providers = None
else:
# found no "best" package, but it's the
# final pass, so include them all
self.logger.debug("Found multiple providers for %s,"
"including all" %
self.get_package_name(req))
if providers:
self.logger.debug("Requirement '%s' satisfied by %s" %
(self.get_package_name(req),
",".join([self.get_package_name(p)
for p in providers])))
newpkgs = set(providers).difference(packages)
if newpkgs:
for package in newpkgs:
if self.is_package(package):
pkgs.add(package)
else:
unknown.add(package)
reqs_satisfied.add(req)
elif providers is not None:
# nothing provided this requirement at all
self.logger.debug("Nothing provides %s" %
self.get_package_name(req))
unknown.add(req)
reqs_satisfied.add(req)
# else, defer
requires.difference_update(reqs_satisfied)
# infinite loop protection
if len(requires) == start_reqs and len(pkgs) == 0:
final_pass = True
if final_pass and requires:
unknown.update(requires)
requires = set()
unknown = [self.get_package_name(p) for p in unknown]
return packages, unknown
def clean_cache(self):
for mdtype in ["Headers", "Packages", "Sqlite", "Metadata",
"ExpireCache"]:
# for reasons that are entirely obvious, all of the yum
# API clean* methods return a tuple of 0 (zero, always
# zero) and a list containing a single message about how
# many files were deleted. so useful. thanks, yum.
msg = getattr(self.yumbase, "clean%s" % mdtype)()[1][0]
if not msg.startswith("0 "):
self.logger.info(msg)
def main():
parser = OptionParser()
parser.add_option("-c", "--config", help="Config file")
parser.add_option("-v", "--verbose", help="Verbosity level", action="count")
(options, args) = parser.parse_args()
logger = get_logger(options.verbose)
try:
cmd = args[0]
except IndexError:
logger.error("No command given")
return 1
if not os.path.exists(options.config):
logger.error("Config file %s not found" % options.config)
return 1
depsolver = DepSolver(options.config, options.verbose)
if cmd == "clean":
depsolver.clean_cache()
print json.dumps(True)
elif cmd == "complete":
data = json.loads(sys.stdin.read())
depsolver.groups = data['groups']
(packages, unknown) = depsolver.complete(data['packages'])
print json.dumps(dict(packages=list(packages),
unknown=list(unknown)))
elif cmd == "is_virtual_package":
package = json.loads(sys.stdin.read())
print json.dumps(bool(depsolver.get_provides(package, silent=True)))
elif cmd == "get_deps" or cmd == "get_provides":
package = json.loads(sys.stdin.read())
print json.dumps(list(getattr(depsolver, cmd)(package)))
elif cmd == "get_group":
data = json.loads(sys.stdin.read())
if "type" in data:
packages = depsolver.get_group(data['group'], ptype=data['type'])
else:
packages = depsolver.get_group(data['group'])
print json.dumps(list(packages))
elif cmd == "is_package":
package = json.loads(sys.stdin.read())
print json.dumps(getattr(depsolver, cmd)(package))
if __name__ == '__main__':
sys.exit(main())
|