Esempio n. 1
0
def killProcessByName(processName):
    killed = False
    ec = ExecCmd(log)
    lst = ec.run('killall %s' % processName)
    if len(lst) == 0:
        killed = True
    return killed
def getCurrentTheme():
    curTheme = ['']
    if getCurrentResolution() != '':
        cmd = '/usr/sbin/plymouth-set-default-theme'
        ec = ExecCmd(log)
        curTheme = ec.run(cmd, False)
    return curTheme[0]
def getPackageStatus(packageName):
    status = ''
    try:
        cmdChk = 'apt-cache policy ' + str(packageName)
        ec = ExecCmd(log)
        packageCheck = ec.run(cmdChk, False)

        for line in packageCheck:
            instChk = re.search('installed:.*\d.*', line.lower())
            if not instChk:
                instChk = re.search('installed.*', line.lower())
                if instChk:
                    # Package is not installed
                    log.write('Package not installed: ' + str(packageName), 'drivers.getPackageStatus', 'debug')
                    status = packageStatus[1]
                    break
            else:
                # Package is installed
                log.write('Package is installed: ' + str(packageName), 'drivers.getPackageStatus', 'debug')
                status = packageStatus[0]
                break
        # Package is not found: uninstallable
        if not status:
            log.write('Package not found: ' + str(packageName), 'drivers.getPackageStatus', 'warning')
            status = packageStatus[2]
    except:
        # If something went wrong: assume that package is uninstallable
        log.write('Could not get status info for package: ' + str(packageName), 'drivers.getPackageStatus', 'error')
        status = packageStatus[2]

    return status
class DistroGeneral(object):
    def __init__(self, distroPath):
        self.ec = ExecCmd()
        distroPath = distroPath.rstrip('/')
        if basename(distroPath) == "root":
            distroPath = dirname(distroPath)
        self.distroPath = distroPath
        self.rootPath = join(distroPath, "root")

        self.edition = basename(distroPath)
        self.description = "SolydXK"
        infoPath = join(self.rootPath, "etc/solydxk/info")
        if exists(infoPath):
            self.edition = self.ec.run(cmd="grep EDITION= \"{}\" | cut -d'=' -f 2".format(infoPath), returnAsList=False).strip('"')
            self.description = self.ec.run(cmd="grep DESCRIPTION= \"{}\" | cut -d'=' -f 2".format(infoPath), returnAsList=False).strip('"')

    def getIsoFileName(self):
        # Get the date string
        d = datetime.now()
        serial = d.strftime("%Y%m")
        # Check for a localized system
        localePath = join(self.rootPath, "etc/default/locale")
        if exists(localePath):
            locale = self.ec.run(cmd="grep LANG= {}".format(localePath), returnAsList=False).strip('"').replace(" ", "")
            matchObj = re.search("\=\s*([a-z]{2})", locale)
            if matchObj:
                language = matchObj.group(1)
                if language != "en":
                    serial += "_{}".format(language)
        isoFileName = "{}_{}.iso".format(self.description.lower().replace(' ', '_').split('-')[0], serial)
        return isoFileName
Esempio n. 5
0
    def __init__(self, collectData=True):
        # Get the settings
        self.scriptDir = abspath(dirname(__file__))
        self.filesDir = join(self.scriptDir, "files")
        self.ec = ExecCmd()
        self.cfg = Config(join(self.filesDir, 'updatemanager.conf'))
        self.settings = self.getSettings()

        self.umfiles = {}
        self.umfiles['umupd'] = join(self.filesDir, ".umupd")
        self.umfiles['umrefresh'] = join(self.filesDir, ".umrefresh")
        self.umfiles['ummaintenance'] = join(self.filesDir, ".ummaintenance")
        self.umfiles['uminstallum'] = join(self.filesDir, ".uminstallum")

        # Variables
        self.localUpdVersion = None
        self.serverUpdVersion = None
        self.newUpd = False

        self.hasInternet = False
        self.repos = []

        # Set global variables
        self.umfilesUrl = self.getUmFilesUrl()
        if collectData:
            self.collectData()
Esempio n. 6
0
def getLatestLunuxHeader(includeString='', excludeString=''):
    lhList = []
    ec = ExecCmd(log)
    list = ec.run('apt search linux-headers', False)
    startIndex = 14
    for item in list:
        lhMatch = re.search('linux-headers-\d[a-zA-Z0-9-\.]*', item)
        if lhMatch:
            lh = lhMatch.group(0)
            addLh = True
            if includeString != '':
                inclMatch = re.search(includeString, lh)
                if inclMatch:
                    if excludeString != '':
                        exclMatch = re.search(excludeString, lh)
                        if exclMatch:
                            addLh = False
                else:
                    addLh = False
        
            # Append to list
            if addLh:
                lhList.append(lh)
    lhList.sort(reverse=True)
    return lhList[0]
Esempio n. 7
0
def getPackageStatus(packageName):
    try:
        cmdChk = 'apt-cache policy ' + str(packageName)
        status = ''
        ec = ExecCmd(log)
        packageCheck = ec.run(cmdChk, False)
            
        for line in packageCheck:
            instChk = re.search('installed:.*\d.*', line.lower())
            if not instChk:             
                instChk = re.search('installed.*', line.lower())
                if instChk:
                    # Package is not installed
                    log.write('Package not installed: ' + str(packageName), 'drivers.getPackageStatus', 'debug')
                    status = packageStatus[1]
                    break
            else:
                # Package is installed
                log.write('Package is installed: ' + str(packageName), 'drivers.getPackageStatus', 'debug')
                status = packageStatus[0]
                break
        # Package is not found: uninstallable
        if not status:
            log.write('Package not found: ' + str(packageName), 'drivers.getPackageStatus', 'warning')
            status = packageStatus[2]
    except:
        # If something went wrong: assume that package is uninstallable
        log.write('Could not get status info for package: ' + str(packageName), 'drivers.getPackageStatus', 'error')
        status = packageStatus[2]
            
    return status
Esempio n. 8
0
def getCurrentTheme():
    curTheme = ['']
    if getCurrentResolution() != '':
        cmd = '/usr/sbin/plymouth-set-default-theme'
        ec = ExecCmd(log)
        curTheme = ec.run(cmd, False)
    return curTheme[0]
Esempio n. 9
0
def isPackageInstalled(packageName, alsoCheckVersion=True):
    isInstalled = False
    try:
        cmd = 'dpkg-query -l %s | grep ^i' % packageName
        if '*' in packageName:
            cmd = 'aptitude search %s | grep ^i' % packageName
        ec = ExecCmd(log)
        pckList = ec.run(cmd, False)
        for line in pckList:
            matchObj = re.search('([a-z]+)\s+([a-z0-9\-_\.]*)', line)
            if matchObj:
                if matchObj.group(1)[:1] == 'i':
                    if alsoCheckVersion:
                        cache = apt.Cache()
                        pkg = cache[matchObj.group(2)]
                        if pkg.installed.version == pkg.candidate.version:
                            isInstalled = True
                            break
                    else:
                        isInstalled = True
                        break
            if isInstalled:
                break
    except:
        pass
    return isInstalled
Esempio n. 10
0
def getLinuxHeadersAndImage(getLatest=False, includeLatestRegExp='', excludeLatestRegExp=''):
    returnList = []
    lhList = []
    ec = ExecCmd(log)
    if getLatest:
        lst = ec.run('aptitude search linux-headers', False)
        for item in lst:
            lhMatch = re.search('linux-headers-\d+\.[a-zA-Z0-9-\.]*', item)
            if lhMatch:
                lh = lhMatch.group(0)
                addLh = True
                if includeLatestRegExp != '':
                    inclMatch = re.search(includeLatestRegExp, lh)
                    if not inclMatch:
                        addLh = False
                if excludeLatestRegExp != '':
                    exclMatch = re.search(excludeLatestRegExp, lh)
                    if exclMatch:
                        addLh = False

                # Append to list
                if addLh:
                    lhList.append(lh)
    else:
        # Get the current linux header package
        linHeader = ec.run("echo linux-headers-$(uname -r)", False)
        lhList.append(linHeader[0])

    # Sort the list and add the linux-image package name
    if lhList:
        lhList.sort(reverse=True)
        returnList.append(lhList[0])
        returnList.append('linux-image-' + lhList[0][14:])
    return returnList
Esempio n. 11
0
 def __init__(self, mountDir, unpackIso, unpackDir, queue):
     threading.Thread.__init__(self)
     self.ec = ExecCmd()
     self.mountDir = mountDir
     self.unpackIso = unpackIso
     self.unpackDir = unpackDir
     self.queue = queue
     self.returnMessage = None
Esempio n. 12
0
def previewPlymouth():
    cmd = "su -c 'plymouthd; plymouth --show-splash ; for ((I=0; I<10; I++)); do plymouth --update=test$I ; sleep 1; done; plymouth quit'"
    log.write('Preview command: ' + cmd, 'drivers.previewPlymouth', 'debug')
    try:
        ec = ExecCmd(log)
        ec.run(cmd, False)
    except Exception, detail:
        log.write(detail, 'drivers.previewPlymouth', 'error')
Esempio n. 13
0
def getDivertedFiles(mustContain=None):
    divertedFiles = []
    cmd = 'dpkg-divert --list'
    if mustContain:
        cmd = 'dpkg-divert --list | grep %s | cut -d' ' -f3' % mustContain
    ec = ExecCmd(log)
    divertedFiles = ec.run(cmd, False)
    return divertedFiles
Esempio n. 14
0
def previewPlymouth():
    cmd = "su -c 'plymouthd; plymouth --show-splash ; for ((I=0; I<10; I++)); do plymouth --update=test$I ; sleep 1; done; plymouth quit'"
    log.write('Preview command: ' + cmd, 'drivers.previewPlymouth', 'debug')
    try:
        ec = ExecCmd(log)
        ec.run(cmd, False)
    except Exception, detail:
        log.write(detail, 'drivers.previewPlymouth', 'error')
Esempio n. 15
0
    def __init__(self, distribution, loggerObject):
        self.distribution = distribution.lower()
        self.log = loggerObject
        self.ec = ExecCmd(self.log)

        # Install nvidia-detect if it isn't installed already
        if functions.getPackageStatus('nvidia-detect') == packageStatus[1]:
            self.log.write('Install nvidia-detect', 'nvidia.getNvidia', 'info')
            self.ec.run('apt-get -y --force-yes install nvidia-detect')
Esempio n. 16
0
def isProcessRunning(processName):
    isProc = False
    cmd = 'ps -C ' + processName
    ec = ExecCmd(log)
    procList = ec.run(cmd, False)
    if procList:
        if len(procList) > 1:
            isProc = True
    return isProc
Esempio n. 17
0
def isPackageInstalled(packageName):
    isInstalled = False
    cmd = 'aptitude search ' + packageName + ' | grep ^i'
    ec = ExecCmd(log)
    packageList = ec.run(cmd, False)
    if packageList:
        if len(packageList) > 0:
            isInstalled = True
    return isInstalled
Esempio n. 18
0
 def __init__(self, distribution, loggerObject):
     self.distribution = distribution.lower()
     self.log = loggerObject
     self.ec = ExecCmd(self.log)
     self.status = ''
     self.currentChip = ''
     self.installableChip = ''
     self.installableDriver = ''
     self.hw = ''
Esempio n. 19
0
def getSystemVersionInfo():
    info = ''
    try:
        ec = ExecCmd(log)
        infoList = ec.run('cat /proc/version', False)
        if infoList:
            info = infoList[0]
    except Exception, detail:
        log.write(detail, 'functions.getSystemVersionInfo', 'error')
Esempio n. 20
0
def getDistribution():
    distribution = ''
    try:
        cmdDist = 'cat /etc/*-release | grep DISTRIB_CODENAME'
        ec = ExecCmd(log)
        dist = ec.run(cmdDist, False)[0]
        distribution = dist[dist.find('=') + 1:]
    except Exception, detail:
        log.write(detail, 'functions.getDistribution', 'error')
Esempio n. 21
0
def getGraphicsCard():
    global graphicsCard
    if graphicsCard == None:
        cmdGraph = 'lspci | grep VGA'
        ec = ExecCmd(log)
        hwGraph = ec.run(cmdGraph, False)
        for line in hwGraph:
            graphicsCard = line[line.find(': ') + 2:]
            break
    return graphicsCard
Esempio n. 22
0
def getDistributionDescription():
    distribution = ''
    try:
        cmdDist = 'cat /etc/*-release | grep DISTRIB_DESCRIPTION'
        ec = ExecCmd(log)
        dist = ec.run(cmdDist, False)[0]
        distribution = dist[dist.find('=') + 1:]
        distribution = string.replace(distribution, '"', '')
    except Exception, detail:
        log.write(detail, 'functions.getDistributionDescription', 'error')
Esempio n. 23
0
    def __init__(self, distroPath):
        self.ec = ExecCmd()
        self.dg = DistroGeneral(distroPath)
        distroPath = distroPath.rstrip('/')
        if basename(distroPath) == "root":
            distroPath = dirname(distroPath)
        self.rootPath = join(distroPath, "root")

        # ISO edition
        self.edition = self.dg.edition
Esempio n. 24
0
def getDefaultTerminal():
    terminal = None
    cmd = "update-alternatives --display x-terminal-emulator"
    ec = ExecCmd(log)
    terminalList = ec.run(cmd, False)
    for line in terminalList:
        reObj = re.search("\'(\/.*)\'", line)
        if reObj:
            terminal = reObj.group(1)
    return terminal
Esempio n. 25
0
def getGraphicsCard():
    global graphicsCard
    if graphicsCard is None:
        cmdGraph = 'lspci | grep VGA'
        ec = ExecCmd(log)
        hwGraph = ec.run(cmdGraph, False)
        for line in hwGraph:
            graphicsCard = line[line.find(': ') + 2:]
            break
    return graphicsCard
Esempio n. 26
0
def isFileLocked(path):
    locked = False
    cmd = 'lsof %s' % path
    ec = ExecCmd(log)
    lsofList = ec.run(cmd, False)
    for line in lsofList:
        if path in line:
            locked = True
            break
    return locked
Esempio n. 27
0
def getPackagesWithFile(fileName):
    packages = []
    if len(fileName) > 0:
        cmd = 'dpkg -S %s' % fileName
        ec = ExecCmd(log)
        packageList = ec.run(cmd, False)
        for package in packageList:
            if '*' not in package:
                packages.append(package[:package.find(':')])
    return packages
Esempio n. 28
0
def getDistributionDescription():
    distribution = ''
    try:
        cmdDist = 'cat /etc/*-release | grep DISTRIB_DESCRIPTION'
        ec = ExecCmd(log)
        dist = ec.run(cmdDist, False)[0]
        distribution = dist[dist.find('=') + 1:]
        distribution = string.replace(distribution, '"', '')
    except Exception, detail:
        log.write(detail, 'functions.getDistributionDescription', 'error')
Esempio n. 29
0
def getVideoCards(pciId=None):
    videoCard = []
    cmdVideo = 'lspci -nn | grep VGA'
    ec = ExecCmd(log)
    hwVideo = ec.run(cmdVideo, False)
    for line in hwVideo:
        videoMatch = re.search(':\s(.*)\[(\w*):(\w*)\]', line)
        if videoMatch and (pciId is None or pciId.lower() + ':' in line.lower()):
            videoCard.append([videoMatch.group(1), videoMatch.group(2), videoMatch.group(3)])
    return videoCard
Esempio n. 30
0
    def __init__(self, distroPath, queue):
        threading.Thread.__init__(self)
        self.ec = ExecCmd()
        self.dg = DistroGeneral(distroPath)
        self.ed = EditDistro(distroPath)
        self.queue = queue

        self.returnMessage = None

        # Paths
        distroPath = distroPath.rstrip('/')
        if basename(distroPath) == "root":
            distroPath = dirname(distroPath)
        self.distroPath = distroPath
        self.rootPath = join(distroPath, "root")
        self.bootPath = join(distroPath, "boot")
        self.livePath = join(self.bootPath, "live")
        self.scriptDir = abspath(dirname(__file__))

        # Check for old dir
        oldDir = join(self.bootPath, "solydxk")
        if exists(oldDir):
            self.ec.run("rm -r %s" % oldDir)

        # Make sure live directory exists
        if not exists(self.livePath):
            self.ec.run("mkdir -p %s" % self.livePath)

        # ISO Name
        self.isoName = self.dg.description

        # ISO distribution
        self.isoBaseName = self.dg.getIsoFileName()
        self.isoFileName = join(self.distroPath, self.isoBaseName)

        # Trackers, and webseeds
        self.trackers = ""
        self.webseeds = ""
        trackersPath = join(self.scriptDir, "files/trackers")
        webseedsPath = join(self.scriptDir, "files/webseeds")
        if exists(trackersPath):
            with open(trackersPath, "r") as f:
                lines = f.readlines()
                trList = []
                for line in lines:
                    trList.append(line.strip())
                self.trackers = ",".join(trList)
        if exists(webseedsPath):
            with open(webseedsPath, "r") as f:
                lines = f.readlines()
                wsList = []
                for line in lines:
                    #wsList.append("%s/%s" % (line.strip(), webseedIsoName))
                    wsList.append("%s/%s" % (line.strip(), self.isoBaseName))
                self.webseeds = ",".join(wsList)
Esempio n. 31
0
def getPackageDependencies(packageName):
    retList = []
    cmd = 'apt-cache depends ' + packageName + ' | grep Depends'
    ec = ExecCmd(log)
    depList = ec.run(cmd, False)
    if depList:
        for line in depList:
            matchObj = re.search(':\s(.*)', line)
            if matchObj:
                retList.append(matchObj.group(1))
    return retList
Esempio n. 32
0
def getGraphicsCardManufacturerPciId():
    pciId = []
    cmdGraph = 'lspci -nn | grep VGA'
    ec = ExecCmd(log)
    hwGraph = ec.run(cmdGraph, False)
    if hwGraph:
        idMatch = re.search('\[(\w*):(\w*)\]', hwGraph[0])
        if idMatch:
            pciId.append(idMatch.group(1))
            pciId.append(idMatch.group(2))
    return pciId
Esempio n. 33
0
def getKernelPackages(getLatest=False, includeLatestRegExp='', excludeLatestRegExp=''):
    lst = []
    ec = ExecCmd(log)
    if getLatest:
        cmdList = ec.run('apt-get -s dist-upgrade | grep "linux-image" | grep ^Inst', False)
        if not cmdList:
            # Already the latest kernel: get all linux-image packages of the current version
            kernelRelease = getKernelRelease()
            if 'amd64' in kernelRelease:
                cmd = "aptitude search linux-image-%s" % kernelRelease
            else:
                pos = kernelRelease.find('486')
                if pos == 0:
                    pos = kernelRelease.find('686')
                if pos > 0:
                    kernelRelease = kernelRelease[0:pos - 1]
                cmd = "aptitude search linux-image-%s" % kernelRelease

            cmdList = ec.run(cmd, False)

        for item in cmdList:
            if not '-dbg' in item:
                obj = re.search('linux\-image\-[a-z0-9\-\.]*', item)
                if obj:
                    img = obj.group(0)
                    addImg = True
                    if includeLatestRegExp != '':
                        inclObj = re.search(includeLatestRegExp, img)
                        if not inclObj:
                            addImg = False
                    if excludeLatestRegExp != '':
                        exclObj = re.search(excludeLatestRegExp, img)
                        if exclObj:
                            addImg = False

                    # Append to list
                    if addImg:
                        lst.append(img)
                        lst.append(string.replace(img, "image", "headers"))

        if not lst:
            # Get the current linux header package
            cmdList = ec.run('echo linux-image-$(uname -r)', False)
            img = cmdList[0]
            lst.append(img)
            lst.append(string.replace(img, "image", "headers"))
    else:
        # Get the current linux header package
        cmdList = ec.run('echo linux-image-$(uname -r)', False)
        img = cmdList[0]
        lst.append(img)
        lst.append(string.replace(img, "image", "headers"))

    return lst
Esempio n. 34
0
def getPackageVersion(packageName):
    version = ''
    cmd = 'apt-cache policy ' + packageName + ' | grep Installed'
    ec = ExecCmd(log)
    versionList = ec.run(cmd, False)

    for line in versionList:
        versionObj = re.search(':\s(.*)', line.lower())
        if versionObj:
            version = versionObj.group(1)
    return version
Esempio n. 35
0
def hasWireless():
    wl = False
    cmd = 'iwconfig | grep "Access Point"'
    ec = ExecCmd(log)
    wlList = ec.run(cmd, False)
    if wlList:
        for line in wlList:
            if 'Access Point' in line:
                wl = True
                break
    return wl
Esempio n. 36
0
def getResolutions(minRes='', maxRes='', reverseOrder=False, getVesaResolutions=False):
    cmd = None
    cmdList = ['640x480', '800x600', '1024x768', '1280x1024', '1600x1200']

    if getVesaResolutions:
        vbeModes = '/sys/bus/platform/drivers/uvesafb/uvesafb.0/vbe_modes'
        if os.path.exists(vbeModes):
            cmd = "cat %s | cut -d'-' -f1" % vbeModes
        elif isPackageInstalled('v86d') and isPackageInstalled('hwinfo'):
            cmd = "sudo hwinfo --framebuffer | grep '0x0' | cut -d' ' -f5"
    else:
        cmd = "xrandr | grep '^\s' | cut -d' ' -f4"

    if cmd is not None:
        ec = ExecCmd(log)
        cmdList = ec.run(cmd, False)
    # Remove any duplicates from the list
    resList = list(set(cmdList))

    avlRes = []
    avlResTmp = []
    minW = 0
    minH = 0
    maxW = 0
    maxH = 0

    # Split the minimum and maximum resolutions
    if 'x' in minRes:
        minResList = minRes.split('x')
        minW = strToNumber(minResList[0], True)
        minH = strToNumber(minResList[1], True)
    if 'x' in maxRes:
        maxResList = maxRes.split('x')
        maxW = strToNumber(maxResList[0], True)
        maxH = strToNumber(maxResList[1], True)

    # Fill the list with screen resolutions
    for line in resList:
        for item in line.split():
            itemChk = re.search('\d+x\d+', line)
            if itemChk:
                itemList = item.split('x')
                itemW = strToNumber(itemList[0], True)
                itemH = strToNumber(itemList[1], True)
                # Check if it can be added
                if itemW >= minW and itemH >= minH and (maxW == 0 or itemW <= maxW) and (maxH == 0 or itemH <= maxH):
                    log.write(_("Resolution added: %(res)s") % { "res": item }, 'functions.getResolutions', 'debug')
                    avlResTmp.append([itemW, itemH])

    # Sort the list and return as readable resolution strings
    avlResTmp.sort(key=operator.itemgetter(0), reverse=reverseOrder)
    for res in avlResTmp:
        avlRes.append(str(res[0]) + 'x' + str(res[1]))
    return avlRes
Esempio n. 37
0
 def __init__(self, treeView, statusIcon, builder, prefs, log, newUpVersion, rtobject=None):
     threading.Thread.__init__(self)
     self.treeView = treeView
     self.statusIcon = statusIcon
     self.builder = builder
     self.window = self.builder.get_object("umWindow")
     self.newUpVersion = newUpVersion
     self.prefs = prefs
     self.log = log
     self.curdir = os.path.dirname(os.path.realpath(__file__))
     self.sharedir = os.path.join(self.curdir.replace('/lib/', '/share/'))
     self.ec = ExecCmd(rtobject)
     print ">>>> InstallThread"
Esempio n. 38
0
def getDistributionReleaseNumber():
    release = 0
    try:
        cmdRel = 'cat /etc/*-release | grep DISTRIB_RELEASE'
        ec = ExecCmd(log)
        relLst = ec.run(cmdRel, False)
        if relLst:
            rel = relLst[0]
            release = rel[rel.find('=') + 1:]
            release = string.replace(release, '"', '')
            release = strToNumber(release)
    except Exception, detail:
        log.write(detail, 'functions.getDistributionReleaseNumber', 'error')
Esempio n. 39
0
 def __init__(self, treeview_update, statusIcon, builder, prefs, log, app_hidden, newUpVersion=None):
     threading.Thread.__init__(self)
     self.treeview_update = treeview_update
     self.statusIcon = statusIcon
     self.builder = builder
     self.window = self.builder.get_object("umWindow")
     self.prefs = prefs
     self.log = log
     self.app_hidden = app_hidden
     self.newUpVersion = newUpVersion
     self.curdir = os.path.dirname(os.path.realpath(__file__))
     self.cfgignored = os.path.join(self.curdir, 'updatemanager.ignored')
     self.ec = ExecCmd()
     print ">>>> RefreshThread"
Esempio n. 40
0
def getAvailableThemes():
    cmd = 'aptitude search ' + avlThemesSearchstr + ' | grep ^p'
    ec = ExecCmd(log)
    availableThemes = ec.run(cmd)
    avlThemes = []

    for line in availableThemes:
        matchObj = re.search('plymouth-themes-([a-zA-Z0-9-]*)', line)
        if matchObj:
            theme = matchObj.group(1)
            if not 'all' in theme:
                avlThemes.append(theme)

    return avlThemes
Esempio n. 41
0
def getAvailableThemes():
    startmatch = '39m-'
    cmd = 'apt search ' + avlThemesSearchstr + ' | grep ^p'
    ec = ExecCmd(log)
    availableThemes = ec.run(cmd)
    avlThemes = []

    for line in availableThemes:
        matchObj = re.search('plymouth-themes-([a-zA-Z0-9-]*)', line)
        if matchObj:
            theme = matchObj.group(1)
            if not 'all' in theme:
                avlThemes.append(theme)

    return avlThemes
Esempio n. 42
0
def getRemovablePackageName(theme):
    cmd = 'dpkg -S ' + theme + '.plymouth'
    log.write('Search package command: ' + cmd, 'drivers.getRemovablePackageName', 'debug')
    package = ''
    ec = ExecCmd(log)
    packageNames = ec.run(cmd, False)

    for line in packageNames:
        if avlThemesSearchstr in line:
            matchObj = re.search('(^.*):', line)
            if matchObj:
                package = matchObj.group(1)
                break
    log.write('Package found ' + package, 'drivers.getRemovablePackageName', 'debug')
    return package
Esempio n. 43
0
    def __init__(self, umglobal):
        self.ec = ExecCmd()
        self.umglobal = umglobal
        self.kernelArchitecture = self.umglobal.getKernelArchitecture()

        self.packagesInfo = []

        self.downgradablePackages = []
        self.kernelPackages = []
        self.upgradablePackages = []
        self.newPackages = []
        self.removedPackages = []
        self.heldbackPackages = []
        self.notavailablePackages = []
        self.orphanedPackages = []
Esempio n. 44
0
def getRemovablePackageName(theme):
    cmd = 'dpkg -S ' + theme + '.plymouth'
    log.write('Search package command: ' + cmd, 'drivers.getRemovablePackageName', 'debug')
    package = ''
    ec = ExecCmd(log)
    packageNames = ec.run(cmd, False)

    for line in packageNames:
        if avlThemesSearchstr in line:
            matchObj = re.search('(^.*):', line)
            if matchObj:
                package = matchObj.group(1)
                break
    log.write('Package found ' + package, 'drivers.getRemovablePackageName', 'debug')
    return package
Esempio n. 45
0
class DistroGeneral(object):
    def __init__(self, distroPath):
        self.ec = ExecCmd()
        distroPath = distroPath.rstrip('/')
        if basename(distroPath) == "root":
            distroPath = dirname(distroPath)
        self.distroPath = distroPath
        self.rootPath = join(distroPath, "root")

        self.edition = basename(distroPath)
        self.description = "SolydXK"
        infoPath = join(self.rootPath, "etc/solydxk/info")
        if exists(infoPath):
            self.edition = self.ec.run(
                cmd="grep EDITION= {} | cut -d'=' -f 2".format(infoPath),
                returnAsList=False).strip('"')
            self.description = self.ec.run(
                cmd="grep DESCRIPTION= {} | cut -d'=' -f 2".format(infoPath),
                returnAsList=False).strip('"')

    def getPlymouthTheme(self):
        plymouthTheme = ""
        if exists(join(self.rootPath,
                       "usr/share/plymouth/themes/solydk-logo")):
            plymouthTheme = "solydk-logo"
        elif exists(
                join(self.rootPath, "usr/share/plymouth/themes/solydx-logo")):
            plymouthTheme = "solydx-logo"
        return plymouthTheme

    def getIsoFileName(self):
        # Get the date string
        d = datetime.now()
        serial = d.strftime("%Y%m")
        # Check for a localized system
        localePath = join(self.rootPath, "etc/default/locale")
        if exists(localePath):
            locale = self.ec.run(cmd="grep LANG= {}".format(localePath),
                                 returnAsList=False).strip('"').replace(
                                     " ", "")
            matchObj = re.search("\=\s*([a-z]{2})", locale)
            if matchObj:
                language = matchObj.group(1)
                if language != "en":
                    serial += "_{}".format(language)
        isoFileName = "{}_{}.iso".format(
            self.description.lower().replace(' ', '_').split('-')[0], serial)
        return isoFileName
Esempio n. 46
0
class DistroGeneral(object):
    def __init__(self, distroPath):
        self.ec = ExecCmd()
        distroPath = distroPath.rstrip('/')
        if basename(distroPath) == "root":
            distroPath = dirname(distroPath)
        self.distroPath = distroPath
        self.rootPath = join(distroPath, "root")
        lsb_release_path = join(self.rootPath, "etc/lsb-release")
        self.edition = get_lsb_release_info('DISTRIB_CODENAME', lsb_release_path)
        self.description = get_lsb_release_info('DISTRIB_DESCRIPTION', lsb_release_path)
        if len(self.edition) == 0: self.edition = basename(distroPath)
        if len(self.description) == 0: self.description = basename(distroPath)

    def getIsoFileName(self):
        # Get the date string
        d = datetime.now()
        serial = d.strftime("%Y%m")
        # Check for a localized system
        localePath = join(self.rootPath, "etc/default/locale")
        if exists(localePath):
            locale = self.ec.run(cmd="grep LANG= '%s'" % localePath, returnAsList=False).strip('"').replace(" ", "")
            matchObj = re.search("\=\s*([a-z]{2})", locale)
            if matchObj:
                language = matchObj.group(1)
                if language != "en":
                    serial += "_{}".format(language)
        isoFileName = "{}_{}.iso".format(self.description.lower().replace(' ', '_').split('-')[0], serial)
        return isoFileName
Esempio n. 47
0
class Mirror():
    def __init__(self, log=None):
        self.log = log
        self.ec = ExecCmd()

    def save(self, replaceRepos):
        try:
            src = '/etc/apt/sources.list'
            if os.path.exists(src):
                dt = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                msg = _("Backup %(src)s to %(src)s.%(date)s") % { "src": src, "src": src, "date": dt }
                self.log.write(msg, "Mirror.save", "debug")
                os.system("cp -f %s %s.%s" % (src, src, dt))

                new_repos = []
                cmd = "cat %s" % src
                lstOut = self.ec.run(cmd, False)
                for line in lstOut:
                    line = str(unicode(line.strip(), 'ascii', 'ignore'))
                    if not line.startswith('#'):
                        for repo in replaceRepos:
                            if repo[0] in line:
                                line = line.replace(repo[0], repo[1])
                    new_repos.append(line)

                if new_repos:
                    f = open(src, 'w')
                    for repo in new_repos:
                        f.write("%s\n" % repo)
                        #print "%s\n" % repo
                    f.close()

        except Exception, detail:
            # This is a best-effort attempt, fail graciously
            self.log.write(str(detail), "Mirror.save", "exception")
Esempio n. 48
0
class MirrorGetSpeed(threading.Thread):
    def __init__(self, mirrors, queue, umglobal):
        threading.Thread.__init__(self)
        self.ec = ExecCmd()
        self.umglobal = umglobal
        self.mirrors = mirrors
        self.queue = queue

    def run(self):
        httpCode = -1
        dlSpeed = 0
        for mirrorData in self.mirrors:
            try:
                mirror = mirrorData[3].strip()
                if mirror.endswith('/'):
                    mirror = mirror[:-1]

                # Check Debian repository
                httpCode = -1
                dlSpeed = 0
                url = "%s/%s" % (mirror, self.umglobal.settings["dl-test"])
                cmd = "curl --connect-timeout %d -m %d -w '%%{http_code}\n%%{speed_download}\n' -o /dev/null -s http://%s" % (
                    int(self.umglobal.settings["timeout-secs"] / 2),
                    self.umglobal.settings["timeout-secs"], url)

                lst = self.ec.run(cmd, False)
                if lst:
                    httpCode = int(lst[0])
                    dlSpeed = lst[1]
                    # Download speed returns as string with decimal separator
                    # On non-US systems converting to float throws an error
                    # Split on the separator, and use the left part only
                    if ',' in dlSpeed:
                        dlSpeed = dlSpeed.split(',')[0]
                    elif '.' in dlSpeed:
                        dlSpeed = dlSpeed.split('.')[0]
                    dlSpeed = int(dlSpeed) / 1000

                    self.queue.put([mirror, "%d Kb/s" % dlSpeed])
                    print(("Server {0} - {1} Kb/s ({2})".format(
                        mirror, dlSpeed,
                        self.getHumanReadableHttpCode(httpCode))))

            except Exception as detail:
                # This is a best-effort attempt, fail graciously
                print(("Error: http code = {} / error = {}".format(
                    self.getHumanReadableHttpCode(httpCode), detail)))

    def getHumanReadableHttpCode(self, httpCode):
        if httpCode == 200:
            return "OK"
        elif httpCode == 403:
            return "403: forbidden"
        elif httpCode == 404:
            return "404: not found"
        elif httpCode >= 500:
            return "%d: server error" % httpCode
        else:
            return "Error: %d" % httpCode
Esempio n. 49
0
    def __init__(self):
        # Check if script is running
        self.scriptDir = abspath(dirname(__file__))
        self.filesDir = join(self.scriptDir, "files")
        self.scriptName = basename(__file__)
        self.umglobal = UmGlobal()
        self.ec = ExecCmd()

        # Handle arguments
        parser = argparse.ArgumentParser(
            description='Trail Update Manager Tray')
        parser.add_argument('-r', '--reload', action="store_true", help='')
        args, extra = parser.parse_known_args()

        print((">> args = {}".format(args)))
        if args.reload:
            pids = self.umglobal.getScriptPids("updatemanagertray.py")
            if len(pids) > 1:
                print(("updatemanagertray.py already running - kill pid {}".
                       format(pids[0])))
                os.system("kill {}".format(pids[0]))

        # Build status icon menu
        self.refreshText = _("Refresh")
        self.quitText = _("Quit")
        menu = Gtk.Menu()
        menuUm = Gtk.MenuItem(_("Update Manager"))
        menuUm.connect('activate', self.open_um)
        menu.append(menuUm)
        # Separator not functioning in wheezy
        #menuSep1 = Gtk.SeparatorMenuItem()
        #menu.append(menuSep1)
        menuPref = Gtk.MenuItem(_("Preferences"))
        menuPref.connect('activate', self.open_preferences)
        menu.append(menuPref)
        menuRefresh = Gtk.MenuItem(self.refreshText)
        menuRefresh.connect('activate', self.manualRefresh)
        menu.append(menuRefresh)
        menuQuit = Gtk.MenuItem(self.quitText)
        menuQuit.connect('activate', self.quit_tray)
        menu.append(menuQuit)

        self.statusIcon = Gtk.StatusIcon()
        self.umrefresh = UmRefresh(self.statusIcon, self.umglobal)
        self.notifier = UmNotifier(self.statusIcon, self.umglobal,
                                   self.umrefresh)

        self.statusIcon.connect('activate', self.icon_activate)
        self.statusIcon.connect('popup-menu', self.popup_menu, menu)

        # Initiate first check
        self.refresh()

        # Loop the refresh function
        # For some reason you cannot start a threaded class from init
        self.timeout = int(self.umglobal.settings["hrs-check-status"] * 60 *
                           60)
        GObject.timeout_add_seconds(self.timeout, self.refresh)
Esempio n. 50
0
    def __init__(self, distroPath):
        self.ec = ExecCmd()
        distroPath = distroPath.rstrip('/')
        if basename(distroPath) == "root":
            distroPath = dirname(distroPath)
        self.distroPath = distroPath
        self.rootPath = join(distroPath, "root")

        self.edition = basename(distroPath)
        self.description = "SolydXK"
        infoPath = join(self.rootPath, "etc/solydxk/info")
        if exists(infoPath):
            self.edition = self.ec.run(
                cmd="grep EDITION= {} | cut -d'=' -f 2".format(infoPath),
                returnAsList=False).strip('"')
            self.description = self.ec.run(
                cmd="grep DESCRIPTION= {} | cut -d'=' -f 2".format(infoPath),
                returnAsList=False).strip('"')
Esempio n. 51
0
 def __init__(self, statusIcon, umglobal):
     self.scriptDir = abspath(dirname(__file__))
     self.ec = ExecCmd()
     self.statusIcon = statusIcon
     self.umglobal = umglobal
     #self.apt = UmApt(self.umglobal)
     self.pbExec = GdkPixbuf.Pixbuf.new_from_file(
         self.umglobal.settings["icon-exec"])
     self.pbApply = GdkPixbuf.Pixbuf.new_from_file(
         self.umglobal.settings["icon-apply"])
     self.pbInfo = GdkPixbuf.Pixbuf.new_from_file(
         self.umglobal.settings["icon-info"])
     self.pbDisconnected = GdkPixbuf.Pixbuf.new_from_file(
         self.umglobal.settings["icon-disconnected"])
     self.pbError = GdkPixbuf.Pixbuf.new_from_file(
         self.umglobal.settings["icon-error"])
     self.counter = 0
     self.quit = False
Esempio n. 52
0
    def __init__(self, umglobal):
        self.ec = ExecCmd()
        self.umglobal = umglobal
        self.kernelArchitecture = self.umglobal.getKernelArchitecture()

        self.packagesInfo = []

        self.downgradablePackages = []
        self.kernelPackages = []
        self.upgradablePackages = []
        self.newPackages = []
        self.removedPackages = []
        self.heldbackPackages = []
        self.notavailablePackages = []
        self.orphanedPackages = []

        # --force-yes is deprecated in stretch
        self.force = self.umglobal.get_apt_force()
Esempio n. 53
0
    def __init__(self, collectData=True):
        # Get the settings
        self.scriptDir = abspath(dirname(__file__))
        self.filesDir = join(self.scriptDir, "files")
        self.shareDir = self.scriptDir.replace('lib', 'share')
        self.iconsDir = join(self.shareDir, 'icons')
        self.htmlDir = join(self.shareDir, "html")
        self.ec = ExecCmd()
        self.cfg = Config(join(self.filesDir, 'updatemanager.conf'))
        self.title = _("Update Manager")
        self.status = None
        self.isKf5 = False

        # Autostart
        self.autostartDir = '/etc/xdg/autostart'
        self.autostartFile = 'updatemanagertray.desktop'
        self.autostartSourceFile = join(self.filesDir, self.autostartFile)
        self.autostartDestFile = join(self.autostartDir, self.autostartFile)

        self.umfiles = {}
        self.umfiles['umupd'] = join(self.filesDir, ".umupd")
        self.umfiles['umrefresh'] = join(self.filesDir, ".umrefresh")
        self.umfiles['ummaintenance'] = join(self.filesDir, ".ummaintenance")
        self.umfiles['uminstallum'] = join(self.filesDir, ".uminstallum")

        # Status texts
        self.connectedText = _("Your system is up to date")
        self.disconnectedText = _("No internet connection")
        self.errorText = _("Error")
        self.executeText = _("Executing command")
        self.updatesText = _("There are updates available")
        self.warningText = _("Warning")

        # Variables
        self.localUpdVersion = None
        self.serverUpdVersion = None
        self.newUpd = False
        self.hasInternet = False
        self.repos = []

        # Set global variables
        if collectData:
            self.collectData()
Esempio n. 54
0
def getResolutions(minRes='', maxRes='', reverseOrder=False):
    cmd = 'xrandr'
    ec = ExecCmd(log)
    cmdList = ec.run(cmd, False)
    avlRes = []
    avlResTmp = []
    minW = 0
    minH = 0
    maxW = 0
    maxH = 0

    # Split the minimum and maximum resolutions
    if 'x' in minRes:
        minResList = minRes.split('x')
        minW = strToInt(minResList[0])
        minH = strToInt(minResList[1])
    if 'x' in maxRes:
        maxResList = maxRes.split('x')
        maxW = strToInt(maxResList[0])
        maxH = strToInt(maxResList[1])

    # Fill the list with screen resolutions
    for line in cmdList:
        for item in line.split():
            if item and 'x' in item and len(item) > 2 and not '+' in item and not 'axis' in item and not 'maximum' in item:
                log.write('Resolution found: ' + item, 'functions.getResolutions', 'debug')
                itemList = item.split('x')
                itemW = strToInt(itemList[0])
                itemH = strToInt(itemList[1])
                # Check if it can be added
                if itemW >= minW and itemH >= minH and (maxW == 0 or itemW <= maxW) and (maxH == 0 or itemH <= maxH):
                    log.write('Resolution added: ' + item, 'functions.getResolutions', 'debug')
                    avlResTmp.append([itemW, itemH])

    # Sort the list and return as readable resolution strings
    avlResTmp.sort(key=operator.itemgetter(0), reverse=reverseOrder)
    for res in avlResTmp:
        avlRes.append(str(res[0])  + 'x' + str(res[1]))
    return avlRes
Esempio n. 55
0
class Mirror():
    def __init__(self, log=None):
        self.log = log
        self.ec = ExecCmd()

    def save(self, replaceRepos):
        try:
            src = '/etc/apt/sources.list'
            if os.path.exists(src):
                dt = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                msg = "Backup %s to %s.%s" % (src, src, dt)
                self.log.writelines("%s\n" % msg)
                self.log.flush()
                print msg
                os.system("cp -f %s %s.%s" % (src, src, dt))

                new_repos = []
                cmd = "cat %s" % src
                lstOut = self.ec.run(cmd, False)
                for line in lstOut:
                    line = str(unicode(line.strip(), 'ascii', 'ignore'))
                    if not line.startswith('#'):
                        for repo in replaceRepos:
                            if repo[0] in line:
                                line = line.replace(repo[0], repo[1])
                    new_repos.append(line)

                if new_repos:
                    f = open(src, 'w')
                    for repo in new_repos:
                        f.write("%s\n" % repo)
                        #print "%s\n" % repo
                    f.close()

        except Exception, detail:
            # This is a best-effort attempt, fail graciously
            msg = "Mirror exception: %s" % detail
            self.log.writelines("%s\n" % msg)
            self.log.flush()
            print msg
Esempio n. 56
0
class UmApt(object):
    def __init__(self, umglobal):
        self.ec = ExecCmd()
        self.umglobal = umglobal
        self.kernelArchitecture = self.umglobal.getKernelArchitecture()

        self.packagesInfo = []

        self.downgradablePackages = []
        self.kernelPackages = []
        self.upgradablePackages = []
        self.newPackages = []
        self.removedPackages = []
        self.heldbackPackages = []
        self.notavailablePackages = []
        self.orphanedPackages = []

        # Build installed packages info list
        #self.createPackagesInfoList()

    def createPackagesInfoList(self):
        # Reset variables
        self.packagesInfo = []

        # Use env LANG=C to ensure the output of apt-show-versions is always en_US
        cmd = "env LANG=C bash -c 'apt-show-versions'"
        # Get the output of the command in a list
        lst = self.ec.run(cmd=cmd, realTime=False)

        # Loop through each line and fill the package lists
        for line in lst:
            items = line.split(" ")

            # Get package name
            if self.kernelArchitecture == "x86_64" and "i386" in items[0]:
                pck = items[0].split("/")[0]
            else:
                pck = items[0].split(":")[0]

            # In case your in Wheezy or older
            if "/" in pck:
                pck = pck.split("/")[0]
                ver = items[len(items) - 3]
            else:
                ver = items[1]

            # Get available version
            avVer = ''
            if "uptodate" in line:
                avVer = ver
            elif "upgradeable" in line:
                avVer = items[len(items) - 1]

            # Add info to list
            self.packagesInfo.append([pck, ver, avVer])

    def createPackageLists(self, customAptGetCommand=""):
        # Reset variables
        upgradablePackagesTmp = []
        heldbackPackagesTmp = []
        self.upgradablePackages = []
        self.newPackages = []
        self.removedPackages = []
        self.heldbackPackages = []

        # Create approriate command
        # Use env LANG=C to ensure the output of dist-upgrade is always en_US
        cmd = "env LANG=C bash -c 'apt-get dist-upgrade --assume-no'"
        #cmd = "env LANG=C bash -c 'apt-get upgrade --assume-no'"
        if "apt-get" in customAptGetCommand:
            customAptGetCommand = customAptGetCommand.replace(
                "--force-yes", "")
            customAptGetCommand = customAptGetCommand.replace(
                "--assume-yes", "")
            customAptGetCommand = customAptGetCommand.replace("--yes", "")
            customAptGetCommand = customAptGetCommand.replace("-y", "")
            cmd = "env LANG=C bash -c '%s --assume-no'" % customAptGetCommand

        # Get the output of the command in a list
        lst = self.ec.run(cmd=cmd, realTime=False)

        # Loop through each line and fill the package lists
        prevLine = None
        for line in lst:
            if line[0:1].strip() == "":
                if "removed:" in prevLine.lower():
                    self.fillPackageList(self.removedPackages, line.strip())
                elif "new packages" in prevLine.lower():
                    self.fillPackageList(self.newPackages, line.strip(), True)
                elif "kept back:" in prevLine.lower():
                    heldbackPackagesTmp.append(line.strip())
                elif "upgraded:" in prevLine.lower():
                    upgradablePackagesTmp.append(line.strip())
            else:
                prevLine = line

        # Create upgradable packages list without held back packages
        for pck in upgradablePackagesTmp:
            if pck not in heldbackPackagesTmp:
                self.fillPackageList(self.upgradablePackages, pck)

        # Create list with held back packages
        for pck in heldbackPackagesTmp:
            self.fillPackageList(self.heldbackPackages, pck)

    def initAptShowVersions(self):
        # Initialize or update package cache only
        cmd = "apt-show-versions -i"
        self.ec.run(cmd=cmd, realTime=False)

    def fillPackageList(self, packageList, line, new=False):
        packages = line.split(" ")
        for package in packages:
            package = package.strip().replace("*", "")
            if new:
                # We're not going to show version info for new packages
                packageList.append([package, "", ""])
            else:
                for info in self.packagesInfo:
                    if package == info[0] or "%s:i386" % package == info[0]:
                        packageList.append(info)
                        break

    def fillNotAvailablePackages(self):
        self.notavailablePackages = []
        # Use env LANG=C to ensure the output of apt-show-versions is always en_US
        cmd = "env LANG=C bash -c 'apt-show-versions' | grep 'available'"
        # Get the output of the command in a list
        lst = self.ec.run(cmd=cmd, realTime=False)

        # Loop through each line and fill the package lists
        for line in lst:
            items = line.split(" ")
            pck = items[0].split(":")[0]
            if pck != "updatemanager":
                if self.kernelArchitecture == "x86_64" and "i386" in items[0]:
                    pck = items[0].split("/")[0]
                ver = items[1]
                avVer = ""
                self.notavailablePackages.append([pck, ver, avVer])

    def fillDowngradablePackages(self):
        self.downgradablePackages = []
        # Use env LANG=C to ensure the output of apt-show-versions is always en_US
        cmd = "env LANG=C bash -c 'apt-show-versions' | grep 'newer'"
        # Get the output of the command in a list
        lst = self.ec.run(cmd=cmd, realTime=False)

        # Loop through each line and fill the package lists
        for line in lst:
            items = line.split(" ")
            pck = items[0].split(":")[0]
            if pck != "updatemanager":
                if self.kernelArchitecture == "x86_64" and "i386" in items[0]:
                    pck = items[0].split("/")[0]
                ver = items[1]
                avVer = self.getDowngradablePackageVersion(pck)
                if ver != avVer:
                    self.downgradablePackages.append([pck, ver, avVer])

    def fillKernelPackages(self):
        self.kernelPackages = []
        # Use env LANG=C to ensure the output of apt-show-versions is always en_US
        cmd = "env LANG=C bash -c 'apt-show-versions | grep ^linux-'"
        # Get the output of the command in a list
        lst = self.ec.run(cmd=cmd, realTime=False)

        # Loop through each line and fill the package lists
        for line in lst:
            items = line.split(" ")
            pck = items[0].split(":")[0]
            if "-image-" in pck \
            or "-headers-" in pck \
            or "-kbuild-" in pck:
                self.kernelPackages.append([pck, items[1], ""])

    def fillOrphanedPackages(self):
        self.orphanedPackages = []
        # Use env LANG=C to ensure the output of apt-show-versions is always en_US
        cmd = "env LANG=C bash -c 'deborphan'"
        # Get the output of the command in a list
        lst = self.ec.run(cmd=cmd, realTime=False)

        # Loop through each line and fill the package lists
        for line in lst:
            pck = line.split(":")[0]
            if pck != "updatemanager":
                if self.kernelArchitecture == "x86_64" and "i386" in line:
                    pck = line
                ver = ""
                avVer = ""
                for info in self.packagesInfo:
                    if pck == info[0]:
                        ver = info[1]
                        avVer = info[2]
                self.orphanedPackages.append([pck, ver, avVer])

    # Get the package version number
    def getDowngradablePackageVersion(self, package):
        cmd = "env LANG=C bash -c 'apt-cache show %s | grep \"^Version:\" | cut -d\" \" -f 2'" % package
        lst = self.ec.run(cmd, realTime=False)
        if len(lst) > 1:
            return lst[1]
        else:
            return lst[0]

    def getPackageVersion(self, package, candidate=False):
        cmd = "env LANG=C bash -c 'apt-cache policy %s | grep \"Installed:\"'" % package
        if candidate:
            cmd = "env LANG=C bash -c 'apt-cache policy %s | grep \"Candidate:\"'" % package
        #lst = self.ec.run(cmd, realTime=False)[0].strip().split(' ')
        #return lst[-1]
        return "1.0"

    def aptHasErrors(self):
        ret = self.ec.run("apt-get --assume-no upgrade", False, False)
        if ret[0:2].upper() == "E:":
            return ret
        return None

    def getAptCacheLockedProgram(self, aptPackages):
        procLst = self.ec.run("ps -U root -u root -o comm=", False)
        for aptProc in aptPackages:
            if aptProc in procLst:
                return aptProc
        return None

    def cleanCache(self, safe=True):
        cmd = "apt-get --yes --force-yes autoclean"
        if not safe:
            cmd = "apt-get --yes --force-yes clean"
        self.ec.run(cmd, realTime=False)
Esempio n. 57
0
class Broadcom():
    def __init__(self, distribution, loggerObject):
        self.distribution = distribution.lower()
        self.log = loggerObject
        self.ec = ExecCmd(self.log)
        self.status = ''
        self.currentChip = ''
        self.installableChip = ''
        self.installableDriver = ''
        self.hw = ''
    
    # Called from drivers.py: Check for Broadcom
    def getBroadcom(self):
        hwList = []
        self.setCurrentChipInfo()
        if self.currentChip != '':
            if self.installableChip != '':
                self.log.write('Broadcom chip serie found: ' + self.installableChip, 'broadcom.getBroadcom', 'info')
                hwList.append([self.hw, hwCodes[2], self.status])
            else:
                # Broadcom was found, but no supported chip set: return uninstallable
                self.log.write('Broadcom chip serie not supported: ' + self.currentChip, 'broadcom.getBroadcom', 'warning')
                hwList.append([self.hw, hwCodes[2], packageStatus[2]])
                        
        return hwList
    
    # Check for Broadcom chip set and set variables
    def setCurrentChipInfo(self):
        hwList = []
        self.currentChip = ''
        self.installableDriver = ''
        self.status = ''
        
        # Get Broadcom info
        cmdBc = 'lspci -vnn -d 14e4:'
        hwBc = self.ec.run(cmdBc)
        for line in hwBc:
            self.hw = line[line.find(': ') + 2:]
            self.log.write('Broadcom found: ' + self.hw, 'broadcom.setCurrentChipInfo', 'info')
            if hwCodes[2] in self.hw.lower():
                # Get the chip set number
                chipSet = re.search('14e4:(.*)]', self.hw)
                if chipSet:
                    self.currentChip = chipSet.group(1)
                    self.log.write('Broadcom chip set found: ' + self.currentChip, 'broadcom.setCurrentChipInfo', 'debug')
                    for chipList in bcChips:
                        if self.currentChip == chipList[0]:
                            # Supported chipset found: set variables
                            self.log.write('Broadcom chip set driver: ' + chipList[1], 'broadcom.setCurrentChipInfo', 'debug')
                            self.installableChip = chipList[0]
                            self.installableDriver = chipList[1]
                            self.status = functions.getPackageStatus(chipList[1])
                            break
            if self.installableChip != '':
                # Don't look further if you already found an installable chip set
                break
            else:
                self.log.write('Broadcom chip set not supported: ' + self.hw, 'broadcom.setCurrentChipInfo', 'error')
    
    # Install the broadcom drivers
    def installBroadcom(self):
        try:
            self.setCurrentChipInfo()
            if self.installableDriver != '':
                # Get the correct linux header package
                linHeader = self.ec.run("echo linux-headers-$(uname -r|sed 's,[^-]*-[^-]*-,,')", False)
                self.log.write('Linux header name to install: ' + linHeader[0], 'broadcom.installBroadcom', 'info')
                
                # Only install linux header if it is not installed
                status = functions.getPackageStatus(linHeader[0])
                if status == packageStatus[1]:
                    self.log.write('Download package: ' + linHeader, 'broadcom.installBroadcom', 'info')
                    self.ec.run('apt-get download ' + linHeader)
                    
                # Download the driver
                cmdBc = 'apt-get download ' + self.installableDriver
                self.log.write('Download package: ' + self.installableDriver, 'broadcom.installBroadcom', 'info')
                self.ec.run(cmdBc)
                
                # Remove any module that might be in the way
                self.log.write('modprobe b44, b43, b43legacy, ssb, brcmsmac', 'broadcom.installBroadcom', 'debug')
                os.system('modprobe -rf b44')
                os.system('modprobe -rf b43')
                os.system('modprobe -rf b43legacy')
                os.system('modprobe -rf ssb')
                os.system('modprobe -rf brcmsmac')
                
                # Install the dowloaded packages
                self.log.write('Install downloaded packages', 'broadcom.installBroadcom', 'info')
                self.ec.run('dpkg -i *.deb')
                # Delete the downloaded packages
                self.log.write('Remove downloaded debs', 'broadcom.installBroadcom', 'debug')
                os.system('rm -f *.deb')
                
                # Finish up
                if self.installableDriver == 'broadcom-sta-dkms':
                    # Blacklist b43, brcmsmac
                    self.log.write('blacklist b43 brcmsmac bcma', 'broadcom.installBroadcom', 'debug')
                    modFile = open(blacklistPath, 'w')
                    modFile.write('blacklist b43 brcmsmac')
                    modFile.close()
                    # Start wl
                    self.log.write('modprobe wl', 'broadcom.installBroadcom', 'debug')
                    os.system('modprobe wl')
                elif 'b43' in self.installableDriver:
                    # Start b43
                    self.log.write('modprobe b43', 'broadcom.installBroadcom', 'debug')
                    os.system('modprobe b43')
                else:
                    # Start brcmsmac
                    self.log.write('modprobe brcmsmac', 'broadcom.installBroadcom', 'debug')
                    os.system('modprobe brcmsmac')
            else:
                self.log.write('No Broadcom chip set found', 'broadcom.installBroadcom', 'error')
                
        except Exception, detail:
            self.log.write(detail, 'broadcom.installBroadcom', 'exception')
Esempio n. 58
0
    def __init__(self):
        # Check if script is running
        self.scriptName = basename(__file__)
        self.umglobal = UmGlobal()

        # Handle arguments
        parser = argparse.ArgumentParser(
            description='SolydXK Update Manager Preferences')
        parser.add_argument('-r', '--reload', action="store_true", help='')
        args, extra = parser.parse_known_args()

        print(("args = {}".format(args)))
        if args.reload:
            pids = self.umglobal.getProcessPids("updatemanagerpref.py")
            if len(pids) > 1:
                print(("updatemanagerpref.py already running - kill pid {}".
                       format(pids[0])))
                os.system("kill {}".format(pids[0]))

        # Initiate logging
        self.logFile = join('/var/log', self.umglobal.settings['log'])
        self.log = Logger(self.logFile)

        # Load window and widgets
        self.builder = Gtk.Builder()
        self.builder.add_from_file(
            join(self.umglobal.shareDir, 'updatemanagerpref.glade'))

        # Preferences window objects
        go = self.builder.get_object
        self.window = go("windowPref")
        self.nbPref = go('nbPref')
        self.btnSaveMirrors = go('btnSaveMirrors')
        self.btnCheckMirrorsSpeed = go("btnCheckMirrorsSpeed")
        self.lblMirrors = go('lblMirrors')
        self.tvMirrors = go("tvMirrors")
        self.btnRemoveBlackList = go("btnRemoveBlacklist")
        self.btnAddBlackList = go("btnAddBlacklist")
        self.tvBlacklist = go("tvBlacklist")
        self.tvAvailable = go("tvAvailable")
        self.lblGeneral = go("lblGeneral")
        self.btnSaveGeneral = go("btnSaveGeneral")
        self.chkHideMaintenance = go("chkHideMaintenance")
        self.chkAutostart = go("chkAutostart")

        # GUI translations
        self.window.set_title(_("Update Manager Preferences"))
        self.btnSaveMirrors.set_label(_("Save mirrors"))
        self.btnCheckMirrorsSpeed.set_label(_("Check mirrors speed"))
        self.btnRemoveBlackList.set_label(_("Remove"))
        self.btnAddBlackList.set_label(_("Blacklist"))
        self.lblMirrors.set_label(_("Repository mirrors"))
        self.lblGeneral.set_label(_("General"))
        go("lblHideMaintenance").set_label(_("Hide maintenance"))
        go("lblBlacklist").set_label(_("Blacklisted packages"))
        go("lblMirrorsText").set_label(_("Select the fastest repository"))
        go("lblBlacklistText").set_label(_("Blacklisted packages"))
        go("lblAvailableText").set_label(_("Available packages"))
        go("lblGlobalSettings").set_label(_("Global settings"))

        # Initiate the treeview handler and connect the custom toggle event with on_tvMirrors_toggle
        self.tvMirrorsHandler = TreeViewHandler(self.tvMirrors)
        self.tvMirrorsHandler.connect('checkbox-toggled',
                                      self.on_tvMirrors_toggle)

        self.tvBlacklistHandler = TreeViewHandler(self.tvBlacklist)
        self.tvAvailableHandler = TreeViewHandler(self.tvAvailable)

        # Initialize
        self.ec = ExecCmd(loggerObject=self.log)
        self.queue = Queue()
        self.excludeMirrors = ['security', 'community']
        self.activeMirrors = self.umglobal.getMirrorData(
            excludeMirrors=self.excludeMirrors)
        self.deadMirrors = self.umglobal.getMirrorData(getDeadMirrors=True)
        self.mirrors = self.getMirrors()
        self.threads = {}
        self.blacklist = []
        self.available = []

        self.fillGeneralSettings()
        self.fillTreeViewMirrors()
        self.fillTreeViewBlackList()
        self.fillTreeViewAvailable()

        # Connect the signals and show the window
        self.builder.connect_signals(self)
        self.window.show()