/usr/share/pyshared/firmwaretools/repository.py is in firmware-tools-common 2.1.14-0ubuntu1.
This file is owned by root:root, with mode 0o644.
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 | # vim:expandtab:autoindent:tabstop=4:shiftwidth=4:filetype=python:tw=0
#############################################################################
#
# Copyright (c) 2005 Dell Computer Corporation
# Dual Licenced under GNU GPL and OSL
#
#############################################################################
"""
repository module
"""
from __future__ import generators
import os
import ConfigParser
import package
import pycompat
import dep_parser
import sys
import traceback
import firmwaretools as ft
from firmwaretools.trace_decorator import decorate, traceLog, getLog
import logging
moduleLog = getLog()
moduleVerboseLog = getLog(prefix="verbose.")
class CircularDependencyError(Exception): pass
# TODO:
# -- conf item should NEVER be used outside of constructor (makePackage)
decorate(traceLog())
def makePackage(configFile):
conf = ConfigParser.ConfigParser()
conf.read(configFile)
# make a standard package
displayname = "unknown"
if conf.has_option("package", "displayname"):
displayname = conf.get("package", "displayname")
type = package.RepositoryPackage
try:
pymod = conf.get("package","module")
moduleLog.debug("pymod: %s" % pymod)
module = __import__(pymod, globals(), locals(), [])
for i in pymod.split(".")[1:]:
module = getattr(module, i)
packageTypeClass = conf.get("package", "type")
type = getattr(module, packageTypeClass)
moduleLog.debug("direct instantiate")
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError, ImportError, AttributeError):
moduleLog.debug(''.join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)))
pass
p = type(
displayname=displayname,
name=conf.get("package", "name"),
version=conf.get("package", "version"),
conf=conf,
path=os.path.dirname(configFile),
)
return p
class SystemInventory(object):
decorate(traceLog())
def __init__(self, *args, **kargs):
self.deviceList = {}
self.allowDowngrade=False
self.allowReflash=False
decorate(traceLog())
def addDevice(self, device):
self.deviceList[device.uniqueInstance] = { "device": device, "update": None, "available_updates": []}
decorate(traceLog())
def getDevice(self, uniqueInstance, default=None):
return self.deviceList.get(uniqueInstance, default)
decorate(traceLog())
def iterDevices(self, name=None):
for device, details in self.deviceList.items():
if name is None:
yield details["device"]
else:
if details["device"].name == name:
yield details["device"]
else:
try:
if details["device"].shortname == name:
yield details["device"]
except AttributeError:
pass
decorate(traceLog())
def addAvailablePackage(self, package):
for myDev in self.iterDevices(name=package.name):
available_updates = self.deviceList[myDev.uniqueInstance]["available_updates"]
available_updates.append(package)
self.deviceList[myDev.uniqueInstance]["available_updates"] = available_updates
package.attachToDevice(myDev)
decorate(traceLog())
def iterAvailableUpdates(self, device):
for pkg in self.deviceList[device.uniqueInstance]["available_updates"]:
yield pkg
decorate(traceLog())
def getSuggestedUpdatePackageForDevice(self, device):
ret = None
if self.deviceList.has_key(device.uniqueInstance):
ret = self.deviceList[device.uniqueInstance]["update"]
return ret
decorate(traceLog())
def getUpdatePackageForDevice(self, device):
ret = None
if self.deviceList.has_key(device.uniqueInstance):
if self.deviceList[device.uniqueInstance].has_key("pinned_update"):
ret = self.deviceList[device.uniqueInstance]["pinned_update"]
else:
ret = self.deviceList[device.uniqueInstance]["update"]
return ret
decorate(traceLog())
def pinUpdatePackage(self, device, pkg):
#TODO: ensure that pkg is in 'available_pkgs'
hasOldPin = False
if self.deviceList[device.uniqueInstance].has_key("pinned_update"):
hasOldPin = True
oldPin = self.deviceList[device.uniqueInstance]["pinned_update"]
self.deviceList[device.uniqueInstance]["pinned_update"] = pkg
# just check the rules... not actually installing
try:
for i in self.generateInstallationOrder(): pass
except CircularDependencyError, e:
# roll back
if hasOldPin:
self.deviceList[device.uniqueInstance]["pinned_update"] = oldPin
else:
del(self.deviceList[device.uniqueInstance]["pinned_update"])
raise
decorate(traceLog())
def unPinDevice(self, device):
if self.deviceList[device.uniqueInstance].has_key("pinned_update"):
del(self.deviceList[device.uniqueInstance]["pinned_update"])
decorate(traceLog())
def reset(self):
for device in self.iterDevices():
self.unPinDevice(device)
decorate(traceLog())
def getMemento(self, deviceHint=None):
memento = {}
memento['savePin'] = {}
for deviceUniqueInstance, details in self.deviceList.items():
if deviceHint:
if deviceHint.uniqueInstance != deviceUniqueInstance:
continue
if details.has_key("pinned_update"):
memento['savePin'][deviceUniqueInstance] = { 'device': details["device"], 'hasPin': 1, 'oldPin': details["pinned_update"] }
else:
memento['savePin'][deviceUniqueInstance] = { 'device': details["device"], 'hasPin': 0, 'oldPin': None }
memento["internal.allowReflash"] = self.allowReflash
memento["internal.allowDowngrade"] = self.allowDowngrade
return memento
decorate(traceLog())
def setMemento(self, memento):
self.allowReflash = memento["internal.allowReflash"]
self.allowDowngrade = memento["internal.allowDowngrade"]
for deviceUniqueInstance, details in memento['savePin'].items():
if details['hasPin']:
self.pinUpdatePackage(details["device"], details["oldPin"])
else:
self.unPinDevice(details["device"])
decorate(traceLog())
def setAllowDowngrade(self, val):
self.allowDowngrade = val
decorate(traceLog())
def getAllowDowngrade(self):
return self.allowDowngrade
decorate(traceLog())
def setAllowReflash(self, val):
self.allowReflash = val
decorate(traceLog())
def getAllowReflash(self):
return self.allowReflash
decorate(traceLog())
def checkRules(self, device, candidate, unionInventory, cb=None):
# is candidate newer than what is installed
if not self.allowDowngrade and device.compareVersion(candidate) > 0:
ft.callCB(cb, who="checkRules", what="package_not_newer", package=candidate, device=device)
return 0
# is candidate newer than what is installed
if not self.allowReflash and device.compareVersion(candidate) == 0:
ft.callCB(cb, who="checkRules", what="package_same_version", package=candidate, device=device)
return 0
#check to see if this package has specific system requirements
# for now, check if we are on a specific system by checking for
# a BIOS package w/ matching id. In future, may have specific
# system package.
if hasattr(candidate,"conf") and candidate.conf.has_option("package", "limit_system_support"):
systemVenDev = candidate.conf.get("package", "limit_system_support")
if not unionInventory.get( "system_bios(%s)" % systemVenDev ):
ft.callCB(cb, who="checkRules", what="fail_limit_system_check", package=candidate)
return 0
#check generic dependencies
if hasattr(candidate,"conf") and candidate.conf.has_option("package", "requires"):
requires = candidate.conf.get("package", "requires")
if len(requires):
d = dep_parser.DepParser(requires, unionInventory, self.deviceList)
if not d.depPass:
ft.callCB(cb, who="checkRules", what="fail_dependency_check", package=candidate, reason=d.reason)
return 0
return 1
decorate(traceLog())
def calculateUpgradeList(self, cb=None):
unionInventory = {}
for deviceUniqueInstance, details in self.deviceList.items():
unionInventory[deviceUniqueInstance] = details["device"]
# for every device, look at the available updates to see if one can be applied.
# if we do any work, start over so that dependencies work themselves out over multiple iterations.
workToDo = 1
while workToDo:
workToDo = 0
for deviceUniqueInstance, details in self.deviceList.items():
for candidate in details["available_updates"]:
# check if this package is better than the current best
if unionInventory[deviceUniqueInstance].compareVersion(candidate) >= 0:
continue
if self.checkRules(details["device"], candidate, unionInventory, cb=cb):
self.deviceList[deviceUniqueInstance]["update"] = candidate
# update union inventory
unionInventory[deviceUniqueInstance] = candidate
# need another run-through in case this fixes deps for another package
workToDo = 1
decorate(traceLog())
def generateInstallationOrder(self, returnDeviceToo=0, cb=None):
unionInventory = {}
for deviceUniqueInstance, details in self.deviceList.items():
unionInventory[deviceUniqueInstance] = details["device"]
# generate initial union inventory
# we will start with no update packages and add them in one at a time
# as we install them
updateDeviceList = [] # [ pkg, pkg, pkg ]
for pkgName, details in self.deviceList.items():
update = self.getUpdatePackageForDevice(details["device"])
if update:
updateDeviceList.append( (details["device"], update) )
workToDo = 1
while workToDo:
workToDo = 0
for device, candidate in updateDeviceList:
if self.checkRules(device, candidate, unionInventory, cb=cb):
candidate.setCurrentInstallDevice(device)
if returnDeviceToo:
yield (device, candidate)
else:
yield candidate
# move pkg from to-install list to inventory list
updateDeviceList.remove((device,candidate))
unionInventory[device.uniqueInstance] = candidate
# need another run-through in case this fixes deps for another package
workToDo = 1
if len(updateDeviceList):
raise CircularDependencyError("packages have circular dependency, or are otherwise uninstallable.")
class Repository(object):
decorate(traceLog())
def __init__(self, *args):
self.dirList = []
for i in args:
self.dirList.append(i)
decorate(traceLog())
def iterPackages(self, cb=None):
for dir in self.dirList:
try:
for (path, dirs, files) in pycompat.walkPath(dir):
if "package.ini" in files:
ft.callCB(cb, who="iterPackages", what="found_package_ini", path=os.path.join(path, "package.ini" ))
try:
p = makePackage( os.path.join(path, "package.ini" ))
ft.callCB(cb, who="iterPackages", what="made_package", package=p)
yield p
except:
moduleLog.debug(''.join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)))
pass
except OSError: # directory doesnt exist, so no repo packages. :-)
pass
decorate(traceLog())
def iterLatestPackages(self, cb=None):
latest = {}
for candidate in self.iterPackages(cb=cb):
pkgName = candidate.name
if candidate.conf.has_option("package", "limit_system_support"):
pkgName = pkgName + "_" + candidate.conf.get("package", "limit_system_support")
p = latest.get(pkgName)
if not p:
latest[pkgName] = candidate
elif p.compareVersion(candidate) < 0:
latest[pkgName] = candidate
ft.callCB(cb, who="iterLatestPackages", what="done_generating_list")
keys = latest.keys()
keys.sort()
for package in keys:
ft.callCB(cb, who="iterLatestPackages", what="made_package", package=latest[package])
yield latest[package]
|