class InventoryCommand(ftcommands.YumCommand): decorate(traceLog()) def getModes(self): return ['inventory'] decorate(traceLog()) def addSubOptions(self, base, mode, cmdline, processedArgs): base.optparser.add_option("--show-unknown", help="Show unknown devices.", action="store_true", dest="show_unknown", default=False) decorate(traceLog()) def doCommand(self, base, mode, cmdline, processedArgs): sys.stderr.write("Wait while we inventory system:\n") headerWasPrinted = False for pkg in base.yieldInventory(cb=cli.mycb({})): if not headerWasPrinted: sys.stderr.write(firmwaretools.pycompat.clearLine()) sys.stderr.write("System inventory:\n") sys.stderr.flush() headerWasPrinted = True if pkg.version == "unknown" and not base.opts.show_unknown: continue print("\t%s = %s" % (str(pkg), pkg.version)) return [0, "Done"]
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]
class MockPackage2(package.RepositoryPackage): decorate(traceLog()) def __init__(self, *args, **kargs): super(MockPackage2, self).__init__(*args, **kargs) decorate(traceLog()) def install(self): self.status = "in_progress" self.status = "success" return "SUCCESS"
class ListPluginsCommand(ftcommands.YumCommand): decorate(traceLog()) def getModes(self): return ['listplugins'] decorate(traceLog()) def doCommand(self, base, mode, cmdline, processedArgs): print("Available Plugins:") for p in base.listPluginsFromIni(): print("\t%s" % p) print("Loaded Plugins:") for p in base.plugins.listLoaded(): print("\t%s" % p) return [0, "Done"]
class BackgroundWorker(threading.Thread): def __init__(self, function, args=None, kargs=None): threading.Thread.__init__(self) self.function = function self.args = args self.kargs = kargs self.exception = None self.returnCode = None self.running = 1 if self.args is None: self.args = [] if self.kargs is None: self.kargs = {} self.start() decorate(traceLog()) def run(self): try: self.returnCode = self.function(*self.args, **self.kargs) except (Exception, ), e: self.exception = e self.running = 0
class MockRepositoryPackage(package.RepositoryPackage): decorate(traceLog()) def __init__(self, *args, **kargs): super(MockRepositoryPackage, self).__init__(*args, **kargs) self.capabilities['can_downgrade'] = True self.capabilities['can_reflash'] = True self.capabilities['accurate_update_percentage'] = True self.uniqueInstance = self.name decorate(traceLog()) def install(self): self.status = "in_progress" for i in xrange(100): self.progressPct = i / 100.0 time.sleep(0.01) #print "MockRepositoryPackage -> Install pkg(%s) version(%s)" % (str(self), self.version) self.progressPct = 1 self.status = "success"
def main(args): """This does all the real work""" def setDebug(): import pdb pdb.set_trace() signal.signal(signal.SIGUSR1, setDebug) def exUserCancel(): logger.critical('Exiting on user cancel') sys.exit(1) decorate(traceLog()) def exIOError(e): if e.errno == 32: logger.critical('Exiting on Broken Pipe') else: logger.critical(str(e)) sys.exit(1) decorate(traceLog()) def exPluginExit(e): '''Called when a plugin raises PluginExit. Log the plugin's exit message if one was supplied. ''' if str(e): logger.warn('%s' % e) sys.exit(1) decorate(traceLog()) def exFatal(e): logger.critical('%s' % e) sys.exit(1) try: locale.setlocale(locale.LC_ALL, '') except locale.Error, e: # default to C locale if we get a failure. print >> sys.stderr, 'Failed to set locale, defaulting to C' locale.setlocale(locale.LC_ALL, 'C')
class BootstrapCommand(ftcommands.YumCommand): decorate(traceLog()) def getModes(self): return ['bootstrap'] decorate(traceLog()) def addSubOptions(self, base, mode, cmdline, processedArgs): # need to add bootstrap-specific options to optparser base.optparser.add_option( "-u", "--up2date_mode", action="store_true", dest="comma_separated", default=False, help="Comma-separate values for use with up2date.") base.optparser.add_option( "-a", "--apt_mode", action="store_true", dest="apt_mode", default=False, help="fixup names so that they are compatible with apt") decorate(traceLog()) def doCommand(self, base, mode, cmdline, processedArgs): parse = str if base.opts.apt_mode: parse = debianCleanName venId, sysId = base.getSystemId() out = "" for pkg in base.yieldInventory(): if base.opts.comma_separated: if venId and sysId: out = out + ",%s" % parse( pkg.name + "/system(ven_0x%04x_dev_0x%04x)" % (venId, sysId)) out = out + ",%s" % parse(pkg.name) try: if venId and sysId: out = out + ",%s" % parse( pkg.shortname + "/system(ven_0x%04x_dev_0x%04x)" % (venId, sysId)) out = out + ",%s" % parse(pkg.shortname) except AttributeError: pass else: if venId and sysId: print("%s/system(ven_0x%04x_dev_0x%04x)" % (parse(pkg.name), venId, sysId)) print("%s" % parse(pkg.name)) try: if venId and sysId: print("%s/system(ven_0x%04x_dev_0x%04x)" % (parse(pkg.shortname), venId, sysId)) print("%s" % parse(pkg.shortname)) except AttributeError: pass # strip leading comma: out = out[1:] if out: print(out) return [0, "Done"]
if venId and sysId: print("%s/system(ven_0x%04x_dev_0x%04x)" % (parse(pkg.name), venId, sysId)) print("%s" % parse(pkg.name)) try: if venId and sysId: print("%s/system(ven_0x%04x_dev_0x%04x)" % (parse(pkg.shortname), venId, sysId)) print("%s" % parse(pkg.shortname)) except AttributeError: pass # strip leading comma: out = out[1:] if out: print(out) return [0, "Done"] # used by bootstrap decorate(traceLog()) def debianCleanName(s): s = s.replace('_', '-') s = s.replace('(', '-') s = s.replace(')', '') s = s.lower() return s
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): unionInventory = {} for deviceUniqueInstance, details in self.deviceList.items(): unionInventory[deviceUniqueInstance] = details["device"] for pkg in self.deviceList[device.uniqueInstance]["available_updates"]: if self.checkRules(device, pkg, unionInventory, runSoftRules=False, cb=None): 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
# required by the Firmware-Tools plugin API __VERSION__ = firmwaretools.__VERSION__ plugin_type = (plugins.TYPE_CORE,) requires_api_version = "2.0" # end: api reqs moduleLog = getLog() conf = None wineprefix = None dosprefix = None class noHdrs(fte.DebugExc): pass # this is called from doCheck in buildrpm_cmd and should register any spec files # and hooks this module supports decorate(traceLog()) def buildrpm_doCheck_hook(conduit, *args, **kargs): global conf conf = checkConf_buildrpm(conduit.getConf(), conduit.getBase().opts) br.specMapping["BiosPackage"] = {"spec": conf.biospackagespec, "ini_hook": buildrpm_ini_hook} # this is called by the buildrpm_doCheck_hook and should ensure that all config # options have reasonable default values and that config file values are # properly overridden by cmdline options, where applicable. decorate(traceLog()) def checkConf_buildrpm(conf, opts): if getattr(conf, "biospackagespec", None) is None: conf.biospackagespec = None return conf # this hook is called during the RPM build process. It should munge the ini
class DepParser(object): tokens = ( 'ID', 'LT', 'LE', 'EQ', 'GE', 'GT', 'COMMA' ) t_ID = r'[\w()]+' t_LT = r'<' t_LE = r'<=' t_EQ = r'==' t_GE = r'>=' t_GT = r'>' t_COMMA = r',' t_ignore = " \t" def t_error(self, t): print "Illegal character '%s'" % t.value[0] t.skip(1) decorate(traceLog()) def __init__(self, string, inventory, fullInventory, *args, **kargs): self.inventory = inventory self.fullInventory = fullInventory self.depPass = 1 import ply_lex lexer = ply_lex.lex( module=self ) import ply_yacc parser = ply_yacc.yacc( module=self, write_tables=0, debug=0 ) parser.parse(string, lexer=lexer, debug=0) precedence = ( ('left', 'COMMA'), ) def p_error(self, t): print "Syntax error at '%s'" % t def p_stmt(self, t): # statement_list can be 1) empty, 2) single statement, or 3) list """statement_list : | statement | statement_list COMMA statement statement : dep""" pass def p_package_depencency(self, t): """dep : ID LT ID | ID LE ID | ID EQ ID | ID GE ID | ID GT ID """ op = t[2] reqPkg = package.Package (name=t[1], version=t[3], displayname="virtual package") pkg = self.inventory.get(t[1]) if pkg: r = pkg.compareVersion(reqPkg) evalStr = "%s %s 0" % (r, op) if not eval(evalStr): self.reason = "Failed for rule: requires %s %s %s" % (t[1], t[2], t[3]) self.depPass = 0 else: self.reason = "Repository package doesn't exist in system inventory." self.depPass = 0 def p_package_exists(self, t): """dep : ID""" if not self.inventory.get(t[1]): self.reason = "Failed for rule: requires %s" % t[1] self.depPass = 0