Logo Search packages:      
Sourcecode: jockey version File versions  Download package

handlers.py

# (c) 2007 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

'''Define some common abstract basic handler types.

These provide the common functionality for concrete handlers of different
classes, like handlers for a kernel module, a driver package, a handler group,
etc.

Custom concrete handlers need to fulfill the following requirements:
 - __init__(self, ui) must take exactly one argument (a reference to an
   AbstractUI instance). All othe properties must be detected by the
   constructor or changed with methods. These classes are instantiated
   automatically, which is not possible with constructors which need more
   arguments.

 - All handler types in this module have some abstract functions which need to
   be implemented (see the documentation of the particular classes).
'''

import subprocess, os.path, sys, logging
from gettext import gettext as _

import detection
from oslib import OSLib

#--------------------------------------------------------------------#

00042 class Handler:
    '''Abstract basic handler.'''

00045     def __init__(self, ui, name, description=None, rationale=None):
        '''Create a handler with given (human readable) name.
        
        Every handler should have a human readable name. A custom rationale and
        a multi-line description can be given, too. Every handler gets a
        reference to the currently used user interface (subclass of AbstractUI)
        so that it can make callbacks and query the user.
        '''
        self._changed = False
        self._name = name
        self._description = description
        self.ui = ui
        self._rationale = rationale

00059     def name(self):
        '''Return one-line name of the handler (for human consumption).'''

        return self._name

00064     def description(self):
        '''Return multi-line description of the handler.'''

        return self._description

00069     def id(self):
        '''Return an unique identifier of the handler.

        This is used for specifying a handler with --enable/--disable on the
        command line, and is mentioned in the --list output.
        '''
        return '%s:%s' % (str(self.__class__).split('.')[-1], self.name())

00077     def rationale(self):
        '''Return rationale as to why this driver might be enabled.
        
        Might return None if no rationale is available.
        '''
        if self._rationale:
            return self._rationale

        # default rationale
        if self.free():
            return None
        else:
            return _('This driver is necessary to support the '
                'hardware, there is no free/open alternative.\n\n'
                'If this driver is not enabled, the hardware will not '
                'function.')

00094     def changed(self):
        '''Return if the module has been enabled/disabled at least once.'''

        return self._changed

    #
    # The following methods can be specialized in subclasses
    # 

00103     def can_change(self):
        '''Check whether we can actually modify settings of this handler.

        This might not be the case if e. g. the user manually modified a
        configuration file. Return an explanatory text if settings can not be
        changed, or None if changing is ok.
        '''
        return None

    def __str__(self):
        return '%s([%s, %s, %s] %s)' % (
            self.id(),
            str(self.__class__).split('.')[-1],
            self.free() and 'free' or 'nonfree',
            self.enabled() and 'enabled' or 'disabled',
            self.name())

    #
    # The following methods must be implemented in subclasses
    # 

00124     def free(self):
        '''Return if the handler represents a free software driver.'''

        raise NotImplementedError, 'subclasses need to implement this'

00129     def enabled(self):
        '''Return if the handler is enabled.
        
        'Enabled' means that the user agreed to use this driver if it is
        applicable.
        '''
        raise NotImplementedError, 'subclasses need to implement this'

00137     def used(self):
        '''Return if the handler is currently in use.'''

        raise NotImplementedError, 'subclasses need to implement this'

00142     def available(self):
        '''Return if the conditions to use this handler on the system are met.

        This usually means that the hardware for this driver is available, but
        there might be hardware independent drivers, too.
        
        If this returns True or False, the answer is definitive and no further
        detection, db querying, etc is performed. If this returns None, then
        the handler cannot decide availability on its own; in that case it is
        merely available in the handler pool, and an external driver database
        (detection.DriverDB) is queried.
        '''
        raise NotImplementedError, 'subclasses need to implement this'

00156     def ui_category(self):
        '''Return handler category (translated, human readable, short).'''

        raise NotImplementedError, 'subclasses need to implement this'

00161     def enable(self):
        '''Allow the OS to use it if the hardware is available.
        
        If possible, the handler should be loaded, too.
        '''
        self._changed = True

00168     def disable(self):
        '''Prevent the OS from using it even if the hardware is available.

        If possible, the handler should be unloaded, too.
        '''
        self._changed = True

#--------------------------------------------------------------------#

00177 class HandlerGroup(Handler):
    '''Perform operations on a group of handlers.

    A group should be provided if it makes little sense to present several very
    similar handlers in the UI. For example, the three VMWare or the dozens of
    commercial OSS drivers should be grouped.
    '''
    def __init__(self, ui, name, id, description=None, rationale=None):
        Handler.__init__(self, ui, name, description, rationale)
        self._id = id
        self.subhandlers = []

00189     def id(self):
        '''Return an unique identifier of the handler.'''

        return self._id

00194     def add(self, handler):
        '''Add a subhandler.'''

        self.subhandlers.append(handler)

00199     def free(self):
        '''Return if all subhandlers represent free software drivers.'''

        for h in self.subhandlers:
            if not h.free():
                return False

        return True

00208     def enabled(self):
        '''Return if all subhandlers are enabled.'''

        for h in self.subhandlers:
            if not h.enabled():
                return False

        return True

00217     def used(self):
        '''Return if any subhandler is used.'''

        for h in self.subhandlers:
            if h.used():
                return True

        return False

00226     def available(self):
        '''Return if the hardware for any subhandler is available.
        
        If all subhandlers return False, this returns False. If any subhandler
        returns True, this returns True. Otherwise this returns None.
        '''
        all_False = True

        for h in self.subhandlers:
            a = h.available()
            if a:
                return True
            if a == None:
                all_false = False
            else:
                assert a == False

        if all_false:
            return False
        else:
            return None

00248     def ui_category(self):
        '''Return handler category (translated, human readable, short).'''

        return self.subhandlers[0].ui_category()

00253     def enable(self):
        '''Enable all subhandlers.'''

        for h in self.subhandlers:
            h.enable()

00259     def disable(self):
        '''Disable all subhandlers.'''

        for h in self.subhandlers:
            h.disable()

00265     def changed(self):
        '''Return if at least one subhandler has been enabled/disabled at
        least once.'''

        for h in self.subhandlers:
            if h.changed():
                return True

        return False

00275     def can_change(self):
        '''Check whether we can actually modify settings of this handler.'''

        assert self.subhandlers

        for h in self.subhandlers:
            c = h.can_change()
            if c:
                return c

        return None

#--------------------------------------------------------------------#

00289 class KernelModuleHandler(Handler):
    '''Handler for a kernel module.
    
    This class can be used as a standard handler for kernel modules (and in
    fact detection.get_handlers() uses this as a default handler if there is no
    custom one). Subclasses have to implement __init__() at least.
    '''
    _loaded_modules = None
    
00298     def __init__(self, ui, module, name=None, description=None, rationale=None):
        '''Create handler for a kernel module.
        
        If not given explicitly, the name is read from modinfo's 'description'
        field.
        '''
        self.module = module
        self._modinfo = detection.get_modinfo(self.module)
        assert self._modinfo, 'kernel module %s exists' % self.module
        if not name:
            name = '\n'.join(self._modinfo.get('description', [self.module]))
        Handler.__init__(self, ui, name, description, rationale)

00311     def id(self):
        '''Return an unique identifier of the handler.'''

        return 'kmod:' + self.module

00316     def free(self):
        '''Return if the handler represents a free software driver.'''

        # this function needs to be kept in sync with the kernel function
        # is_license_gpl_compatible()

        for l in self._modinfo.get('license', ['unknown']):
            if l in ('GPL', 'GPL v2', 'GPL and additional rights', 
                'Dual BSD/GPL', 'Dual MIT/GPL', 'Dual MPL/GPL'):
                return True

        return False

00329     def enabled(self):
        '''Return if the handler is enabled.
        
        'Enabled' means that the user agreed to use this driver if it is
        applicable.
        '''
        return not OSLib.inst.module_blacklisted(self.module)

00337     def used(self):
        '''Return if the handler is currently in use.'''

        return self.module_loaded(self.module)

00342     def available(self):
        '''Return if the conditions to use this handler on the system are met
        (e. g. hardware for this driver is available).

        This defaults to None, because we usually want to delegate this to the
        driver db. Subclasses are welcome to override this, of course.
        '''
        return None

00351     def ui_category(self):
        '''Return handler category (translated, human readable, short).'''

        return self.ui._('Device driver')

00356     def enable(self):
        '''Allow the OS to use it if the hardware is available.
        
        This removes the module from the modprobe blacklist.
        '''
        Handler.enable(self)
        OSLib.inst.blacklist_module(self.module, False)
        subprocess.call([OSLib.inst.modprobe_path, self.module])
        self.read_loaded_modules()
        self.rebind(self.module) # TODO: is this always wanted?

00367     def disable(self):
        '''Prevent the OS from using it even if the hardware is available.

        This adds the module to the modprobe blacklist.
        '''
        Handler.disable(self)
        OSLib.inst.blacklist_module(self.module, True)

    @classmethod
00376     def rebind(klass, module):
        '''Re-bind all devices using the module.
        
        This is necessary for example to reload firmware.
        '''
        drivers_dir = os.path.join(OSLib.inst.sys_dir, 'module', module, 'drivers')
        if not os.path.isdir(drivers_dir):
            logging.warning('%s does not exist, cannot rebind %s driver' % (
                drivers_dir, module))
            return

        for driver in os.listdir(drivers_dir):
            driver_path = os.path.join(drivers_dir, driver)
            for device in os.listdir(driver_path):
                # only consider subdirs which are not called 'module'
                if device == 'module' or not os.path.isdir(
                    os.path.join(driver_path, device)):
                    continue
                try:
                    logging.debug('unbind/rebind on driver %s: device %s', driver_path, device)
                    open(os.path.join(driver_path, 'unbind'), 'w').write(device)
                    open(os.path.join(driver_path, 'bind'), 'w').write(device)
                except IOError:
                    logging.warning('unbind/rebind for device %s on driver %s failed', 
                        device, driver_path, exc_info=True)

    @classmethod
00403     def read_loaded_modules(klass):
        '''Get the list of loaded kernel modules.'''

        klass._loaded_modules = []

        proc_modules = open(OSLib.inst.proc_modules)
        try:
            for line in proc_modules:
                try:
                    line = line[:line.index(' ')]
                except ValueError:
                    pass

                klass._loaded_modules.append(line.strip())
        finally:
            proc_modules.close()

    @classmethod
00421     def module_loaded(klass, module):
        '''Return if the handler is currently in use.'''

        if klass._loaded_modules == None:
            klass.read_loaded_modules()

        return module in klass._loaded_modules

#--------------------------------------------------------------------#

00431 class FirmwareHandler(KernelModuleHandler):
    '''Handler for an already available kernel module needing firmware.

    Subclasses need to extend enable() and implement disable() to do something
    with the downloaded file (unpack it, put into the right directory, etc.).
    This class' enable() function will deal with downloading it and the UI
    progress reporting of the download.
    '''
00439     def __init__(self, ui, module, testfile, name=None, description=None, 
            rationale=None, url=None, sha1sum=None, free=False):
        '''Create handler for a piece of firmware for a kernel module.
        
        The required argument 'url' specifies where the firmware can be
        downloaded from. The optional 'sha1sum' argument provides a checksum of
        the downloaded file. The file will not be installed if it does not
        match.

        enabled() will return True iff the path in testfile exists.

        By default this handler assumes that the firmware is not free (since
        otherwise the distribution could ship it together with the driver). You
        can set 'free' to True for free firmware.
    
        If not given explicitly, the name is read from modinfo's 'description'
        field.
        '''
        self.url = url
        self.sha1sum = sha1sum
        self._free = free
        self.testfile = testfile
        if not rationale:
            if self._free:
                rationale = ui.string_free_aux_firmware
            else:
                rationale = ui.string_nonfree_aux_firmware

        KernelModuleHandler.__init__(self, ui, module, name, description,
            rationale)

00470     def free(self):
        '''Return if the handler represents a free software driver.'''

        if self._free == False:
            return False
        elif self._free is None:
            return KernelModuleHandler.free(self)
        else:
            return True

00480     def enabled(self):
        '''Return if the handler is enabled.
        
        'Enabled' means that the user agreed to use this driver if it is
        applicable.
        '''
        return os.path.exists(self.testfile) and KernelModuleHandler.enabled(self)

00488     def used(self):
        '''Return if the handler is currently in use.'''

        return self.enabled() and KernelModuleHandler.used(self)

00493     def ui_category(self):
        '''Return handler category (translated, human readable, short).'''

        return self.ui._('Firmware')

00498     def enable(self):
        '''Allow the OS to use it if the hardware is available.
        
        This downloads the url and puts it into self.firmware_file. Subclasses
        need to provide an actual implementation what to do with the file.
        '''
        self.firmware_file = self.ui.download_url(self.url)[0]
        if not self.firmware_file:
            return

        # TODO: sha1sum check

        KernelModuleHandler.enable(self)

00512     def disable(self):
        '''Prevent the OS from using it even if the hardware is available.
        
        Implementation in subclasses need to remove the firmware files and call
        KernelModuleHandler.disable().
        '''
        raise NotImplementedError, 'subclasses need to implement this'

#--------------------------------------------------------------------#

00522 class DriverPackageHandler(Handler):
    '''Handler for a driver package, not tied to a particular kernel module.
    
    Subclasses need to implement __init__(), available() and used() at least.
    '''
00527     def __init__(self, ui, package, name=None, description=None, 
            rationale=None):
        '''Create handler for of driver package.
        
        If not given explicitly, the name and description are taken from the
        distribution package.
        '''
        self.package = package
        if not name or not description:
            (distro_name, distro_desc) = OSLib.inst.package_description(package)
            if not name:
                name = distro_name
            if not description:
                description = distro_desc

        Handler.__init__(self, ui, name, description, rationale)

00544     def id(self):
        '''Return an unique identifier of the handler.'''

        return 'pkg:' + self.package

00549     def free(self):
        '''Return if the handler represents a free software driver.'''

        return OSLib.inst.is_package_free(self.package)

00554     def enabled(self):
        '''Return if the handler is enabled.
        
        'Enabled' means that the user agreed to use this driver if it is
        applicable.
        '''
        return OSLib.inst.package_installed(self.package)

00562     def available(self):
        '''Return if the conditions to use this handler on the system are met.

        This usually means that the hardware for this driver is available, but
        there might be hardware independent drivers, too.
        
        This returns False if the package is not available, otherwise None.
        Subclasses are welcome to add a positive detection, but should return
        False if this method returns False, unless they require a separate
        package repository.
        '''
        try:
            OSLib.inst.package_description(self.package)
            return None
        except ValueError:
            return False

00579     def ui_category(self):
        '''Return handler category (translated, human readable, short).'''

        return self.ui._('Device driver')

00584     def enable(self):
        '''Allow the OS to use it if the hardware is available.
        
        If possible, the handler should be loaded, too.
        '''
        self.ui.install_package(self.package)
        if OSLib.inst.package_installed(self.package):
            Handler.enable(self)

00593     def disable(self):
        '''Prevent the OS from using it even if the hardware is available.

        If possible, the handler should be unloaded, too.
        '''
        self.ui.remove_package(self.package)
        Handler.disable(self)

#--------------------------------------------------------------------#

00603 class ModulePackageHandler(KernelModuleHandler, DriverPackageHandler):
    '''Kernel module which needs an additional driver package.
    
    Subclasses need to implement __init__(), available() and used() at least.
    '''
00608     def __init__(self, ui, module, package, name=None, description=None, 
            rationale=None):
        '''Handler for a kernel module which needs an additional driver package.
        
        If not given explicitly, the name is read from modinfo's 'description'
        field.
        '''
        DriverPackageHandler.__init__(self, ui, package, name, description,
            rationale)
        KernelModuleHandler.__init__(self, ui, module, name, description,
            rationale)

00620     def id(self):
        '''Return an unique identifier of the handler.'''

        return KernelModuleHandler.id(self)

00625     def can_change(self):
        '''Check whether we can actually modify settings of this handler.

        This might not be the case if e. g. the user manually modified a
        configuration file. Return an explanatory text if settings can not be
        changed, or None if changing is ok.
        '''
        return DriverPackageHandler.can_change(self) or \
            KernelModuleHandler.can_change(self)

00635     def free(self):
        '''Return if the handler represents a free software driver.'''

        return DriverPackageHandler.free(self) and \
            KernelModuleHandler.free(self)

00641     def available(self):
        '''Return if the conditions to use this handler on the system are met.

        This usually means that the hardware for this driver is available, but
        there might be hardware independent drivers, too.
        
        This returns False if the package is not available, otherwise None.
        Subclasses are welcome to add a positive detection, but should return
        False if this method returns False.
        '''
        # KernelModuleHandler does not have an interesting implementation, so
        # only query the package one by default
        return DriverPackageHandler.available(self)

00655     def enabled(self):
        '''Return if the handler is enabled.
        
        'Enabled' means that the user agreed to use this driver if it is
        applicable.
        '''
        dr = DriverPackageHandler.enabled(self)
        km = KernelModuleHandler.enabled(self)
        logging.debug('ModulePackageHandler(%s, %s): module enabled: %s, package installed: %s' % (
            self.module, self.package, km, dr))
        return dr and km

00667     def enable(self):
        '''Allow the OS to use it if the hardware is available.
        
        If possible, the handler should be loaded, too.
        '''
        DriverPackageHandler.enable(self)
        KernelModuleHandler.enable(self)

00675     def disable(self):
        '''Prevent the OS from using it even if the hardware is available.

        If possible, the handler should be unloaded, too.
        '''
        DriverPackageHandler.disable(self)
        KernelModuleHandler.disable(self)

Generated by  Doxygen 1.6.0   Back to index