Exemplo n.º 1
0
class _TokenTable(ctypes.Structure):
    _instance = None
    decorate(traceLog())

    def __init__(self, *args):
        self._tableobj = None
        self._tableobj = DLL.token_table_factory(*args)

    def __del__(self):
        if self._tableobj is not None:
            DLL.token_table_free(self._tableobj)

    decorate(traceLog())

    def __iter__(self):
        cur = ctypes.POINTER(Token)()
        while 1:
            cur = DLL.token_table_get_next(self._tableobj, cur)
            if bool(cur):
                yield cur.contents
            else:
                raise exceptions.StopIteration(_("hit end of table."))

    decorate(traceLog())

    def __getitem__(self, id):
        if id is None:
            raise exceptions.IndexError(_("Cannot dereference NULL ID"))
        cur = ctypes.POINTER(Token)()
        cur = DLL.token_table_get_next_by_id(self._tableobj, cur, id)
        if bool(cur):
            return cur.contents
        else:
            raise exceptions.IndexError(_("ID 0x%04x not found") % id)
Exemplo n.º 2
0
class _SmbiosTable(ctypes.Structure):
    _instance = None

    decorate(traceLog())

    def __init__(self, *args):
        self._tableobj = None
        self._tableobj = DLL.smbios_table_factory(*args)

    def __del__(self):
        if self._tableobj is not None:
            DLL.smbios_table_free(self._tableobj)

    decorate(traceLog())

    def __iter__(self):
        cur = ctypes.POINTER(SmbiosStructure)()
        while 1:
            cur = DLL.smbios_table_get_next_struct(self._tableobj, cur)
            if bool(cur):
                yield cur.contents
            else:
                raise exceptions.StopIteration(_("hit end of table."))

    decorate(traceLog())

    def iterByType(self, t):
        cur = ctypes.POINTER(SmbiosStructure)()
        while 1:
            cur = DLL.smbios_table_get_next_struct(self._tableobj, cur)
            if bool(cur):
                if cur.contents.getType() == t:
                    yield cur.contents
            else:
                raise exceptions.StopIteration(_("hit end of table."))

    decorate(traceLog())

    def getStructureByHandle(self, handle):
        cur = ctypes.POINTER(SmbiosStructure)()
        cur = DLL.smbios_table_get_next_struct_by_handle(
            self._tableobj, cur, handle)
        if not bool(cur):
            raise exceptions.IndexError(
                _("No SMBIOS structure found with handle %s") % handle)
        return cur.contents

    decorate(traceLog())

    def getStructureByType(self, t):
        cur = ctypes.POINTER(SmbiosStructure)()
        cur = DLL.smbios_table_get_next_struct_by_type(self._tableobj, cur, t)
        if not bool(cur):
            raise exceptions.IndexError(
                _("No SMBIOS structure found with type %s") % t)
        return cur.contents

    __getitem__ = getStructureByType
Exemplo n.º 3
0
class DummyPlugins:
    '''
    This class provides basic emulation of the YumPlugins class. It exists so
    that calls to plugins.run() don't fail if plugins aren't in use.
    '''
    decorate(traceLog())

    def run(self, *args, **kwargs):
        pass

    decorate(traceLog())

    def setCmdLine(self, *args, **kwargs):
        pass
Exemplo n.º 4
0
def errorOnNegativeFN(exception_fn=None):
    decorate(traceLog())
    def _errorOnNegativeFN(result, func, args):
        getLog(prefix="trace.").info("RAN CTYPES FUNCTION: %s" % func.__name__)
        if result is None or result < 0:
            _doExc(exception_fn, result, func, args, _("function returned negative error code") )
        return result
    return _errorOnNegativeFN
Exemplo n.º 5
0
def errorOnZeroFN(exception_fn=None):
    decorate(traceLog())
    def _errorOnZeroFN(result, func, args):
        getLog(prefix="trace.").info("RAN CTYPES FUNCTION: %s" % func.__name__)
        if result is None or result == 0:
            _doExc(exception_fn, result, func, args, _("function returned error value of zero") )
        return result
    return _errorOnZeroFN
Exemplo n.º 6
0
def errorOnNullPtrFN(exception_fn=None):
    decorate(traceLog())
    def _errorOnNullPtrFN(result, func, args):
        getLog(prefix="trace.").info("RAN CTYPES FUNCTION: %s" % func.__name__)
        if not bool(result): # check for null pointer
            _doExc(exception_fn, result, func, args, _("null pointer returned") )
        return result
    return _errorOnNullPtrFN
Exemplo n.º 7
0
class _CmosAccess(ctypes.Structure):
    _instance = None

    decorate(traceLog())

    def __init__(self, *args):
        self._cmosobj = None
        self._cmosobj = DLL.cmos_obj_factory(*args)
        self._callbacks = []

    # dont decorate __del__
    def __del__(self):
        DLL.cmos_obj_free(self._cmosobj)

    decorate(traceLog())

    def readByte(self, indexPort, dataPort, offset):
        buf = ctypes.c_uint8()
        DLL.cmos_obj_read_byte(self._cmosobj, buf, indexPort, dataPort, offset)
        return buf.value

    decorate(traceLog())

    def writeByte(self, buf, indexPort, dataPort, offset):
        DLL.cmos_obj_write_byte(self._cmosobj, buf, indexPort, dataPort,
                                offset)

    decorate(traceLog())

    def registerCallback(self, callback, userdata, freecb):
        cb = WRITE_CALLBACK(callback)
        # append callback to array that has same lifetime as object so python
        # doesnt garbage collect it from under us
        self._callbacks.append(cb)

        # special handling for possible NULL free callback
        fcb = ctypes.cast(None, FREE_CALLBACK)
        if freecb is not None:
            fcb = FREE_CALLBACK(freecb)
            self._callbacks.append(fcb)

        DLL.cmos_obj_register_write_callback(self._cmosobj, cb, userdata, fcb)
Exemplo n.º 8
0
def errorOnNullPtrFN(exception_fn=None):
    decorate(traceLog())

    def _errorOnNullPtrFN(result, func, args):
        getLog(prefix="trace.").info("RAN CTYPES FUNCTION: %s" % func.__name__)
        if not bool(result):  # check for null pointer
            _doExc(exception_fn, result, func, args,
                   _("null pointer returned"))
        return result

    return _errorOnNullPtrFN
Exemplo n.º 9
0
def errorOnNegativeFN(exception_fn=None):
    decorate(traceLog())

    def _errorOnNegativeFN(result, func, args):
        getLog(prefix="trace.").info("RAN CTYPES FUNCTION: %s" % func.__name__)
        if result is None or result < 0:
            _doExc(exception_fn, result, func, args,
                   _("function returned negative error code"))
        return result

    return _errorOnNegativeFN
Exemplo n.º 10
0
def errorOnZeroFN(exception_fn=None):
    decorate(traceLog())

    def _errorOnZeroFN(result, func, args):
        getLog(prefix="trace.").info("RAN CTYPES FUNCTION: %s" % func.__name__)
        if result is None or result == 0:
            _doExc(exception_fn, result, func, args,
                   _("function returned error value of zero"))
        return result

    return _errorOnZeroFN
Exemplo n.º 11
0
class _MemoryAccess(ctypes.Structure):
    _instance = None

    decorate(traceLog())

    def __init__(self, *args):
        self._memobj = None
        self._memobj = DLL.memory_obj_factory(*args)

    # dont decorate __del__
    def __del__(self):
        DLL.memory_obj_free(self._memobj)

    decorate(traceLog())

    def read(self, offset, length):
        buf = ctypes.create_string_buffer(length)
        DLL.memory_obj_read(self._memobj, buf, offset, length)
        return buf

    decorate(traceLog())

    def write(self, buf, offset):
        DLL.memory_obj_write(self._memobj, buf, offset, len(buf))

    decorate(traceLog())

    def search(self, pattern, start, end, stride):
        return DLL.memory_obj_search(self._memobj, pattern, len(pattern),
                                     start, end, stride)

    decorate(traceLog())

    def close_hint(self, hint=None):
        if hint is not None:
            if hint:
                DLL.memory_obj_suggest_leave_open(self._memobj)
            else:
                DLL.memory_obj_suggest_close(self._memobj)

        return DLL.memory_obj_should_close(self._memobj)
Exemplo n.º 12
0
def freeLibStringFN(free_fn, exception_fn=None):
    decorate(traceLog())
    def _freeLibStringFN(result, func, args):
        getLog(prefix="trace.").info("RAN CTYPES FUNCTION: %s" % func.__name__)
        pystr = ctypes.cast(result, ctypes.c_char_p).value
        if pystr is None:
            pystr = ""
            #_doExc(exception_fn, result, func, args, _("null string returned") )

        free_fn(result)
        return pystr
    return _freeLibStringFN
Exemplo n.º 13
0
class SmbiosStructure(ctypes.Structure):
    decorate(traceLog(), strip_trailing_whitespace())

    def getString(self, off):
        return DLL.smbios_struct_get_string_from_offset(self, off)

    decorate(traceLog(), strip_trailing_whitespace())

    def getStringNumber(self, num):
        return DLL.smbios_struct_get_string_number(self, num)

    decorate(traceLog())

    def getType(self):
        return DLL.smbios_struct_get_type(self)

    decorate(traceLog())

    def getLength(self):
        return DLL.smbios_struct_get_length(self)

    decorate(traceLog())

    def getHandle(self):
        return DLL.smbios_struct_get_handle(self)

    # use struct module to pull data out
    decorate(traceLog())

    def getData(self, offset, len):
        buf = ctypes.create_string_buffer(len)
        DLL.smbios_struct_get_data(self, buf, offset, len)
        return buf.raw
Exemplo n.º 14
0
def freeLibStringFN(free_fn, exception_fn=None):
    decorate(traceLog())

    def _freeLibStringFN(result, func, args):
        getLog(prefix="trace.").info("RAN CTYPES FUNCTION: %s" % func.__name__)
        pystr = ctypes.cast(result, ctypes.c_char_p).value
        if pystr is None:
            pystr = ""
            #_doExc(exception_fn, result, func, args, _("null string returned") )

        free_fn(result)
        return pystr

    return _freeLibStringFN
Exemplo n.º 15
0
class PluginConduit(object):
    decorate(traceLog())

    def __init__(self, parent, base, conf):
        self._parent = parent
        self._base = base
        self._conf = conf

        self.logger = getLog()
        self.verbose_logger = getLog(prefix="verbose.")

    decorate(traceLog())

    def info(self, msg):
        self.verbose_logger.info(msg)

    decorate(traceLog())

    def error(self, msg):
        self.logger.error(msg)

    decorate(traceLog())

    def getVersion(self):
        import firmwaretools
        return firmwaretools.__version__

    decorate(traceLog())

    def getOptParser(self):
        '''Return the optparse.OptionParser instance for this execution of Yum

        In the "config" slot a plugin may add extra options to this
        instance to extend the command line options that Yum exposes.

        In all other slots a plugin may only read the OptionParser instance.
        Any modification of the instance at this point will have no effect.

        @return: the global optparse.OptionParser instance used by Yum. May be
            None if an OptionParser isn't in use.
        '''
        return self._parent.optparser

    decorate(traceLog())

    def getBase(self):
        return self._base

    decorate(traceLog())

    def getConf(self):
        return self._conf
Exemplo n.º 16
0
class MyTreeModel(gtk.GenericTreeModel):
    # File, License, Signoff, Comment, STOCK_ID
    _column_types = [str, str, str, str, str]
    columns = {
        "basename": 0,
        "license": 1,
        "signoff": 2,
        "comment": 3,
        "compatible": 4,
        "bad_license_list": 5
    }

    def __init__(self, *args, **kargs):
        gtk.GenericTreeModel.__init__(self)

        from sqlobject.sqlbuilder import EXISTS, Select, Outer, LEFTOUTERJOIN
        self.fd = license_db.Filedata
        self.query_only_with_deps = Filedata.select
        self.query_only_with_deps_clause = (EXISTS(
            Select(DtNeededList.q.Filedata,
                   where=(Outer(Filedata).q.id == DtNeededList.q.Filedata))), )
        self.query_all = Filedata.select
        self.query_all_clause = ()

        #self.default_query = self.query_all
        #self.default_query_clause = self.query_all_clause

        self.count = self.query_all(*self.query_all_clause).count()

        self.default_query = self.query_only_with_deps
        self.default_query_clause = self.query_only_with_deps_clause

    decorate(traceLog())

    def on_get_flags(self):
        return 0
        #return gtk.TREE_MODEL_LIST_ONLY | gtk.TREE_MODEL_ITERS_PERSIST

    decorate(traceLog())

    def on_get_n_columns(self):
        return len(self._column_types)

    decorate(traceLog())

    def on_get_column_type(self, index):
        return self._column_types[index]

    decorate(traceLog())

    def on_get_iter(self, path):
        moduleLogVerbose.info("on_get_iter: %s" % repr(path))
        q = self.default_query(*self.default_query_clause)

        # iterate while there are children and there are path elements left
        retval = {"row": [], "query": [], "path": path}
        for row_no in path:
            moduleLogVerbose.info("  query %s" % row_no)
            iterq = iter(q[row_no:self.count])
            #for x in range(row_no): iterq.next()
            retval["query"].append(iterq)
            row = iterq.next()
            retval["row"].append(row)

            # set the query to the list of children
            q = DtNeededList.select(DtNeededList.q.Filedata == row.id
                                    ).throughTo.Soname.throughTo.has_soname
            count = DtNeededList.select(
                DtNeededList.q.Filedata == row.id).count()

        moduleLogVerbose.info("on_get_iter RETURN: %s" % repr(retval))
        return retval

    decorate(traceLog())

    def on_get_path(self, rowref):
        moduleLogVerbose.info("on_get_path: %s" % repr(rowref))
        return rowref["path"]

    decorate(traceLog())

    def on_get_value(self, rowref, column):
        moduleLogVerbose.info("on_get_value: %s, %s" % (repr(rowref), column))
        filedata = rowref["row"][-1]
        if filedata is None:
            return "nonexistent row: %s" % repr(rowref["path"])

        if column == self.columns["basename"]:
            return filedata.basename
        elif column == self.columns["license"]:
            return license_db.get_license(filedata)
        elif column == self.columns["signoff"]:
            try:
                return license_db.tags_matching(filedata, "SIGNOFF").next()
            except StopIteration, e:
                return ""
        elif column == self.columns["comment"]:
            try:
                return license_db.tags_matching(filedata, "COMMENT").next()
            except StopIteration, e:
                return ""
Exemplo n.º 17
0
class _TokenD4(ctypes.Structure):
    TokenPtrSubclass(0xD4)
    _pack_ = 1
    _fields_ = [("tokenId", ctypes.c_uint16), ("location", ctypes.c_uint16),
                ("value", ctypes.c_uint16)]


class _TokenDA(ctypes.Structure):
    TokenPtrSubclass(0xDA)
    _pack_ = 1
    _fields_ = [("tokenId", ctypes.c_uint16), ("location", ctypes.c_uint8),
                ("andMask", ctypes.c_uint8), ("orValue", ctypes.c_uint8)]


decorate(traceLog())


def TokenTable(flags=TOKEN_GET_SINGLETON, factory_args=None):
    if factory_args is None: factory_args = []
    if _TokenTable._instance is None:
        _TokenTable._instance = _TokenTable(flags, *factory_args)
    return _TokenTable._instance


class _TokenTable(ctypes.Structure):
    _instance = None
    decorate(traceLog())

    def __init__(self, *args):
        self._tableobj = None
Exemplo n.º 18
0
class MyTreeModel(gtk.GenericTreeModel):
    # File, License, Signoff, Comment, STOCK_ID
    _column_types = [str, str, str, str, str]
    columns = {
        "basename": 0,
        "license": 1,
        "signoff": 2,
        "comment": 3,
        "compatible": 4,
        "bad_license_list": 5
    }

    def __init__(self, *args, **kargs):
        gtk.GenericTreeModel.__init__(self)
        self.fd = license_db.Filedata

    def _query_deps(self, row_id):
        return DtNeededList.select(DtNeededList.q.filedata == row_id
                                   ).throughTo.soname.throughTo.has_soname

    def _query_all_filedata(self):
        #return self.fd.select()
        return Filedata.select(
            # only query things that actually have dependencies
            EXISTS(
                Select(DtNeededList.q.filedata,
                       where=(Outer(Filedata).q.id == DtNeededList.q.filedata))
            ),
            # sort by filename
            orderBy=Filedata.q.basename)

    decorate(traceLog())

    def on_get_flags(self):
        return gtk.TREE_MODEL_ITERS_PERSIST
        #return gtk.TREE_MODEL_LIST_ONLY | gtk.TREE_MODEL_ITERS_PERSIST

    decorate(traceLog())

    def on_get_n_columns(self):
        return len(self._column_types)

    decorate(traceLog())

    def on_get_column_type(self, index):
        return self._column_types[index]

    decorate(traceLog())

    def on_get_iter(self, path):
        retval = None
        # iterate while there are children and there are path elements left
        for p in path:
            retval = self.on_iter_nth_child(retval, p)
            if retval is None:
                break
        return retval

    decorate(traceLog())

    def on_get_path(self, rowref):
        return rowref["path"]

    decorate(traceLog())

    def on_get_value(self, rowref, column):
        filedata = rowref["row"]
        if filedata is None:
            return "nonexistent row: %s" % repr(rowref["path"])

        if column == self.columns["basename"]:
            return filedata.basename
        elif column == self.columns["license"]:
            return license_db.get_license(filedata)
        elif column == self.columns["signoff"]:
            try:
                return license_db.tags_matching(filedata, "SIGNOFF").next()
            except StopIteration, e:
                return ""
        elif column == self.columns["comment"]:
            try:
                return license_db.tags_matching(filedata, "COMMENT").next()
            except StopIteration, e:
                return ""
Exemplo n.º 19
0
class Plugins:
    '''
    Manager class for plugins.
    '''
    def __init__(self, base, optparser=None, types=None, disabled=None):
        '''Initialise the instance.
        '''
        self.base = base
        self.optparser = optparser
        self.cmdline = (None, None)

        self.verbose_logger = getLog(prefix="verbose.")

        self.disabledPlugins = disabled
        if types is None:
            types = ALL_TYPES
        if not isinstance(types, (list, tuple)):
            types = (types, )

        # TODO: load plugins here
        self._plugins = {}
        for i in self.base.listPluginsFromIni():
            conf = self.base.getPluginConfFromIni(i)
            moduleLogVerbose.info("Checking Plugin (%s)" % i)
            if conf.enabled:
                self._loadModule(i, conf, types)

        # Call close handlers when yum exit's
        #atexit.register(self.run, 'close')

        # Let plugins register custom config file options
        self.run('config')

    decorate(traceLog())

    def _loadModule(self, pluginName, conf, types):
        # load plugin
        try:
            savePath = sys.path
            sys.path.insert(0, self.base.conf.pluginSearchPath)
            if conf.search is not None:
                sys.path.insert(0, conf.search)
            module = __import__(conf.module, globals(), locals(), [])
            sys.path = savePath
        except DisablePlugin:
            moduleLogVerbose.info(
                "\tPlugin raised DisablePlugin exception. skipping.")
            return
        except ImportError, e:
            sys.path = savePath
            raise errors.ConfigError('Plugin "%s" cannot be loaded: %s' %
                                     (conf.module, e))

        for i in conf.module.split(".")[1:]:
            module = getattr(module, i)

        # Check API version required by the plugin
        if not hasattr(module, 'requires_api_version'):
            raise errors.ConfigError(
                'Plugin "%s" doesn\'t specify required API version' %
                conf.module)

        if not apiverok(API_VERSION, module.requires_api_version):
            raise errors.ConfigError(
                'Plugin "%s" requires API %s. Supported API is %s.' % (
                    conf.module,
                    module.requires_api_version,
                    API_VERSION,
                ))

        # Check plugin type against filter
        plugintypes = getattr(module, 'plugin_type', None)
        if plugintypes is None:
            raise errors.ConfigError(
                'Plugin "%s" doesn\'t specify plugin type' % pluginName)
        if not isinstance(plugintypes, (list, tuple)):
            plugintypes = (plugintypes, )
        for plugintype in plugintypes:
            if plugintype not in types:
                moduleLogVerbose.info(
                    "\tPlugin %s not loaded: doesnt match load type (%s)" %
                    (pluginName, plugintypes))
                return
        # Check if this plugin has been temporary disabled
        if self.disabledPlugins:
            if pluginName in self.disabledPlugins:
                moduleLogVerbose.info("\tPlugin %s not loaded: disabled" %
                                      pluginName)
                return

        moduleLogVerbose.info("\tLoaded %s plugin" % pluginName)
        self._plugins[pluginName] = {"conf": conf, "module": module}
Exemplo n.º 20
0
class Token(ctypes.Structure):
    decorate(traceLog())

    def getId(self):
        return DLL.token_obj_get_id(self)

    # dont trace or we recurse...
    def __repr__(self):
        return "<libsmbios_c.Token ID 0x%04x>" % DLL.token_obj_get_id(self)

    decorate(traceLog())

    def getType(self):
        return DLL.token_obj_get_type(self)

    decorate(traceLog())

    def isBool(self):
        return DLL.token_obj_is_bool(self)

    decorate(traceLog())

    def isActive(self):
        return DLL.token_obj_is_active(self)

    decorate(traceLog())

    def activate(self):
        return DLL.token_obj_activate(self)

    decorate(traceLog())

    def isString(self):
        return DLL.token_obj_is_string(self)

    decorate(traceLog())

    def getPtr(self):
        ptr = DLL.token_obj_get_ptr(self)
        typ = ctypes.POINTER(TokenPtr.subclasses[self.getType()])
        return ctypes.cast(ptr, typ).contents

    decorate(traceLog())

    def getString(self):
        len = ctypes.c_size_t()
        retstr = DLL.token_obj_get_string(self, ctypes.byref(len))
        # not usually null-terminated, so use string_at with len
        if bool(retstr):  # avoid null-ptr deref
            return ctypes.string_at(retstr, len.value)
        else:
            return None

    decorate(traceLog())

    def setString(self, newstr):
        return DLL.token_obj_set_string(self, newstr, len(newstr))

    decorate(traceLog())

    def tryPassword(self, pass_ascii, pass_scancode):
        return DLL.token_obj_try_password(self, pass_ascii, pass_scancode)
Exemplo n.º 21
0
class _DellSmi(ctypes.Structure):
    _instance = None

    decorate(traceLog())
    def __init__(self, *args, **kargs):
        self._smiobj = None
        self._smiobj = DLL.dell_smi_factory(*args)
        self.bufs = [0,0,0,0]

    # dont decorate __del__
    def __del__(self):
        DLL.dell_smi_obj_free(self._smiobj)

    decorate(traceLog())
    def setClass(self, smiclass):
        DLL.dell_smi_obj_set_class(self._smiobj, smiclass)

    decorate(traceLog())
    def setSelect(self, select):
        DLL.dell_smi_obj_set_select(self._smiobj, select)

    decorate(traceLog())
    def setArg(self, arg, val):
        DLL.dell_smi_obj_set_arg(self._smiobj, arg, val)

    decorate(traceLog())
    def getRes(self, res):
        return DLL.dell_smi_obj_get_res(self._smiobj, res)

    decorate(traceLog())
    def buffer_frombios_auto(self, arg, size):
        self.bufs[arg] = DLL.dell_smi_obj_make_buffer_frombios_auto(self._smiobj, arg, size)
        return self.bufs[arg]

    decorate(traceLog())
    def buffer_frombios_withheader(self, arg, size):
        self.bufs[arg] = DLL.dell_smi_obj_make_buffer_frombios_withheader(self._smiobj, arg, size)
        return self.bufs[arg]

    decorate(traceLog())
    def buffer_frombios_withoutheader(self, arg, size):
        self.bufs[arg] = DLL.dell_smi_obj_make_buffer_frombios_withoutheader(self._smiobj, arg, size)
        return self.bufs[arg]

    decorate(traceLog())
    def buffer_tobios(self, arg, size, buf):
        self.bufs[arg] = DLL.dell_smi_obj_make_buffer_tobios(self._smiobj, arg, size)
        if len(buf) < size: size = len(buf)
        ctypes.memmove( self.bufs[arg], buf, size )

    decorate(traceLog())
    def execute(self):
        ret = DLL.dell_smi_obj_execute(self._smiobj)
        raiseExceptionOnError(ret, self)

    decorate(traceLog())
    def getBufContents(self, arg):
        return self.bufs[arg]
Exemplo n.º 22
0
    decorate(traceLog())
    def getLength(self):
        return DLL.smbios_struct_get_length(self)

    decorate(traceLog())
    def getHandle(self):
        return DLL.smbios_struct_get_handle(self)

    # use struct module to pull data out
    decorate(traceLog())
    def getData(self, offset, len):
        buf = ctypes.create_string_buffer(len)
        DLL.smbios_struct_get_data(self, buf, offset, len)
        return buf.raw

decorate(traceLog())
def SmbiosTable(flags=SMBIOS_GET_SINGLETON, *factory_args):
    if flags & SMBIOS_GET_SINGLETON:
        if _SmbiosTable._instance is None:
            _SmbiosTable._instance = _SmbiosTable( flags, *factory_args)
        return _SmbiosTable._instance
    else:
        return _SmbiosTable( flags, *factory_args)

class _SmbiosTable(ctypes.Structure):
    _instance = None

    decorate(traceLog())
    def __init__(self, *args):
        self._tableobj = None
        self._tableobj = DLL.smbios_table_factory(*args)
Exemplo n.º 23
0
class FtBase(object):
    """This is a primary structure and base class. It houses the objects and
       methods needed to perform most things . It is almost an abstract
       class in that you will need to add your own class above it for most
       real use."""
    def __init__(self):
        self.logger = getLog()
        self.verbose_logger = getLog(prefix="verbose.")

        self.cmdargs = []
        self.cb = None

        self._conf = None
        self._repo = None
        self._systemInventory = None
        self._vendorId = None
        self._systemId = None

        self.verbosity = 0
        self.trace = 0
        self.loggingConfig = os.path.join(PKGCONFDIR, "firmware.conf")

        # Start with plugins disabled
        self.disablePlugins()

    def _getConfig(self,
                   cfgFiles=None,
                   pluginTypes=(
                       plugins.TYPE_CORE,
                       plugins.TYPE_INVENTORY,
                   ),
                   optparser=None,
                   disabledPlugins=None):
        if self._conf is not None:
            return self._conf

        if cfgFiles is None:
            cfgFiles = [
                os.path.join(PKGCONFDIR, "firmware.conf"),
            ]

        if disabledPlugins is None:
            disabledPlugins = []

        self.conf = confObj()

        self.setupLogging(self.loggingConfig, self.verbosity, self.trace)

        self.setConfFromIni(cfgFiles)

        self.conf.uid = os.geteuid()

        self.doPluginSetup(optparser, pluginTypes, disabledPlugins)

        return self._conf

    def setupLogging(self, configFile, verbosity=1, trace=0):
        # set up logging
        logging.config.fileConfig(configFile)
        root_log = logging.getLogger()
        ft_log = logging.getLogger("firmwaretools")
        ft_verbose_log = logging.getLogger("verbose")
        ft_trace_log = logging.getLogger("trace")

        ft_log.propagate = 0
        ft_trace_log.propagate = 0
        ft_verbose_log.propagate = 0

        if verbosity >= 1:
            ft_log.propagate = 1
        if verbosity >= 2:
            ft_verbose_log.propagate = 1
        if verbosity >= 3:
            for hdlr in root_log.handlers:
                hdlr.setLevel(logging.DEBUG)
        if trace:
            ft_trace_log.propagate = 1

    decorate(traceLog())

    def setConfFromIni(self, cfgFiles):
        defaults = {
            "sysconfdir": SYSCONFDIR,
            "pythondir": PYTHONDIR,
            "datadir": DATADIR,
            "pkgpythondir": PKGPYTHONDIR,
            "pkgdatadir": PKGDATADIR,
            "pkgconfdir": PKGCONFDIR,
            "localstatedir": LOCALSTATEDIR,
        }
        self._ini = ConfigParser.SafeConfigParser(defaults)
        for i in cfgFiles:
            self._ini.read(i)

        mapping = {
            # conf.WHAT    : (iniSection, iniOption, default)
            "storageTopdir":
            ('main', 'storage_topdir', "%s/firmware" % DATADIR),
            "pluginSearchPath": ('main', 'plugin_search_path',
                                 os.path.join(PKGDATADIR, "plugins")),
            "pluginConfDir": ('main', 'plugin_config_dir',
                              os.path.join(PKGCONFDIR, "firmware.d")),
            "rpmMode": ('main', 'rpm_mode', "manual"),
        }
        for key, val in mapping.items():
            if self._ini.has_option(val[0], val[1]):
                setattr(self.conf, key, self._ini.get(val[0], val[1]))
            else:
                setattr(self.conf, key, val[2])

        # read plugin configs
        for i in glob.glob("%s/*.conf" % self.conf.pluginConfDir):
            self._ini.read(i)

    decorate(traceLog())

    def listPluginsFromIni(self):
        return [
            x[len("plugin:"):] for x in self._ini.sections()
            if x.startswith("plugin:")
        ]

    decorate(traceLog())

    def getPluginConfFromIni(self, plugin):
        section = "plugin:%s" % plugin
        conf = confObj()

        conf.module = None
        conf.enabled = False
        conf.search = None

        for i in self._ini.options(section):
            setattr(conf, i, self._ini.get(section, i))

        #required ("enabled", "module"):
        if getattr(conf, "module", None) is None:
            conf.enabled = False

        return conf

    # called early so no tracing.
    def disablePlugins(self):
        '''Disable plugins
        '''
        self.plugins = plugins.DummyPlugins()

    decorate(traceLog())

    def doPluginSetup(self,
                      optparser=None,
                      pluginTypes=None,
                      disabledPlugins=None):
        if isinstance(self.plugins, plugins.Plugins):
            raise RuntimeError("plugins already initialised")

        self.plugins = plugins.Plugins(self, optparser, pluginTypes,
                                       disabledPlugins)

    decorate(traceLog())

    def _getRepo(self):
        if self._repo is not None:
            return self._repo

        self._repo = repository.Repository(self.conf.storageTopdir)
        return self._repo

    decorate(traceLog())

    def _getInventory(self):
        if self._systemInventory is not None:
            return self._systemInventory

        self._systemInventory = repository.SystemInventory()
        self.plugins.run("preinventory", inventory=self._systemInventory)
        self.plugins.run("inventory", inventory=self._systemInventory)
        self.plugins.run("postinventory", inventory=self._systemInventory)
        return self._systemInventory

    decorate(traceLog())

    def calculateUpgradeList(self, cb=None):
        saveCb = self.cb
        self.cb = cb
        try:
            for candidate in self.repo.iterPackages(cb=cb):
                self.systemInventory.addAvailablePackage(candidate)

            self.systemInventory.calculateUpgradeList(cb)
        finally:
            self.cb = saveCb

        return self.systemInventory

    # properties so they auto-create themselves with defaults
    repo = property(fget=lambda self: self._getRepo(),
                    fset=lambda self, value: setattr(self, "_repo", value))
    conf = property(fget=lambda self: self._getConfig(),
                    fset=lambda self, value: setattr(self, "_conf", value),
                    fdel=lambda self: setattr(self, "_conf", None))
    systemInventory = property(
        fget=lambda self: self._getInventory(),
        fset=lambda self, value: setattr(self, "_systemInventory", value),
        fdel=lambda self: setattr(self, "_systemInventory", None))

    decorate(traceLog())

    def lock(self):
        if self.conf.uid == 0:
            self.runLock = open(PID_FILE, "a+")
            try:
                fcntl.lockf(self.runLock.fileno(),
                            fcntl.LOCK_EX | fcntl.LOCK_NB)
            except IOError, e:
                raise errors.LockError, "unable to obtain exclusive lock."