コード例 #1
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 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
コード例 #2
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
コード例 #3
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')
コード例 #4
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')
コード例 #5
0
ファイル: functions.py プロジェクト: 0rakul/updatemanager
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
コード例 #6
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
コード例 #7
0
ファイル: functions.py プロジェクト: 0rakul/updatemanager
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
コード例 #8
0
ファイル: mirror.py プロジェクト: 0rakul/updatemanager
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")
コード例 #9
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
コード例 #10
0
def getCurrentTheme():
    curTheme = ['']
    if getCurrentResolution() != '':
        cmd = '/usr/sbin/plymouth-set-default-theme'
        ec = ExecCmd(log)
        curTheme = ec.run(cmd, False)
    return curTheme[0]
コード例 #11
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]
コード例 #12
0
def getCurrentTheme():
    curTheme = ['']
    if getCurrentResolution() != '':
        cmd = '/usr/sbin/plymouth-set-default-theme'
        ec = ExecCmd(log)
        curTheme = ec.run(cmd, False)
    return curTheme[0]
コード例 #13
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
コード例 #14
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
コード例 #15
0
ファイル: functions.py プロジェクト: 0rakul/updatemanager
def killProcessByName(processName):
    killed = False
    ec = ExecCmd(log)
    lst = ec.run('killall %s' % processName)
    if len(lst) == 0:
        killed = True
    return killed
コード例 #16
0
ファイル: mirror.py プロジェクト: ruibarreira/updatemanager
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
コード例 #17
0
ファイル: functions.py プロジェクト: 0rakul/updatemanager
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
コード例 #18
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')
コード例 #19
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
コード例 #20
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
コード例 #21
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')
コード例 #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')
コード例 #23
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
コード例 #24
0
ファイル: functions.py プロジェクト: 0rakul/updatemanager
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
コード例 #25
0
ファイル: functions.py プロジェクト: 0rakul/updatemanager
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
コード例 #26
0
ファイル: functions.py プロジェクト: 0rakul/updatemanager
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
コード例 #27
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
コード例 #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')
コード例 #29
0
ファイル: functions.py プロジェクト: 0rakul/updatemanager
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
コード例 #30
0
ファイル: functions.py プロジェクト: 0rakul/updatemanager
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
コード例 #31
0
ファイル: mirror.py プロジェクト: ruibarreira/updatemanager
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
コード例 #32
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
コード例 #33
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
コード例 #34
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
コード例 #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
コード例 #36
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')
コード例 #37
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
コード例 #38
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
コード例 #39
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
コード例 #40
0
ファイル: mirror.py プロジェクト: NaglayaMorda/updatemanager
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
コード例 #41
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
コード例 #42
0
class UpdateManagerPref(object):
    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()

    # ===============================================
    # Main window functions
    # ===============================================

    def on_btnSaveGeneral_clicked(self, widget):
        self.saveGeneralSettings()

    def on_btnCheckMirrorsSpeed_clicked(self, widget):
        self.checkMirrorsSpeed()

    def on_btnSaveMirrors_clicked(self, widget):
        self.saveMirrors()

    def on_btnCancel_clicked(self, widget):
        self.window.destroy()

    def on_btnRemoveBlacklist_clicked(self, widget):
        self.removeBlacklist()

    def on_btnAddBlacklist_clicked(self, widget):
        self.addBlacklist()

    # ===============================================
    # Blacklist functions
    # ===============================================

    def fillGeneralSettings(self):
        for tab in self.umglobal.settings["hide-tabs"]:
            if tab == "maintenance":
                self.chkHideMaintenance.set_active(True)
        self.chkAutostart.set_active(self.umglobal.settings["autostart"])

    def fillTreeViewBlackList(self):
        self.blacklist = []
        cmd = "env LANG=C dpkg --get-selections | grep hold$ | awk '{print $1}'"
        lst = self.ec.run(cmd, False)
        for pck in lst:
            self.blacklist.append([False, pck.strip()])
        # Fill treeview
        columnTypesList = ['bool', 'str']
        self.tvBlacklistHandler.fillTreeview(self.blacklist, columnTypesList,
                                             0, 400, False)

    def fillTreeViewAvailable(self):
        self.available = []
        cmd = "env LANG=C dpkg --get-selections | grep install$ | awk '{print $1}'"
        lst = self.ec.run(cmd, False)
        for pck in lst:
            self.available.append([False, pck.strip()])
        # Fill treeview
        columnTypesList = ['bool', 'str']
        self.tvAvailableHandler.fillTreeview(self.available, columnTypesList,
                                             0, 400, False)

    def addBlacklist(self):
        packages = self.tvAvailableHandler.getToggledValues()
        for pck in packages:
            self.log.write("Blacklist package: %s" % pck,
                           "UMPref.addBlacklist", "debug")
            cmd = "echo '%s hold' | dpkg --set-selections" % pck
            system(cmd)
        self.fillTreeViewBlackList()
        self.fillTreeViewAvailable()

    def removeBlacklist(self):
        packages = self.tvBlacklistHandler.getToggledValues()
        for pck in packages:
            self.log.write("Remove package from blacklist: %s" % pck,
                           "UMPref.removeBlacklist", "debug")
            cmd = "echo '%s install' | dpkg --set-selections" % pck
            system(cmd)
        self.fillTreeViewBlackList()
        self.fillTreeViewAvailable()

    # ===============================================
    # Mirror functions
    # ===============================================

    def fillTreeViewMirrors(self):
        # Fill mirror list
        if len(self.mirrors) > 1:
            # Fill treeview
            columnTypesList = ['bool', 'str', 'str', 'str', 'str']
            self.tvMirrorsHandler.fillTreeview(self.mirrors, columnTypesList,
                                               0, 400, True)

            # TODO - We have no mirrors: hide the tab until we do
            #self.nbPref.get_nth_page(1).set_visible(False)
        else:
            self.nbPref.get_nth_page(1).set_visible(False)

    def saveMirrors(self):
        # Safe mirror settings
        replaceRepos = []
        # Get user selected mirrors
        model = self.tvMirrors.get_model()
        itr = model.get_iter_first()
        while itr is not None:
            sel = model.get_value(itr, 0)
            if sel:
                repo = model.get_value(itr, 2)
                url = model.get_value(itr, 3)
                not_changed = ''
                # Get currently selected data
                for mirror in self.mirrors:
                    if mirror[0] and mirror[2] == repo:
                        if mirror[3] != url:
                            # Currently selected mirror
                            replaceRepos.append([mirror[3], url])
                        else:
                            not_changed = url
                        break
                if url not in replaceRepos and url not in not_changed:
                    # Append the repositoriy to the sources file
                    replaceRepos.append(['', url])
            itr = model.iter_next(itr)

        if not replaceRepos:
            # Check for dead mirrors
            model = self.tvMirrors.get_model()
            itr = model.get_iter_first()
            while itr is not None:
                sel = model.get_value(itr, 0)
                if sel:
                    repo = model.get_value(itr, 2)
                    url = model.get_value(itr, 3)
                    # Get currently selected data
                    for mirror in self.deadMirrors:
                        if mirror[1] == repo and mirror[2] != url:
                            # Currently selected mirror
                            replaceRepos.append([mirror[2], url])
                            break
                itr = model.iter_next(itr)

        if replaceRepos:
            self.btnSaveMirrors.set_sensitive(False)
            self.btnCheckMirrorsSpeed.set_sensitive(False)

            m = Mirror()
            ret = m.save(replaceRepos, self.excludeMirrors)
            if ret == '':
                self.ec.run(cmd="apt-get update",
                            outputTreeView=self.tvMirrors)
                self.umglobal.getLocalInfo()
                self.mirrors = self.getMirrors()
                self.fillTreeViewMirrors()
            else:
                self.log.write(ret, "UMPref.saveMirrors", "exception")

            self.btnSaveMirrors.set_sensitive(True)
            self.btnCheckMirrorsSpeed.set_sensitive(True)
        else:
            msg = _("There are no repositories to save.")
            MessageDialog(self.lblMirrors.get_label(), msg)

    def getMirrors(self):
        mirrors = [[
            _("Current"),
            _("Country"),
            _("Repository"),
            _("URL"),
            _("Speed")
        ]]
        for mirror in self.activeMirrors:
            if mirror:
                self.log.write("Mirror data: %s" % ' '.join(mirror),
                               "UMPref.getMirrors", "debug")
                blnCurrent = self.isUrlInSources(mirror[2])
                mirrors.append(
                    [blnCurrent, mirror[0], mirror[1], mirror[2], ''])
        return mirrors

    def isUrlInSources(self, url):
        url = "://%s" % url
        blnRet = False

        for repo in self.umglobal.repos:
            if url in repo:
                blnRet = True
                for excl in self.excludeMirrors:
                    if excl in repo:
                        blnRet = False
                        break
                break
        return blnRet

    def checkMirrorsSpeed(self):
        name = 'mirrorspeed'
        self.btnCheckMirrorsSpeed.set_sensitive(False)
        self.btnSaveMirrors.set_sensitive(False)
        t = MirrorGetSpeed(self.mirrors, self.queue, self.umglobal)
        self.threads[name] = t
        t.daemon = True
        t.start()
        self.queue.join()
        GObject.timeout_add(5, self.checkThread, name)

    def checkThread(self, name):
        if self.threads[name].is_alive():
            lst = self.queue.get()
            if lst:
                self.writeSpeed(lst[0], lst[1])
            self.queue.task_done()
            return True

        # Thread is done
        if not self.queue.empty():
            lst = self.queue.get()
            if lst:
                self.writeSpeed(lst[0], lst[1])
            self.queue.task_done()
        del self.threads[name]
        self.btnCheckMirrorsSpeed.set_sensitive(True)
        self.btnSaveMirrors.set_sensitive(True)
        return False

    def writeSpeed(self, url, speed):
        model = self.tvMirrors.get_model()
        itr = model.get_iter_first()
        while itr is not None:
            repo = model.get_value(itr, 3)
            if repo == url:
                self.log.write("Mirror speed for %s = %s" % (url, speed),
                               "UMPref.writeSpeed", "debug")
                model.set_value(itr, 4, speed)
                path = model.get_path(itr)
                self.tvMirrors.scroll_to_cell(path)
            itr = model.iter_next(itr)
        self.tvMirrors.set_model(model)
        # Repaint GUI, or the update won't show
        while Gtk.events_pending():
            Gtk.main_iteration()

    def on_tvMirrors_toggle(self, obj, path, colNr, toggleValue):
        path = int(path)
        model = self.tvMirrors.get_model()
        selectedIter = model.get_iter(path)
        selectedRepo = model.get_value(selectedIter, 2)

        rowCnt = 0
        itr = model.get_iter_first()
        while itr is not None:
            if rowCnt != path:
                repo = model.get_value(itr, 2)
                if repo == selectedRepo:
                    model[itr][0] = False
            itr = model.iter_next(itr)
            rowCnt += 1

    # ===============================================
    # General functions
    # ===============================================

    def saveGeneralSettings(self):
        lst = []
        for tab in self.umglobal.settings["hide-tabs"]:
            if tab != "maintenance":
                lst.append(tab)
        if self.chkHideMaintenance.get_active():
            lst.append("maintenance")
        if lst:
            self.umglobal.saveSettings('misc', 'hide-tabs', ",".join(lst))
        else:
            self.umglobal.saveSettings('misc', 'hide-tabs', "")

        # Automatically start updatemanager on boot
        autostart = self.chkAutostart.get_active()
        self.umglobal.settings["autostart"] = autostart
        if autostart:
            if exists(self.umglobal.autostartSourceFile) and \
               exists(self.umglobal.autostartDir):
                copy(self.umglobal.autostartSourceFile,
                     self.umglobal.autostartDir)
        elif exists(self.umglobal.autostartDestFile):
            remove(self.umglobal.autostartDestFile)

        msg = _("The new settings will take effect after UM restart.")
        MessageDialog(self.lblGeneral.get_label(), msg)

    # Close the gui
    def on_windowPref_destroy(self, widget):
        Gtk.main_quit()
コード例 #43
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')
コード例 #44
0
class InstallThread(threading.Thread):

    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"

    def run(self):

        try:
            self.log.writelines("++ Install requested by user\n")
            self.log.flush()
            gtk.gdk.threads_enter()
            self.window.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
            self.window.set_sensitive(False)
            installNeeded = False
            packages = []
            model = self.treeView.get_model()
            gtk.gdk.threads_leave()

            itr = model.get_iter_first()
            history = open("/var/log/updatemanager.history", "a")
            while (itr is not None):
                checked = model.get_value(itr, INDEX_UPGRADE)
                if (checked == "true"):
                    installNeeded = True
                    package = model.get_value(itr, INDEX_PACKAGE_NAME)
                    oldVersion = model.get_value(itr, INDEX_OLD_VERSION)
                    newVersion = model.get_value(itr, INDEX_NEW_VERSION)
                    history.write(commands.getoutput('date +"%Y.%m.%d %H:%M:%S"') + "\t" + package + "\t" + oldVersion + "\t" + newVersion + "\n")
                    packages.append(package)
                    self.log.writelines("++ Will install " + str(package) + "\n")
                    self.log.flush()
                itr = model.iter_next(itr)
            history.close()

            if installNeeded:

                proceed = True
                try:
                    pkgs = ' '.join(str(pkg) for pkg in packages)
                    warnings = commands.getoutput(self.curdir + "/checkWarnings.py %s" % pkgs)
                    #print (curdir + "/checkWarnings.py %s" % pkgs)
                    warnings = warnings.split("###")
                    if len(warnings) == 2:
                        installations = warnings[0].split()
                        removals = warnings[1].split()
                        if len(installations) > 0 or len(removals) > 0:
                            gtk.gdk.threads_enter()
                            try:
                                dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK_CANCEL, None)
                                dialog.log.set_title("")
                                dialog.log.set_markup("<b>" + _("This upgrade will trigger additional changes") + "</b>")
                                #dialog.log.format_secondary_markup("<i>" + _("All available upgrades for this package will be ignored.") + "</i>")
                                dialog.log.set_icon_from_file(self.prefs["icon_busy"])
                                dialog.log.set_default_size(640, 480)

                                if len(removals) > 0:
                                    # Removals
                                    label = gtk.Label()
                                    if len(removals) == 1:
                                        label.set_text(_("The following package will be removed:"))
                                    else:
                                        label.set_text(_("The following %d packages will be removed:") % len(removals))
                                    label.set_alignment(0, 0.5)
                                    scrolledWindow = gtk.ScrolledWindow()
                                    scrolledWindow.set_shadow_type(gtk.SHADOW_IN)
                                    scrolledWindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
                                    treeview = gtk.TreeView()
                                    column1 = gtk.TreeViewColumn("", gtk.CellRendererText(), text=0)
                                    column1.set_sort_column_id(0)
                                    column1.set_resizable(True)
                                    treeview.append_column(column1)
                                    treeview.set_headers_clickable(False)
                                    treeview.set_reorderable(False)
                                    treeview.set_headers_visible(False)
                                    model = gtk.TreeStore(str)
                                    removals.sort()
                                    for pkg in removals:
                                        itr = model.insert_before(None, None)
                                        model.set_value(itr, 0, pkg)
                                    treeview.set_model(model)
                                    treeview.show()
                                    scrolledWindow.add(treeview)
                                    dialog.log.vbox.add(label)
                                    dialog.log.vbox.add(scrolledWindow)

                                if len(installations) > 0:
                                    # Installations
                                    label = gtk.Label()
                                    if len(installations) == 1:
                                        label.set_text(_("The following package will be installed:"))
                                    else:
                                        label.set_text(_("The following %d packages will be installed:") % len(installations))
                                    label.set_alignment(0, 0.5)
                                    scrolledWindow = gtk.ScrolledWindow()
                                    scrolledWindow.set_shadow_type(gtk.SHADOW_IN)
                                    scrolledWindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
                                    treeview = gtk.TreeView()
                                    column1 = gtk.TreeViewColumn("", gtk.CellRendererText(), text=0)
                                    column1.set_sort_column_id(0)
                                    column1.set_resizable(True)
                                    treeview.append_column(column1)
                                    treeview.set_headers_clickable(False)
                                    treeview.set_reorderable(False)
                                    treeview.set_headers_visible(False)
                                    model = gtk.TreeStore(str)
                                    installations.sort()
                                    for pkg in installations:
                                        itr = model.insert_before(None, None)
                                        model.set_value(itr, 0, pkg)
                                    treeview.set_model(model)
                                    treeview.show()
                                    scrolledWindow.add(treeview)
                                    dialog.vbox.add(label)
                                    dialog.vbox.add(scrolledWindow)

                                dialog.show_all()
                                if dialog.run() == gtk.RESPONSE_OK:
                                    proceed = True
                                else:
                                    proceed = False
                                dialog.destroy()
                            except Exception, detail:
                                print detail
                            gtk.gdk.threads_leave()
                        else:
                            proceed = True
                except Exception, details:
                    print details

                if proceed:
                    gtk.gdk.threads_enter()
                    self.statusIcon.set_from_file(self.prefs["icon_apply"])
                    self.statusIcon.set_tooltip(_("Installing updates"))
                    gtk.gdk.threads_leave()

                    # Check for pre-install script and execute if it exists
                    if self.newUpVersion is not None:
                        preScript = os.path.join(self.curdir, self.newUpVersion + '.pre')
                        if os.path.exists(preScript):
                            cmd = ". %s" % preScript
                            retList = self.ec.run(cmd)
                            #comnd = Popen(' ' + preScript, stdout=self.log, stderr=self.log, shell=True)
                            #returnCode = comnd.wait()
                            self.log.writelines("++ Pre-install script finished\n")

                    self.log.writelines("++ Ready to launch synaptic\n")
                    self.log.flush()
                    cmd = ["sudo", "/usr/sbin/synaptic", "--hide-main-window",
                            "--non-interactive", "--parent-window-id", "%s" % self.window.window.xid]
                    cmd.append("-o")
                    cmd.append("Synaptic::closeZvt=true")
                    cmd.append("--progress-str")
                    cmd.append("\"" + _("Please wait, this can take some time") + "\"")
                    cmd.append("--finish-str")
                    cmd.append("\"" + _("Update is complete") + "\"")
                    f = tempfile.NamedTemporaryFile()

                    for pkg in packages:
                        f.write("%s\tinstall\n" % pkg)
                    cmd.append("--set-selections-file")
                    cmd.append("%s" % f.name)
                    f.flush()
                    comnd = Popen(' '.join(cmd), stdout=self.log, stderr=self.log, shell=True)
                    returnCode = comnd.wait()
                    self.log.writelines("++ Return code:" + str(returnCode) + "\n")
                    #sts = os.waitpid(comnd.pid, 0)
                    f.close()

                    # Check for post install script and execute if it exists
                    if self.newUpVersion is not None:
                        postScript = os.path.join(self.curdir, self.newUpVersion + '.post')
                        if os.path.exists(postScript):
                            cmd = ". %s" % postScript
                            retList = self.ec.run(cmd)
                            #comnd = Popen(' ' + postScript, stdout=self.log, stderr=self.log, shell=True)
                            #returnCode = comnd.wait()
                            self.log.writelines("++ Post-install script finished\n")

                    self.log.writelines("++ Install finished\n")
                    self.log.flush()

                    gtk.gdk.threads_enter()

                    self.window.hide()
                    gtk.gdk.threads_leave()

                    if ("updatemanager" in packages):
                        # Restart
                        try:
                            self.log.writelines("++ updatemanager was updated, restarting it in root mode...\n")
                            self.log.flush()
                            self.log.close()
                        except:
                            pass    # cause we might have closed it already
                        os.system("gksudo --message \"" + _("Please enter your password to restart the update manager") + "\" " + self.curdir + "/updatemanager.py show &")
                    else:
                        # Refresh
                        gtk.gdk.threads_enter()
                        self.statusIcon.set_from_file(self.prefs["icon_busy"])
                        self.statusIcon.set_tooltip(_("Checking for updates"))
                        self.window.window.set_cursor(None)
                        self.window.set_sensitive(True)
                        gtk.gdk.threads_leave()
                        refresh = RefreshThread(self.treeView, self.statusIcon, self.builder, self.prefs, self.log, True)
                        refresh.start()
                else:
                    # Stop the blinking but don't refresh
                    gtk.gdk.threads_enter()
                    self.window.window.set_cursor(None)
                    self.window.set_sensitive(True)
                    gtk.gdk.threads_leave()
            else:
コード例 #45
0
class Conky(object):

    def __init__(self):
        self.scriptDir = abspath(dirname(__file__))

        # Load window and widgets
        self.builder = Gtk.Builder()
        self.builder.add_from_file(join(self.scriptDir, '../../../share/solydxk/conky/conky.glade'))

        go = self.builder.get_object
        self.window = go('conkyWindow')
        self.ebTitle = go('ebTitle')
        self.lblTitle = go('lblTitle')
        self.lblMenuTitle = go('lblMenuTitle')
        self.statusbar = go('statusbar')
        self.ebMenu = go('ebMenu')
        self.ebMenuPreferences = go('ebMenuPreferences')
        self.lblMenuPreferences = go('lblMenuPreferences')
        self.ebMenuNetwork = go('ebMenuNetwork')
        self.lblMenuNetwork = go('lblMenuNetwork')
        self.ebMenuSystem = go('ebMenuSystem')
        self.lblMenuSystem = go('lblMenuSystem')
        self.nbConky = go('nbConky')
        self.btnSave = go('btnSave')

        # Preferences objects
        self.lblPrefAction = go('lblPrefAction')
        self.cmbPrefAction = go('cmbPrefAction')
        self.lsAction = go('lsAction')
        self.btnPrefActionApply = go('btnPrefActionApply')
        self.lblPrefAutostart = go('lblPrefAutostart')
        self.chkPrefAutostart = go('chkPrefAutostart')
        self.lblPrefAutostartText = go('lblPrefAutostartText')
        self.lblPrefSleep = go('lblPrefSleep')
        self.cmbPrefSleep = go('cmbPrefSleep')
        self.lsSleep = go('lsSleep')
        self.lblPrefSleepText = go('lblPrefSleepText')
        self.lblPrefAlign = go('lblPrefAlign')
        self.cmbPrefAlign = go('cmbPrefAlign')
        self.lsAlign = go('lsAlign')
        self.lblPrefAlignText = go('lblPrefAlignText')

        # Network objects
        self.lblNetwInterface = go('lblNetwInterface')
        self.txtNetwInterface = go('txtNetwInterface')
        self.lblNetwInterfaceText = go('lblNetwInterfaceText')
        self.lblNetwDownSpeed = go('lblNetwDownSpeed')
        self.txtNetwDownSpeed = go('txtNetwDownSpeed')
        self.lblNetwSpeedText = go('lblNetwSpeedText')
        self.lblNetwUpSpeed = go('lblNetwUpSpeed')
        self.txtNetwUpSpeed = go('txtNetwUpSpeed')
        self.btnNetspeed = go('btnNetspeed')
        self.lblNetwLanIP = go('lblNetwLanIP')
        self.chkNetwLanIP = go('chkNetwLanIP')
        self.lblNetwLanIPText = go('lblNetwLanIPText')
        self.lblNetwIP = go('lblNetwIP')
        self.chkNetwIP = go('chkNetwIP')

        # System objects
        self.lblSysCoresTemp = go('lblSysCoresTemp')
        self.chkSysCores = go('chkSysCores')
        self.lblSysCoresTempText = go('lblSysCoresTempText')
        self.lblSysHdTemp = go('lblSysHdTemp')
        self.chkSysHd = go('chkSysHd')
        self.lblSysTempUnit = go('lblSysTempUnit')
        self.cmbSysTempUnit = go('cmbSysTempUnit')
        self.lsTemp = go('lsTemp')
        self.lblSysCpuFan = go('lblSysCpuFan')
        self.chkSysCpuFan = go('chkSysCpuFan')
        self.lblSysChassisFan = go('lblSysChassisFan')
        self.chkSysChassisFan = go('chkSysChassisFan')
        self.lblSysKernel = go('lblSysKernel')
        self.chkSysKernel = go('chkSysKernel')
        self.lblSysUP = go('lblSysUP')
        self.chkSysUP = go('chkSysUP')

        # Read from config file
        self.cfg = Config(join(self.scriptDir, 'conky.conf'))
        self.clrTitleFg = Gdk.color_parse(self.cfg.getValue('COLORS', 'title_fg'))
        self.clrTitleBg = Gdk.color_parse(self.cfg.getValue('COLORS', 'title_bg'))
        self.clrMenuSelect = Gdk.color_parse(self.cfg.getValue('COLORS', 'menu_select'))
        self.clrMenuHover = Gdk.color_parse(self.cfg.getValue('COLORS', 'menu_hover'))
        self.clrMenuBg = Gdk.color_parse(self.cfg.getValue('COLORS', 'menu_bg'))

        # Set background and forground colors
        self.ebTitle.modify_bg(Gtk.StateType.NORMAL, self.clrTitleBg)
        self.lblTitle.modify_fg(Gtk.StateType.NORMAL, self.clrTitleFg)
        self.lblMenuPreferences.modify_fg(Gtk.StateType.NORMAL, self.clrTitleBg)
        self.lblMenuNetwork.modify_fg(Gtk.StateType.NORMAL, self.clrTitleBg)
        self.lblMenuSystem.modify_fg(Gtk.StateType.NORMAL, self.clrTitleBg)
        self.lblMenuTitle.modify_fg(Gtk.StateType.NORMAL, self.clrTitleBg)
        self.ebMenu.modify_bg(Gtk.StateType.NORMAL, self.clrMenuBg)
        self.ebMenuPreferences.modify_bg(Gtk.StateType.NORMAL, self.clrMenuBg)
        self.ebMenuNetwork.modify_bg(Gtk.StateType.NORMAL, self.clrMenuBg)
        self.ebMenuSystem.modify_bg(Gtk.StateType.NORMAL, self.clrMenuBg)

        # Translations
        self.window.set_title(_("SolydXK Conky"))
        self.lblTitle.set_text(self.window.get_title())
        self.lblMenuPreferences.set_text(_("Preferences"))
        self.lblMenuNetwork.set_text(_("Network"))
        self.lblMenuSystem.set_text(_("System"))
        self.btnSave.set_label(_("Save"))
        self.lblPrefAction.set_text(_("Action"))
        self.btnPrefActionApply.set_label(_("Apply"))
        self.lblPrefAutostart.set_text(_("Autostart"))
        self.lblPrefAutostartText.set_text(_("Autostart Conky on login."))
        self.lblPrefSleep.set_text(_("Sleep"))
        self.lblPrefSleepText.set_text(_("Seconds to wait before starting Conky.\nDefault is 20 seconds."))
        self.lblPrefAlign.set_text(_("Align"))
        self.lblPrefAlignText.set_text(_("Conky alignment on the desktop."))
        self.lblNetwInterface.set_text(_("Interface"))
        self.lblNetwInterfaceText.set_text(_("Auto detected (use ifconfig)."))
        self.lblNetwDownSpeed.set_text(_("Download speed"))
        self.lblNetwSpeedText.set_text(_("Test your download and upload speed\nwith speed.net (in Kilobytes)."))
        self.lblNetwUpSpeed.set_text(_("Upload speed"))
        self.btnNetspeed.set_label(_("speedtest.net"))
        self.lblNetwLanIP.set_text(_("LAN IP"))
        self.lblNetwLanIPText.set_text(_("Check to show these items."))
        self.lblNetwIP.set_text(_("IP"))
        self.lblSysCoresTemp.set_text(_("Core temperature"))
        self.lblSysCoresTempText.set_text(_("Check to show these items."))
        self.lblSysHdTemp.set_text(_("HD temperature"))
        self.lblSysTempUnit.set_text(_("Temperature unit"))
        self.lblSysCpuFan.set_text(_("CPU fan speed"))
        self.lblSysChassisFan.set_text(_("Chassis fan speed"))
        self.lblSysKernel.set_text(_("Kernel"))
        self.lblSysUP.set_text(_("Update Pack"))

        # Fill combos
        actions = [[_("Start")], [_("Stop")], [_("Remove")]]
        for a in actions:
            self.lsAction.append(a)

        self.sleep = [[0], [10], [20], [30], [40], [50], [60]]
        for s in self.sleep:
            self.lsSleep.append(s)

        align = [[_("Right")], [_("Left")]]
        for a in align:
            self.lsAlign.append(a)

        temperature = [[_("Celsius")], [_("Fahrenheit")]]
        for t in temperature:
            self.lsTemp.append(t)

        # Initialize logging
        self.log = Logger('', 'debug', True, self.statusbar)

        # Get command lines
        self.commandCore = self.cfg.getValue('COMMANDS', 'core')
        self.commandCpu = self.cfg.getValue('COMMANDS', 'cpu')
        self.commandChassis = self.cfg.getValue('COMMANDS', 'chassis')
        self.commandHdd = self.cfg.getValue('COMMANDS', 'hdd')
        self.commandLanIp = self.cfg.getValue('COMMANDS', 'lanip')
        self.commandIp = self.cfg.getValue('COMMANDS', 'ip')
        self.commandKernel = self.cfg.getValue('COMMANDS', 'kernel')
        self.commandUp = self.cfg.getValue('COMMANDS', 'up')

        # Init variables
        self.ec = ExecCmd(self.log)
        self.selectedMenuItem = None
        self.defaultSpeed = '1000'
        self.home = expanduser("~/")
        self.dist = functions.getDistribution(False)
        self.luaDir = join(self.home, '.lua/scripts')
        self.lua = join(self.luaDir, 'clock_rings.lua')
        self.conkyrc = join(self.home, '.conkyrc')
        self.conkyStart = join(self.home, '.conky-start')
        self.autostartDir = join(self.home, '.config/autostart')
        self.desktop = join(self.autostartDir, 'conky.desktop')

        # Get current settings
        self.getSettings()

        # Show version number in status bar
        self.version = functions.getPackageVersion('solydxk-conky')
        functions.pushMessage(self.statusbar, self.version)

        # Show preferences at startup
        self.on_ebMenuPreferences_button_release_event()

        self.builder.connect_signals(self)
        self.window.show()

    # ===============================================
    # Menu section functions
    # ===============================================

    def on_ebMenuPreferences_enter_notify_event(self, widget, event):
        self.changeMenuBackground(menuItems[0])

    def on_ebMenuNetwork_enter_notify_event(self, widget, event):
        self.changeMenuBackground(menuItems[1])

    def on_ebMenuSystem_enter_notify_event(self, widget, event):
        self.changeMenuBackground(menuItems[2])

    def on_ebMenuPreferences_leave_notify_event(self, widget, event):
        self.changeMenuBackground(self.selectedMenuItem)

    def on_ebMenuNetwork_leave_notify_event(self, widget, event):
        self.changeMenuBackground(self.selectedMenuItem)

    def on_ebMenuSystem_leave_notify_event(self, widget, event):
        self.changeMenuBackground(self.selectedMenuItem)

    def changeMenuBackground(self, menuItem, select=False):
        ebs = []
        ebs.append([menuItems[0], self.ebMenuPreferences])
        ebs.append([menuItems[1], self.ebMenuNetwork])
        ebs.append([menuItems[2], self.ebMenuSystem])
        for eb in ebs:
            if eb[0] == menuItem:
                if select:
                    self.selectedMenuItem = menuItem
                    eb[1].modify_bg(Gtk.StateType.NORMAL, self.clrMenuSelect)
                else:
                    if eb[0] != self.selectedMenuItem:
                        eb[1].modify_bg(Gtk.StateType.NORMAL, self.clrMenuHover)
            else:
                if eb[0] != self.selectedMenuItem or select:
                    eb[1].modify_bg(Gtk.StateType.NORMAL, self.clrMenuBg)

    def on_ebMenuPreferences_button_release_event(self, widget=None, event=None):
        if self.selectedMenuItem != menuItems[0]:
            self.changeMenuBackground(menuItems[0], True)
            self.lblMenuTitle.set_text(self.lblMenuPreferences.get_text())
            self.nbConky.set_current_page(0)

    def on_ebMenuNetwork_button_release_event(self, widget=None, event=None):
        if self.selectedMenuItem != menuItems[1]:
            self.changeMenuBackground(menuItems[1], True)
            self.lblMenuTitle.set_text(self.lblMenuNetwork.get_text())
            self.nbConky.set_current_page(1)

    def on_ebMenuSystem_button_release_event(self, widget=None, event=None):
        if self.selectedMenuItem != menuItems[2]:
            self.changeMenuBackground(menuItems[2], True)
            self.lblMenuTitle.set_text(self.lblMenuSystem.get_text())
            self.nbConky.set_current_page(2)

    # ===============================================
    # Button functions
    # ===============================================

    def on_btnSave_clicked(self, widget):
        self.saveSettings()

    def on_btnPrefActionApply_clicked(self, widget):
        action = self.getActiveComboValue(self.cmbPrefAction)
        if action:
            if action[0] == 0:
                # Start
                if functions.isProcessRunning('conky'):
                    os.system('killall conky')
                os.system('conky &')
                self.log.write(_("Conky started"), 'conky.on_btnPrefActionApply_clicked', 'info')
            elif action[0] == 1:
                # Stop
                if functions.isProcessRunning('conky'):
                    os.system('killall conky')
                    self.log.write(_("Conky stopped"), 'conky.on_btnPrefActionApply_clicked', 'info')
                else:
                    self.log.write(_("Conky is not running"), 'conky.on_btnPrefActionApply_clicked', 'info')
            elif action[0] == 2:
                # Remove
                self.removeConky()
                self.getDefaultSettings()
                self.log.write(_("Conky removed"), 'conky.on_btnPrefActionApply_clicked', 'info')

    def on_btnNetspeed_clicked(self, widget):
        self.openUrl("http://speedtest.net")

    # ===============================================
    # Get settings
    # ===============================================

    # Default settings (no .conkyrc in user home directory)
    def getDefaultSettings(self):
        # Set default values in gui
        self.log.write(_("Get default settings"), 'conky.getDefaultSettings', 'info')
        self.cmbPrefAction.set_active(0)
        self.cmbPrefSleep.set_active(2)
        self.cmbPrefAlign.set_active(0)
        self.chkPrefAutostart.set_active(True)
        self.txtNetwInterface.set_text(functions.getNetworkInterface())
        self.txtNetwDownSpeed.set_text(self.defaultSpeed)
        self.txtNetwUpSpeed.set_text(self.defaultSpeed)
        self.chkNetwLanIP.set_active(True)
        self.chkNetwIP.set_active(True)
        self.chkSysCores.set_active(True)
        self.chkSysHd.set_active(True)
        self.cmbSysTempUnit.set_active(0)
        self.chkSysCpuFan.set_active(True)
        self.chkSysChassisFan.set_active(True)
        self.chkSysKernel.set_active(True)
        self.chkSysUP.set_active(True)

    # Get conky settings for the current user
    def getSettings(self):
        if exists(self.conkyrc):
            self.log.write(_("Start reading existing settings"), 'conky.getSettings', 'info')
            self.cmbPrefAction.set_active(0)
            # TODO: Read values from conkyrc, and show these in the gui
            conkyrcCont = functions.getFileContents(self.conkyrc)
            luaCont = functions.getFileContents(self.lua)
            startCont = functions.getFileContents(self.conkyStart)

            if functions.findRegExpInString('\[ETH\]', conkyrcCont):
                # If the [ETH] placeholder is found, assume template
                self.getDefaultSettings()
            else:
                # Preferences
                if exists(self.desktop):
                    self.log.write(_("Autostart found"), 'conky.getSettings', 'debug')
                    self.chkPrefAutostart.set_active(True)

                sleepStr = functions.findRegExpInString('\d+', startCont)
                if sleepStr:
                    sleepNr = functions.strToNumber(sleepStr, True)
                    self.log.write(_("Current nr of seconds to sleep before starting Conky: %(sleepnr)d" % {'sleepnr': sleepNr}), 'conky.getSettings', 'debug')
                    index = -1
                    for val in self.sleep:
                        if index >= 0:
                            if sleepNr < val[0]:
                                break
                        index += 1
                    self.cmbPrefSleep.set_active(index)

                alignment = functions.findRegExpInString('alignment\s([a-z]*)', conkyrcCont, 1)
                if alignment:
                    self.log.write(_("Current alignment: %(alignment)s" % {'alignment': alignment}), 'conky.getSettings', 'debug')
                    if alignment == 'tr':
                        self.cmbPrefAlign.set_active(0)
                    else:
                        self.cmbPrefAlign.set_active(1)
                else:
                    self.cmbPrefAlign.set_active(0)

                # Network
                eth = functions.findRegExpInString('\{downspeed\s+([a-z0-9]*)', conkyrcCont, 1)
                if eth:
                    self.log.write(_("Current network interface: %(interface)s" % {'interface': eth}), 'conky.getSettings', 'debug')
                    self.txtNetwInterface.set_text(eth)
                else:
                    self.txtNetwInterface.set_text(functions.getNetworkInterface())

                dl = functions.findRegExpInString('downspeedf.*\n.*\n,*[a-z\=\s]*(\d*)', luaCont, 1)
                if dl:
                    self.log.write(_("Current download speed: %(dl)s" % {'dl': dl}), 'conky.getSettings', 'debug')
                    self.txtNetwDownSpeed.set_text(dl)
                else:
                    self.txtNetwDownSpeed.set_text(self.defaultSpeed)

                ul = functions.findRegExpInString('upspeedf.*\n.*\n,*[a-z\=\s]*(\d*)', luaCont, 1)
                if ul:
                    self.log.write(_("Current upload speed: %(ul)s" % {'ul': ul}), 'conky.getSettings', 'debug')
                    self.txtNetwUpSpeed.set_text(ul)
                else:
                    self.txtNetwUpSpeed.set_text(self.defaultSpeed)

                if functions.findRegExpInString('<inet', conkyrcCont):
                    self.log.write(_("Check LAN IP"), 'conky.getSettings', 'debug')
                    self.chkNetwLanIP.set_active(True)
                if functions.findRegExpInString('dyndns', conkyrcCont):
                    self.log.write(_("Check IP"), 'conky.getSettings', 'debug')
                    self.chkNetwIP.set_active(True)

                # System
                if functions.findRegExpInString('core\d*\s+temp', conkyrcCont):
                    self.log.write(_("Check cores"), 'conky.getSettings', 'debug')
                    self.chkSysCores.set_active(True)
                if functions.findRegExpInString('hddtemp', conkyrcCont, 0, True):
                    self.log.write(_("Check HD temperature"), 'conky.getSettings', 'debug')
                    self.chkSysHd.set_active(True)

                if functions.findRegExpInString('sensors\s+\-f', conkyrcCont):
                    self.log.write(_("Using temperature unit Fahrenheit"), 'conky.getSettings', 'debug')
                    self.cmbSysTempUnit.set_active(1)
                else:
                    self.log.write(_("Using temperature unit Celsius"), 'conky.getSettings', 'debug')
                    self.cmbSysTempUnit.set_active(0)

                if functions.findRegExpInString('cpu\s+fan', conkyrcCont):
                    self.log.write(_("Check CPU fan"), 'conky.getSettings', 'debug')
                    self.chkSysCpuFan.set_active(True)
                if functions.findRegExpInString('chassis\s+fan', conkyrcCont):
                    self.log.write(_("Check chassis fan"), 'conky.getSettings', 'debug')
                    self.chkSysChassisFan.set_active(True)
                if functions.findRegExpInString('kernel', conkyrcCont, 0, True):
                    self.log.write(_("Check kernel"), 'conky.getSettings', 'debug')
                    self.chkSysKernel.set_active(True)
                if functions.findRegExpInString('packlevel', conkyrcCont):
                    self.log.write(_("Check Update Pack"), 'conky.getSettings', 'debug')
                    self.chkSysUP.set_active(True)
        else:
            self.getDefaultSettings()

    # ===============================================
    # Save settings
    # ===============================================

    # Save settings: copy templates, and set values
    def saveSettings(self):
        self.log.write(_("Save settings..."), 'conky.saveSettings', 'info')

        # Kill Conky, and remove all files
        self.removeConky()
        # Wait 5 seconds in the hope conky was stopped
        sleep(5)

        # conkyrc
        template = join(self.scriptDir, 'cfg/conkyrc')
        if exists(template):
            self.log.write(_("Copy %(template)s to %(conkyrc)s" % {"template": template, "conkyrc" :self.conkyrc}), 'conky.saveSettings', 'debug')
            shutil.copy2(template, self.conkyrc)
            functions.chownCurUsr(self.conkyrc)
        else:
            self.log.write(_("Conkyrc template not found %(template)s" % {"template": template}), 'conky.saveSettings', 'error')

        # lua
        template = join(self.scriptDir, 'cfg/clock_rings.lua')
        if exists(template):
            if not exists(self.luaDir):
                os.makedirs(self.luaDir)
            self.log.write(_("Copy %(template)s to %(lua)s" % {"template": template, "lua" :self.lua}), 'conky.saveSettings', 'debug')
            shutil.copy2(template, self.lua)
            functions.chownCurUsr(self.lua)
        else:
            self.log.write(_("Lua template not found %(template)s" % {"template": template}), 'conky.saveSettings', 'error')

        # start script
        template = join(self.scriptDir, 'cfg/conky-start')
        if os.path.exists(template):
            self.log.write(_("Copy %(template)s to %(conkyStart)s" % {"template": template, "conkyStart" :self.conkyStart}), 'conky.saveSettings', 'debug')
            shutil.copy2(template, self.conkyStart)
            functions.chownCurUsr(self.conkyStart)
            functions.makeExecutable(self.conkyStart)
        else:
            self.log.write(_("Start script not found %(template)s" % {"template": template}), 'conky.saveSettings', 'error')

        # Download and upload speed
        dl = self.txtNetwDownSpeed.get_text()
        functions.replaceStringInFile('\[DSPEED\]', str(dl), self.lua)
        self.log.write(_("Save download speed: %(dl)s" % {'dl': dl}), 'conky.saveSettings', 'debug')
        ul = self.txtNetwUpSpeed.get_text()
        functions.replaceStringInFile('\[USPEED\]', str(ul), self.lua)
        self.log.write(_("Save upload speed: %(ul)s" % {'ul': ul}), 'conky.saveSettings', 'debug')

        # Battery / Swap
        bat = '/proc/acpi/battery/BAT0/state'
        if exists(bat):
            self.log.write(_("Battery detected: replace Swap with Battery index"), 'conky.saveSettings', 'debug')
            functions.replaceStringInFile('\$\{swapperc\}', '${battery_percent BAT0}', self.conkyrc)
            functions.replaceStringInFile('\}Swap', '}BAT', self.conkyrc)
            functions.replaceStringInFile("'swapperc'", "'battery_percent'", self.lua)

        # Get selecte temperature unit, and get sensors data accordingly
        tempUnit = self.getActiveComboValue(self.cmbSysTempUnit)[1][0:1].lower()
        if tempUnit == 'c':
            # Celsius
            self.log.write(_("Temperature unit: Celsius"), 'conky.saveSettings', 'debug')
            sensorsCommand = 'sensors'
            sensors = self.ec.run(sensorsCommand, False, False)
        else:
            # Fahrenheit
            self.log.write(_("Temperature unit: Fahrenheit"), 'conky.saveSettings', 'debug')
            sensorsCommand = 'sensors -f'
            sensors = self.ec.run(sensorsCommand, False, False)

        # Core temperature
        if self.chkSysCores.get_active():
            coreList = []
            sensorsList = sensors.splitlines(True)
            for line in sensorsList:
                reObj = re.search('core\s{0,}\d.*\:', line, re.I)
                if reObj:
                    newLine = self.commandCore.replace('[CORESTR]', reObj.group(0))
                    newLine = newLine.replace('[SENSORSTR]', sensorsCommand)
                    self.log.write(_("Core found: %(core)s" % {'core': reObj.group(0)}), 'conky.saveSettings', 'debug')
                    coreList.append(newLine)

            if coreList:
                self.log.write(_("Add Core lines to .conkyrc"), 'conky.saveSettings', 'debug')
                functions.replaceStringInFile('#\s\[CORE\]', '\n'.join(coreList), self.conkyrc)

        # CPU fan speed
        if self.chkSysCpuFan.get_active():
            cpufan = functions.findRegExpInString('cpu\s{0,}fan.*\:', sensors)
            self.log.write(_("Cpu fan value = %(cpufan)s" % {'cpufan' :str(cpufan)}), 'conky.saveSettings', 'debug')
            if cpufan:
                newLine = self.commandCpu.replace('[CPUSTR]', cpufan)
                functions.replaceStringInFile('#\s\[CPUFAN\]', newLine, self.conkyrc)

        # Chassis fan speed
        if self.chkSysChassisFan.get_active():
            chafan = functions.findRegExpInString('chassis\s{0,}fan.*\:', sensors)
            self.log.write(_("Chassis fan value = %(chafan)s" % {'chafan' :str(chafan)}), 'conky.saveSettings', 'debug')
            if chafan:
                newLine = self.commandChassis.replace('[CHASTR]', chafan)
                functions.replaceStringInFile('#\s\[CHAFAN\]', newLine, self.conkyrc)

        # HD temperature unit
        if self.chkSysHd.get_active():
            self.log.write(_("Add HDD temperature to .conkyrc"), 'conky.saveSettings', 'debug')
            newLine = self.commandHdd.replace('[TEMPUNIT]', tempUnit.upper())
            hddCommand = 'hddtemp -n'
            if tempUnit == 'f':
                hddCommand = 'hddtemp -n -u f'
            newLine = newLine.replace('[HDDSTR]', hddCommand)
            functions.replaceStringInFile('#\s\[HDDTEMP\]', newLine, self.conkyrc)

        # LAN IP
        if self.chkNetwLanIP.get_active():
            self.log.write(_("Add LAN IP to .conkyrc"), 'conky.saveSettings', 'debug')
            functions.replaceStringInFile('#\s\[LANIP\]', self.commandLanIp, self.conkyrc)

        # IP
        if self.chkNetwIP.get_active():
            self.log.write(_("Add IP to .conkyrc"), 'conky.saveSettings', 'debug')
            functions.replaceStringInFile('#\s\[IP\]', self.commandIp, self.conkyrc)

        # Kernel
        if self.chkSysKernel.get_active():
            self.log.write(_("Add Kernel to .conkyrc"), 'conky.saveSettings', 'debug')
            functions.replaceStringInFile('#\s\[KERNEL\]', self.commandKernel, self.conkyrc)

        # UP
        if self.chkSysUP.get_active():
            self.log.write(_("Add Update Pack to .conkyrc"), 'conky.saveSettings', 'debug')
            functions.replaceStringInFile('#\s\[UP\]', self.commandUp, self.conkyrc)

        # Conky desktop alignment
        alignment = self.getActiveComboValue(self.cmbPrefAlign)
        self.log.write(_("Conky alignment = %(alignment)s" % {'alignment': alignment[1]}), 'conky.saveSettings', 'debug')
        if alignment[0] > 0:
            functions.replaceStringInFile('alignment\s+tr', 'alignment tl', self.conkyrc)

        # Write sleep before conky start
        sleepNr = functions.strToNumber(self.getActiveComboValue(self.cmbPrefSleep)[1], True)
        self.log.write(_("Conky sleep before start = %(sleep)d seconds" % {'sleep': sleepNr}), 'conky.saveSettings', 'debug')
        if sleepNr != 20:
            functions.replaceStringInFile('20', str(sleepNr), self.conkyStart)

        # Network interface
        eth = self.txtNetwInterface.get_text()
        self.log.write(_("Save network interface: %(interface)s" % {'interface': eth}), 'conky.saveSettings', 'debug')
        functions.replaceStringInFile('\[ETH\]', eth, self.conkyrc)
        functions.replaceStringInFile('\[ETH\]', eth, self.lua)

        # Change color scheme for SolydX
        if 'solydx' in self.dist.lower():
            self.log.write(_("Create orange theme for SolydX"), 'conky.saveSettings', 'debug')
            functions.replaceStringInFile(TEXT_BLUE, TEXT_ORANGE, self.conkyrc)
            functions.replaceStringInFile(TEXT_BLUE, TEXT_ORANGE, self.lua)

        # Automatically start Conky when the user logs in
        if self.chkPrefAutostart.get_active() and not exists(self.desktop):
            self.log.write(_("Write autostart file: %(desktop)s" % {'desktop': self.desktop}), 'conky.saveSettings', 'debug')
            if not exists(self.autostartDir):
                os.makedirs(self.autostartDir)
            desktopCont = '[Desktop Entry]\nComment=SolydXK Conky\nExec=[CONKYSTART]\nIcon=/usr/share/solydxk/logo.png\nStartupNotify=true\nTerminal=false\nType=Application\nName=SolydXK Conky\nGenericName=SolydXK Conky'
            f = open(self.desktop, 'w')
            f.write(desktopCont.replace('[CONKYSTART]', self.conkyStart))
            f.close()
            functions.makeExecutable(self.desktop)

        msg = "SolydXK Conky configuration has finished.\n\nWill now start Conky with the new configuration."
        MessageDialogSave(self.window.get_title(), msg, Gtk.MessageType.INFO, self.window).show()
        self.log.write(_("Save settings done"), 'conky.saveSettings', 'info')

        # Restart Conky
        if functions.isProcessRunning('conky'):
            os.system('killall conky')
        os.system('conky &')

    # ===============================================
    # Miscellaneous functions
    # ===============================================

    def removeConky(self):
        if functions.isProcessRunning('conky'):
            os.system('killall conky')
        if exists(self.conkyrc):
            os.remove(self.conkyrc)
        if exists(self.lua):
            os.remove(self.lua)
        if exists(self.desktop):
            os.remove(self.desktop)
        if exists(self.conkyStart):
            os.remove(self.conkyStart)

    # Open an URL or a program
    def openUrl(self, urlOrPath):
        if urlOrPath != '':
            if '://' in urlOrPath:
                self.log.write(_("Open URL: %(url)s") % {"url": urlOrPath}, 'conky.openUrl', 'debug')
                webbrowser.open(urlOrPath)
            else:
                self.log.write(_("Start program: %(prg)s") % {"prg": urlOrPath}, 'conky.openUrl', 'debug')
                os.system(urlOrPath)
        else:
            self.log.write(_("Nothing to open"), 'conky.openUrl', 'error')

    # Get the selected index and value from a combo box
    def getActiveComboValue(self, combo):
        value = None
        model = combo.get_model()
        active = combo.get_active()
        if active >= 0:
            value = [active, model[active][0]]
        return value

    # Close the gui
    def on_conkyWindow_destroy(self, widget, data=None):
        # Close the app
        Gtk.main_quit()
コード例 #46
0
ファイル: pae.py プロジェクト: AlbertJP/device-driver-manager
class PAE():
    def __init__(self, distribution, loggerObject):
        self.distribution = distribution.lower()
        self.log = loggerObject
        self.ec = ExecCmd(self.log)

    # Check if the PAE kernel for i486 can be installed
    def getPae(self):
        hwList = []
        # Get the kernel release
        kernelRelease = self.ec.run('uname -r')
        if '486' in kernelRelease[0]:
            self.log.write('Single-core kernel found: ' + kernelRelease[0],
                           'pae.getHardwareList', 'debug')

            # Check the machine hardware
            machine = self.ec.run('uname -m')
            if machine[0] == 'i686':
                self.log.write(
                    'Multi-core system running single-core kernel found',
                    'pae.getHardwareList', 'info')
                status = packageStatus[1]
                # Check if PAE is installed next to the i486 kernel
                paeInst = self.ec.run('apt search 686-pae | grep ^i')
                if paeInst:
                    self.log.write('PAE and i486 kernels installed',
                                   'pae.getHardwareList', 'info')
                    status = packageStatus[0]
                hwList.append([
                    'Multi-core support for 32-bit systems', hwCodes[3], status
                ])
            else:
                self.log.write(
                    'PAE kernel cannot be installed: single-core system',
                    'pae.getHardwareList', 'warning')

        elif '686' in kernelRelease[0]:
            self.log.write('Multi-core already installed: ' + kernelRelease[0],
                           'pae.getHardwareList', 'info')
            hwList.append([
                'Multi-core support for 32-bit systems', hwCodes[3],
                packageStatus[0]
            ])

        return hwList

    # Called from drivers.py: install PAE kernel
    def installPAE(self):
        try:
            cmdPae = 'apt-get -y --force-yes install linux-headers-686-pae linux-image-686-pae'
            # Check if already installed
            status = functions.getPackageStatus('linux-headers-686-pae')
            if status == packageStatus[0]:
                cmdPae += ' --reinstall'
            self.log.write('PAE kernel install command: ' + cmdPae,
                           'pae.installPAE', 'debug')
            self.ec.run(cmdPae)

            # Check for Nvidia
            nv = Nvidia(self.distribution, self.log)
            nvList = nv.getNvidia()
            self.log.write('Nvidia info: ' + str(nvList), 'pae.installPAE',
                           'debug')
            for nvInfo in nvList:
                if nvInfo[2] == packageStatus[0]:
                    self.log.write('Install Nvidia drivers', 'pae.installPAE',
                                   'info')
                    nv.installNvidia()

            # Remove xorg.conf
            #xorg = '/etc/X11/xorg.conf'
            #if os.path.exists(xorg):
            #    shutil.move(xorg, xorg + '.ddm')
            #    self.log.write('Moved ' + xorg + ' to ' + xorg + '.ddm', 'pae.installPAE', 'info')

        except Exception, detail:
            self.log.write(detail, 'pae.installPAE', 'error')
コード例 #47
0
class UmRefresh(object):
    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

    def refresh(self):
        uptodateText = _("Your system is up to date")
        updavText = _("There are updates available")
        noConText = _("No internet connection")
        errText = _("Unable to retrieve sources information")
        self.counter += 1
        print(("UmRefresh refresh count #: %d" % self.counter))

        self.statusIcon.set_from_pixbuf(self.pbExec)
        self.statusIcon.set_tooltip_text(_("Refreshing..."))

        if not self.umglobal.isSrciptRunning("updatemanager.py"):
            for fle in glob(join(self.scriptDir, "files/.um*")):
                remove(fle)

        self.umglobal.getLocalInfo()
        if self.umglobal.repos:
            if self.counter > 1:
                self.umglobal.getServerInfo()
            if self.umglobal.hasInternet:
                # Check update status
                if self.checkForUpdates():
                    if self.umglobal.newUpd:
                        self.statusIcon.set_from_pixbuf(self.pbInfo)
                        self.statusIcon.set_tooltip_text(
                            _("New update: %s" %
                              self.umglobal.serverUpdVersion))
                    else:
                        self.statusIcon.set_from_pixbuf(self.pbInfo)
                        self.statusIcon.set_tooltip_text(updavText)
                else:
                    self.statusIcon.set_from_pixbuf(self.pbApply)
                    self.statusIcon.set_tooltip_text(uptodateText)
            else:
                self.statusIcon.set_from_pixbuf(self.pbDisconnected)
                self.statusIcon.set_tooltip_text(noConText)
                # Check every 60 seconds if there is a connection
                GObject.timeout_add_seconds(60, self.refresh)
                return True
        else:
            self.statusIcon.set_from_pixbuf(self.pbError)
            self.statusIcon.set_tooltip_text(errText)

        print("Done refreshing")

    def checkForUpdates(self):
        # Get updateable packages which are not held back"
        cmd = "aptitude search '~U' | grep -v ^ih"

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

        if lst:
            return True
        else:
            return False
コード例 #48
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 = []

        # --force-yes is deprecated in stretch
        self.force = self.umglobal.get_apt_force()

        # 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 in_US
        cmd = "env LANG=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 apt-get dist-upgrade --assume-no"
        if "apt-get" in customAptGetCommand:
            for cmd in self.force.split(" "):
                customAptGetCommand = customAptGetCommand.replace(cmd, "")
            customAptGetCommand = customAptGetCommand.replace("--assume-yes", "")
            customAptGetCommand = customAptGetCommand.replace("--yes", "")
            customAptGetCommand = customAptGetCommand.replace("-y", "")
            cmd = "env LANG=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, include_kept_back=False):
        self.notavailablePackages = []
        # Use env LANG=C to ensure the output of apt-show-versions is always en_US
        # aptitude search '~o' --disable-columns -F "%p %v %V"
        cmd = "env LANG=C apt-show-versions | grep available"
        # Get the output of the command in a list
        notavailables = self.ec.run(cmd=cmd, realTime=False)

        # Get packages that were kept back by the user
        keptbacks = []
        if not include_kept_back:
            cmd = "env LANG=C dpkg --get-selections | grep hold$ | awk '{print $1}'"
            keptbacks = self.ec.run(cmd=cmd, realTime=False)

        # Loop through each line and fill the package lists
        for line in notavailables:
            items = line.split(" ")
            pck = items[0].split(":")[0]
            if pck != "updatemanager" and pck not in keptbacks:
                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 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 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 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 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 apt-cache policy %s | grep Installed:" % package
        if candidate:
            cmd = "env LANG=C apt-cache policy %s | grep Candidate:" % package
        lst = self.ec.run(cmd, realTime=False)[0].strip().split(' ')
        return lst[-1]

    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 %s autoclean" % self.force
        if not safe:
            cmd = "apt-get --yes %s clean" % self.force
        self.ec.run(cmd, realTime=False)

    def getPackageDependencies(self, package):
        cmd = "env LANG=C apt-cache depends %s | grep Depends | grep -v '<' | sed 's/.*ends:\ //' | tr '\n' ' '" % package
        lst = self.ec.run(cmd, realTime=False)[0].strip().split(' ')
        return lst
コード例 #49
0
class UpdateManager(object):
    def __init__(self):
        # Check if script is running
        self.scriptName = basename(__file__)
        self.umglobal = UmGlobal()
        self.user = self.umglobal.getLoginName()

        # Initiate logging
        self.logFile = join('/var/log', self.umglobal.settings['log'])
        print(("UM log = %s" % self.logFile))
        self.log = Logger(self.logFile, maxSizeKB=5120)

        # Remove scripts
        self.deleteScripts(self.umglobal.localUpdVersion)

        # Initialize
        self.ec = ExecCmd(loggerObject=self.log)
        self.apt = UmApt(self.umglobal)
        self.kernelVersion = self.umglobal.getKernelVersion()
        self.upgradables = []
        self.upgradableUM = []
        self.window = None

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

        self.quickUpdate = False
        if args.quick and not self.umglobal.newUpd:
            self.quickUpdate = True
        if args.reload:
            pids = self.umglobal.getProcessPids("updatemanager.py")
            if len(pids) > 1:
                print(("updatemanager.py already running - kill pid {}".format(
                    pids[0])))
                os.system("kill {}".format(pids[0]))

        # Set some global translations
        self.aptErrorText = _("Apt error")
        self.upgradablePackagesText = _(
            "The following packages will be upgraded:")
        self.newPackagesText = _(
            "The following NEW packages will be installed:")
        self.removedPackagesText = _("The following packages will be REMOVED:")
        self.heldbackPackagesText = _(
            "The following packages have been kept back:")
        self.downgradePackagesText = _(
            "The following packages are going to be downgraded:")

        # Cleanup first
        for fle in glob(join(self.umglobal.filesDir, '.um*')):
            remove(fle)

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

        # Quick update
        if self.quickUpdate:
            # Refresh data
            self.refresh()
            self.umglobal.collectData()
            self.apt.createPackagesInfoList()
            self.apt.createPackageLists()
            self.fillTreeView()

            # Run upgrade
            nid = self.run_upgrade()

            if nid != "":
                self.on_command_done(None, 0, nid)

            sys.exit(2)

        # Make sure the files directory is set correctly
        self.checkFilesDir()

        # Main window objects
        self.window = go("windowMain")
        #self.window.set_icon_from_file(join(self.umglobal.iconsDir, self.umglobal.settings["icon-connected"]))
        self.tvPck = go("tvPck")
        self.swTerminal = go("swTerminal")
        self.statusbar = go("statusbar")
        self.btnInstall = go("btnInstall")
        self.btnRefresh = go("btnRefresh")
        self.btnPackages = go("btnPackages")
        self.btnOutput = go("btnOutput")
        self.btnInfo = go("btnInfo")
        self.btnPreferences = go("btnPreferences")
        self.nbMain = go("nbMain")
        self.swInfo = go("swInfo")
        self.btnMaintenance = go("btnMaintenance")
        self.lblMaintenance = go("lblMaintenance")
        self.tvMaintenance = go("tvMaintenance")
        self.btnMaintenanceExecute = go("btnMaintenanceExecute")
        self.chkMaintenanceSelectAll = go("chkMaintenanceSelectAll")
        self.radUnneeded = go("radUnneeded")
        self.radCleanCache = go("radCleanCache")
        self.radDowngradable = go("radDowngradable")
        self.radNotavailable = go("radNotavailable")
        self.radOldKernel = go("radOldKernel")
        self.lblMaintenanceHelp = go("lblMaintenanceHelp")

        # Translations
        self.window.set_title(_("SolydXK Update Manager"))
        self.btnInstall.set_label(_("Install"))
        self.btnRefresh.set_label(_("Refresh"))
        self.btnOutput.set_label(_("Output"))
        self.btnInfo.set_label(_("Information"))
        self.btnPreferences.set_label(_("Preferences"))
        self.btnMaintenance.set_label(_("Maintenance"))
        self.btnPackages.set_label(_("Packages"))
        self.uptodateText = self.umglobal.connectedText
        self.lblMaintenance.set_label(self.btnMaintenance.get_label())
        self.btnMaintenanceExecute.set_label(_("Execute"))
        self.chkMaintenanceSelectAll.set_label(_("Select all"))
        self.radCleanCache.set_label(_("Clean up the apt cache"))
        self.radUnneeded.set_label(_("Remove unneeded packages"))
        self.radNotavailable.set_label(
            _("Remove packages not available\nin the repositories"))
        self.radOldKernel.set_label(_("Remove old kernels"))
        self.radDowngradable.set_label(
            _("Downgrade packages with\nonly lower versions available"))
        self.lblMaintenanceHelp.set_label(
            _("Make sure you create\n"
              "a system image before you\n"
              "continue (e.g. Clonezilla)."))

        # VTE Terminal
        self.terminal = VirtualTerminal(userInputAllowed=self.umglobal.
                                        settings["allow-terminal-user-input"])
        self.swTerminal.add(self.terminal)
        self.terminal.set_vexpand(True)
        self.terminal.set_hexpand(True)
        self.terminal.connect('command-done', self.on_command_done)
        self.terminal.connect('line-added', self.on_line_added)
        palletList = [
            '#4A4A4A', '#BD1919', '#118011', '#CE6800', '#1919BC', '#8D138D',
            '#139494', '#A7A7A7'
        ]
        self.terminal.setTerminalColors("#000000", "#FFFFFF", palletList)
        self.swTerminal.modify_bg(Gtk.StateType.NORMAL,
                                  Gdk.color_parse("#FFFFFF"))

        # Disable all buttons
        self.btnInfo.set_sensitive(False)
        self.btnPreferences.set_sensitive(False)
        self.btnOutput.set_sensitive(False)
        self.btnRefresh.set_sensitive(False)
        self.btnInstall.set_sensitive(False)
        self.btnPackages.set_sensitive(False)
        self.btnMaintenance.set_sensitive(False)

        # Hide tabs if needed
        for tab in self.umglobal.settings["hide-tabs"]:
            if tab == "packages":
                self.nbMain.get_nth_page(0).set_visible(False)
                self.btnPackages.set_visible(False)
            elif tab == "output":
                self.nbMain.get_nth_page(1).set_visible(False)
                self.btnOutput.set_visible(False)
            elif tab == "info":
                self.nbMain.get_nth_page(2).set_visible(False)
                self.btnInfo.set_visible(False)
            elif tab == "maintenance":
                self.nbMain.get_nth_page(3).set_visible(False)
                self.btnMaintenance.set_visible(False)

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

        # Force the window to show
        while Gtk.events_pending():
            Gtk.main_iteration()

        # Just show something that we're busy
        msg = _("Gathering information...")
        self.terminal.executeCommand('echo "%s"' % msg, 'init')
        self.showOutput()

        # Treeview handlers
        self.tvHandler = TreeViewHandler(self.tvPck)
        self.tvMaintenanceHandler = TreeViewHandler(self.tvMaintenance)

        # Version information
        ver = _("Version")
        pckVer = self.apt.getPackageVersion('updatemanager')
        versionInfo = "%(ver)s: %(pckVer)s" % {"ver": ver, "pckVer": pckVer}
        if self.umglobal.localUpdVersion != "2000.01.01":
            versionInfo = "%(ver)s: %(pckVer)s" % {
                "ver": ver,
                "pckVer": pckVer
            }
        self.pushMessage(versionInfo)

        # Log basic information
        self.log.write("==============================================",
                       "UM.init", "debug")
        self.log.write("UM version = %s" % versionInfo, "UM.init", "debug")
        self.log.write("==============================================",
                       "UM.init", "debug")
        mirrorsList = join(self.umglobal.filesDir,
                           basename(self.umglobal.settings["mirrors-list"]))
        if exists(mirrorsList):
            self.log.write("Mirrors list", "UM.init", "debug")
            with open(mirrorsList, 'r') as f:
                for line in f.readlines():
                    self.log.write(line, "UM.init", "debug")
            self.log.write("==============================================",
                           "UM.init", "debug")

        # Refresh apt cache
        self.refresh()

        # Initialize maintenance screen
        self.fillTreeViewMaintenance()

    # ===============================================
    # Main window functions
    # ===============================================

    def on_btnInstall_clicked(self, widget):
        self.run_upgrade()

    def run_upgrade(self):
        nid = ""
        aptHasErrors = self.apt.aptHasErrors()
        if aptHasErrors is not None:
            MessageDialog(self.aptErrorText, aptHasErrors)
        elif self.upgradables:

            if self.apt.upgradablePackages:
                self.log.write(
                    "=================== upgradable pacages ====================",
                    "UM.run_upgrade", "debug")
                self.log.write(
                    self.createLogString(self.apt.upgradablePackages),
                    "UM.run_upgrade", "debug")
            if self.apt.removedPackages:
                self.log.write(
                    "==================== removed packages =====================",
                    "UM.run_upgrade", "debug")
                self.log.write(self.createLogString(self.apt.removedPackages),
                               "UM.run_upgrade", "debug")
            if self.apt.newPackages:
                self.log.write(
                    "======================= new packages =======================",
                    "UM.run_upgrade", "debug")
                self.log.write(self.createLogString(self.apt.newPackages),
                               "UM.run_upgrade", "debug")
            if self.apt.heldbackPackages:
                self.log.write(
                    "=================== kept back packages =====================",
                    "UM.run_upgrade", "debug")
                self.log.write(self.createLogString(self.apt.heldbackPackages),
                               "UM.run_upgrade", "debug")

            if not self.quickUpdate:
                self.showOutput()
            contMsg = _("Continue installation?")
            if self.upgradableUM:
                cmd = "%s install updatemanager" % self.umglobal.settings[
                    'apt-get-string']
                cmd += "; %s install %s" % (
                    self.umglobal.settings['apt-get-string'], " ".join(
                        self.apt.getPackageDependencies('updatemanager')))
                nid = 'uminstallum'
                self.prepForCommand(nid)
                if self.quickUpdate:
                    self.ec.run(cmd)
                else:
                    self.terminal.executeCommand(cmd, nid)
                self.log.write("Execute command: %s (%s)" % (cmd, nid),
                               "UM.on_btnInstall_clicked", "debug")
            else:
                msg = self.getDistUpgradeInfo()
                answer = True
                if msg != "":
                    answer = self.showConfirmationDlg(contMsg, msg)
                if answer:
                    cmd = "%s dist-upgrade" % self.umglobal.settings[
                        'apt-get-string']
                    #if self.umglobal.newUpd:
                    pre = join(
                        self.umglobal.filesDir,
                        self.umglobal.settings['pre-upd'].replace(
                            "[VERSION]", self.umglobal.serverUpdVersion))
                    post = join(
                        self.umglobal.filesDir,
                        self.umglobal.settings['post-upd'].replace(
                            "[VERSION]", self.umglobal.serverUpdVersion))
                    if exists(pre):
                        cmd = "/bin/bash %(pre)s; %(cmd)s" % {
                            "pre": pre,
                            "cmd": cmd
                        }
                    if exists(post):
                        cmd = "%(cmd)s; /bin/bash %(post)s" % {
                            "cmd": cmd,
                            "post": post
                        }
                    nid = 'umupd'
                    self.prepForCommand(nid)
                    if self.quickUpdate:
                        self.ec.run(cmd)
                    else:
                        self.terminal.executeCommand(cmd, nid)
                    self.log.write("Execute command: %s (%s)" % (cmd, nid),
                                   "UM.on_btnInstall_clicked", "debug")

        else:
            if not self.quickUpdate:
                MessageDialog(self.btnInstall.get_label(), self.uptodateText)

        return nid

    def on_btnRefresh_clicked(self, widget):
        self.refresh()

    def on_btnPackages_clicked(self, widget):
        self.showPackages()

    def on_btnOutput_clicked(self, widget):
        self.showOutput()

    def on_btnInfo_clicked(self, widget):
        self.showInfo()

    def on_btnPreferences_clicked(self, widget):
        # Run preferences in its own thread
        pref_thread = threading.Thread(target=self.openPreferences)
        pref_thread.setDaemon(True)
        pref_thread.start()

    def openPreferences(self):
        os.system("updatemanager -p")

    def on_btnMaintenance_clicked(self, widget):
        self.showMaintenance()

    def on_radCleanCache_toggled(self, widget):
        if widget.get_active():
            self.fillTreeViewMaintenance()

    def on_radUnneeded_toggled(self, widget):
        if widget.get_active():
            message = "%s\n\n%s" % (
                _("You might need to run this several times."),
                self.lblMaintenanceHelp.get_label().replace("\n", " "))
            WarningDialog(self.btnMaintenance.get_label(), message)
            self.fillTreeViewMaintenance()

    def on_radNotavailable_toggled(self, widget):
        if widget.get_active():
            message = "%s\n\n%s" % (
                _("Removing not available packages may break your system!"),
                self.lblMaintenanceHelp.get_label().replace("\n", " "))
            WarningDialog(self.btnMaintenance.get_label(), message)
            self.fillTreeViewMaintenance()

    def on_radOldKernel_toggled(self, widget):
        if widget.get_active():
            message = "%s\n\n%s" % (
                _("Once removed you will not be able to boot these kernels!"),
                self.lblMaintenanceHelp.get_label().replace("\n", " "))
            WarningDialog(self.btnMaintenance.get_label(), message)
            self.fillTreeViewMaintenance()

    def on_radDowngradable_toggled(self, widget):
        if widget.get_active():
            message = "%s\n\n%s" % (
                _("Downgrading packages may break your system!"),
                self.lblMaintenanceHelp.get_label().replace("\n", " "))
            WarningDialog(self.btnMaintenance.get_label(), message)
            self.fillTreeViewMaintenance()

    def on_btnMaintenanceExecute_clicked(self, widget):
        self.executeMaintenance()

    def on_chkMaintenanceSelectAll_toggled(self, widget):
        self.tvMaintenanceHandler.treeviewToggleAll(
            toggleColNrList=[0], toggleValue=widget.get_active())

    # ===============================================
    # Maintenance functions
    # ===============================================

    def enableMaintenance(self, enable=True):
        self.btnMaintenanceExecute.set_sensitive(enable)
        self.radUnneeded.set_sensitive(enable)
        self.radCleanCache.set_sensitive(enable)
        self.radDowngradable.set_sensitive(enable)
        self.radOldKernel.set_sensitive(enable)
        self.radNotavailable.set_sensitive(enable)
        self.chkMaintenanceSelectAll.set_sensitive(enable)
        if enable:
            self.chkMaintenanceSelectAll.set_active(False)

    def fillTreeViewMaintenance(self):
        blnCleanCache = self.radCleanCache.get_active()
        blnUnneeded = self.radUnneeded.get_active()
        blnDowngradable = self.radDowngradable.get_active()
        blnNotavailable = self.radNotavailable.get_active()
        blnOldKernels = self.radOldKernel.get_active()

        self.enableMaintenance(False)

        columnTypesList = ['bool', 'str', 'str', 'str']
        packages = [["", _("Package"), _("Installed"), _("Available")]]
        # Clear the treeview first
        self.tvMaintenanceHandler.fillTreeview(packages, columnTypesList, 0,
                                               400, True)

        msg = ""
        if blnCleanCache:
            msg = _("Hit the Execute button to clean the cache.")
            columnTypesList = ['str']
            packages.append([msg])
        elif blnUnneeded:
            msg = self.radUnneeded.get_label()
            self.apt.createPackageLists("apt-get autoremove")
            for pck in self.apt.removedPackages:
                packages.append([False, pck[0], pck[1], pck[2]])
            self.apt.createPackageLists()
            # Add orphaned files
            self.apt.fillOrphanedPackages()
            for pck in self.apt.orphanedPackages:
                packages.append([False, pck[0], pck[1], pck[2]])
        elif blnNotavailable:
            msg = self.radNotavailable.get_label()
            self.apt.fillNotAvailablePackages()
            for pck in self.apt.notavailablePackages:
                if pck[0][0:6] != "linux-":
                    packages.append([False, pck[0], pck[1], ""])
        elif blnOldKernels:
            msg = self.radOldKernel.get_label()
            self.apt.fillKernelPackages()
            for pck in self.apt.kernelPackages:
                if "headers-486" not in pck[0] \
                    and "headers-586" not in pck[0] \
                    and "headers-686" not in pck[0] \
                    and "headers-amd64" not in pck[0] \
                    and "image-486" not in pck[0] \
                    and "image-586" not in pck[0] \
                    and "image-686" not in pck[0] \
                    and "image-amd64" not in pck[0]:

                    checkVersion = self.kernelVersion
                    if "kbuild" in pck[0]:
                        indMinus = self.kernelVersion.index("-")
                        indZero = self.kernelVersion.index("0")
                        if indZero > 0 and indZero < indMinus:
                            ind = indZero - 1
                        else:
                            ind = indMinus
                        if ind > 0:
                            checkVersion = self.kernelVersion[0:ind]
                    if checkVersion not in pck[0]:
                        packages.append([False, pck[0], pck[1], ""])
        elif blnDowngradable:
            msg = self.radDowngradable.get_label()
            self.apt.fillDowngradablePackages()
            for pck in self.apt.downgradablePackages:
                packages.append([False, pck[0], pck[1], pck[2]])

        if len(packages) > 1:
            self.tvMaintenanceHandler.fillTreeview(packages, columnTypesList,
                                                   0, 400, True)
        else:
            if not blnCleanCache:
                msg = _("\"%s\"\n did not return any results.") % msg
                MessageDialog(self.btnMaintenance.get_label(), msg)

        self.enableMaintenance(True)

    def executeMaintenance(self):
        blnCleanCache = self.radCleanCache.get_active()
        blnDowngradable = self.radDowngradable.get_active()
        blnNotNeeded = self.radUnneeded.get_active()
        downgradeString = ""
        deleteString = ""
        updateGrub = False
        cmd = ""

        self.enableMaintenance(False)

        if blnCleanCache:
            safe = False
            msg = _(
                "Do you want to completely clean the apt cache?\n\n"
                "When No, only unavailable installation packages are removed.")
            answer = QuestionDialog(self.radCleanCache.get_label(), msg)
            if answer:
                safe = True
            self.apt.cleanCache(safe)
            msg = _("Apt cache has been cleaned.")
            MessageDialog(self.radCleanCache.get_label(), msg)
        else:
            # Get user selected packages
            model = self.tvMaintenance.get_model()
            itr = model.get_iter_first()
            while itr is not None:
                sel = model.get_value(itr, 0)
                if sel:
                    pck = model.get_value(itr, 1)
                    avVer = model.get_value(itr, 3)
                    if blnDowngradable:
                        downgradeString += " %(pck)s=%(avVer)s" % {
                            "pck": pck,
                            "avVer": avVer
                        }
                    else:
                        deleteString += " %s" % pck
                        if "linux-image" in pck:
                            updateGrub = True
                itr = model.iter_next(itr)

            if downgradeString != "":
                cmd = "%s install %s" % (
                    self.umglobal.settings['apt-get-string'], downgradeString)
            elif deleteString != "":
                cmd = "%s purge %s" % (
                    self.umglobal.settings['apt-get-string'], deleteString)

        if cmd != "":
            self.apt.createPackageLists(cmd)
            msg = self.getDistUpgradeInfo()
            answer = True
            if msg != "":
                contMsg = _("Execute maintenance changes?")
                answer = self.showConfirmationDlg(contMsg, msg)
            if answer:
                if updateGrub:
                    cmd += "; update-grub"
                if blnNotNeeded:
                    cmd += "; %s purge $(COLUMNS=132 dpkg -l | grep ^rc | awk '{ print $2 }')" % self.umglobal.settings[
                        'apt-get-string']
                self.showOutput()
                nid = 'ummaintenance'
                self.prepForCommand(nid)
                self.terminal.executeCommand(cmd, nid)
                self.log.write("Execute command: %s (%s)" % (cmd, nid),
                               "UM.executeMaintenance", "debug")

        self.enableMaintenance(True)

    # ===============================================
    # General functions
    # ===============================================

    def prepForCommand(self, nid):
        os.system("touch %s" % self.umglobal.umfiles[nid])
        if not self.quickUpdate:
            self.btnRefresh.set_sensitive(False)
            self.btnInstall.set_sensitive(False)
            self.btnMaintenance.set_sensitive(False)

    def on_line_added(self, terminal, line):
        if line.strip()[0:2].upper() == "E:":
            self.log.write(line, "UM.on_line_added", "error")
        else:
            self.log.write(line, "UM.on_line_added", "info")

    def on_command_done(self, terminal, pid, nid):
        if nid != "init":
            self.log.write("Command finished (pid=%s, nid=%s)" % (pid, nid),
                           "UM.on_command_done", "info")
            if nid == "uminstallum":
                # Reload UM
                self.log.write(
                    "Updating UM: kill process of updatemanagerpref.py",
                    "UM.on_command_done", "debug")
                self.umglobal.killScriptProcess("updatemanagerpref.py")
                # Reload tray as user
                self.log.write(
                    "Updating UM: kill process of updatemanagertray.py",
                    "UM.on_command_done", "debug")
                self.umglobal.killScriptProcess("updatemanagertray.py")
                cmd = "sudo -u {} updatemanager -t -r".format(self.user)
                os.system(cmd)
                self.log.write(
                    "UM updated: reload tray as user {}".format(self.user),
                    "UM.on_command_done", "debug")
                # Reload UM window
                cmd = join(self.umglobal.scriptDir, "updatemanager.py")
                if self.quickUpdate:
                    cmd = join(self.umglobal.scriptDir, "updatemanager.py -q")
                self.umglobal.reloadWindow(cmd, self.user)
                self.log.write(
                    "UM updated: reload {0} as user {1}".format(
                        cmd, self.user), "UM.on_command_done", "debug")
            elif nid == "umrefresh":
                # Build installed packages info list
                self.apt.createPackagesInfoList()
                # Run post update when needed
                self.postUpdate()
            elif nid == "ummaintenance":
                self.enableMaintenance(True)
                self.fillTreeViewMaintenance()
                self.btnInstall.set_sensitive(True)
                self.btnRefresh.set_sensitive(True)
                self.btnPackages.set_sensitive(True)
                self.btnMaintenance.set_sensitive(True)
                self.showMaintenance()
            elif nid == 'umupd':
                # Save update version in hist file
                self.umglobal.saveHistVersion("upd",
                                              self.umglobal.serverUpdVersion)
                self.log.write(
                    "Save history upd=%s" % self.umglobal.serverUpdVersion,
                    "UM.on_command_done", "debug")
                self.deleteScripts()

            # Refresh data after install or update
            self.umglobal.collectData()
            self.apt.createPackageLists()
            self.fillTreeView()

            # Enable the buttons and load the info page
            self.log.write(
                "Re-initiate window after terminal command: %s" %
                str(not self.quickUpdate), "UM.on_command_done", "debug")
            if not self.quickUpdate:
                self.btnInstall.set_sensitive(True)
                self.btnRefresh.set_sensitive(True)
                self.btnPackages.set_sensitive(True)
                self.btnMaintenance.set_sensitive(True)
                self.btnInfo.set_sensitive(True)
                self.loadInfo()

                if self.umglobal.newUpd:
                    self.showInfo()
                else:
                    # This throws a lock file error in Plasma5
                    #aptHasErrors = self.apt.aptHasErrors()
                    #if aptHasErrors is not None:
                    #MessageDialog(self.aptErrorText, aptHasErrors)
                    #el
                    if self.upgradables:
                        self.showPackages()
                    else:
                        self.showInfo()
                        MessageDialog(self.btnInfo.get_label(),
                                      self.uptodateText)
                self.log.write("Re-initiate window complete",
                               "UM.on_command_done", "debug")

            # Cleanup name file(s)
            for fle in glob(join(self.umglobal.filesDir, '.um*')):
                remove(fle)

    def createLogString(self, packagesList):
        lst = []
        for data in packagesList:
            lst.append(data[0])
        return ' '.join(lst)

    def refresh(self):
        # Refresh server info
        print((self.umglobal.hasInternet))
        self.umglobal.getServerInfo()
        print((self.umglobal.hasInternet))

        # Check of programs locking apt
        prog = self.apt.getAptCacheLockedProgram(
            self.umglobal.settings["apt-packages"])
        if prog is not None:
            msg = _("Another program is locking the apt cache\n\n"
                    "Please, close the program before refreshing:\n"
                    "* %s" % prog)
            MessageDialog(self.btnRefresh.get_label(), msg)
            self.log.write("%s is locking the apt cache" % prog, "UM.refresh",
                           "warning")
        elif self.umglobal.hasInternet:
            if not self.quickUpdate:
                # Update the apt cache
                self.btnPreferences.set_sensitive(True)
                self.btnOutput.set_sensitive(True)
                self.btnRefresh.set_sensitive(False)
                self.btnInstall.set_sensitive(False)
                self.btnMaintenance.set_sensitive(False)
                self.btnPackages.set_sensitive(True)
                self.showOutput()
            cmd = "dpkg --configure -a; %s -f install; apt-get update" % self.umglobal.settings[
                'apt-get-string']
            nid = 'umrefresh'
            self.prepForCommand(nid)
            if self.quickUpdate:
                self.ec.run(cmd)
            else:
                self.terminal.executeCommand(cmd, nid)
            self.apt.initAptShowVersions()
            self.log.write("Execute command: %s (%s)" % (cmd, nid),
                           "UM.refresh", "debug")
        else:
            if not self.quickUpdate:
                # No internet connection
                self.btnInstall.set_sensitive(True)
                self.btnRefresh.set_sensitive(True)
                self.btnPackages.set_sensitive(True)
                self.btnMaintenance.set_sensitive(True)
                self.btnInfo.set_sensitive(True)
                self.btnOutput.set_sensitive(True)
                self.btnPreferences.set_sensitive(True)
                self.loadInfo()
                self.showInfo()

    def postUpdate(self):
        # Check for changed version information
        if self.umglobal.newUpd and self.umglobal.serverUpdVersion is not None:
            self.getScripts([
                self.umglobal.settings['pre-upd'].replace(
                    "[VERSION]", self.umglobal.serverUpdVersion),
                self.umglobal.settings['post-upd'].replace(
                    "[VERSION]", self.umglobal.serverUpdVersion)
            ])

    def fillTreeView(self):
        # First check if this application is upgradable
        self.upgradableUM = self.getUpgradablePackages(
            packageNames=["updatemanager"])
        if self.upgradableUM:
            self.upgradables = self.upgradableUM
        else:
            # Get a list of packages that can be upgraded
            self.upgradableUM = []
            self.upgradables = self.getUpgradablePackages()
            #if not self.upgradables:
            ## Check for black listed packages
            #cmd = "dpkg --get-selections | grep hold$ | awk '{print $1}'"
            #lst = self.ec.run(cmd, False)
            #for pck in lst:
            #self.upgradables.append([pck.strip(), _("blacklisted"), ""])

        if not self.quickUpdate:
            contentList = [[
                _("Package"),
                _("Current version"),
                _("New version")
            ]] + self.upgradables
            self.tvHandler.fillTreeview(contentList=contentList,
                                        columnTypesList=['str', 'str', 'str'],
                                        firstItemIsColName=True)

    def getUpgradablePackages(self, packageNames=[]):
        upckList = []
        if packageNames:
            upckList = []
            for packageName in packageNames:
                for upck in self.apt.upgradablePackages:
                    if upck[0] == packageName:
                        upckList.append(upck)
                        break
        else:
            upckList = self.apt.upgradablePackages
        return upckList

    def getDistUpgradeInfo(self, upgradablesOnly=False):
        info = ""
        if upgradablesOnly:
            if self.apt.upgradablePackages:
                info = "<strong>%s</strong><br>" % self.apt.upgradablePackagesText
                for pck in self.apt.upgradablePackages:
                    info += "%s " % pck[0]
        else:
            if self.apt.removedPackages:
                info = "<strong>%s</strong><br>" % self.removedPackagesText
                for pck in self.apt.removedPackages:
                    info += "%s " % pck[0]
            if self.apt.newPackages:
                if info != "":
                    info += "<p>&nbsp;</p>"
                info += "<strong>%s</strong><br>" % self.newPackagesText
                for pck in self.apt.newPackages:
                    info += "%s " % pck[0]
            if self.apt.heldbackPackages:
                if info != "":
                    info += "<p>&nbsp;</p>"
                info += "<strong>%s</strong><br>" % self.heldbackPackagesText
                for pck in self.apt.heldbackPackages:
                    info += "%s " % pck[0]
            if self.apt.downgradablePackages:
                if info != "":
                    info += "<p>&nbsp;</p>"
                info += "<strong>%s</strong><br>" % self.downgradePackagesText
                for pck in self.apt.downgradablePackages:
                    info += "%s " % pck[0]
        return info

    def showPackages(self):
        self.nbMain.set_current_page(0)

    def showOutput(self):
        self.nbMain.set_current_page(1)
        self.terminal.grab_focus()

    def showInfo(self):
        self.nbMain.set_current_page(2)

    def showMaintenance(self):
        self.nbMain.set_current_page(3)

    def showConfirmationDlg(self, title, message):
        head = "<html><head><style>body { font-family: Arial, Helvetica, Verdana, Sans-serif; font-size: 12px; color: #555555; background: #ffffff; }</style></head><body>"
        end = "</body></html>"
        html = "%s%s%s" % (head, message, end)
        sw = Gtk.ScrolledWindow()
        sw.add(SimpleBrowser(html))
        return CustomQuestionDialog(title, sw, 550, 300, self.window).show()

    # Get pre-install script and post-install script from the server
    def getScripts(self, files):
        for fle in files:
            flePath = join(self.umglobal.filesDir, fle)
            if not exists(flePath):
                # Get the new scripts if they exist
                url = "%s/%s/%s" % (self.umglobal.settings['solydxk'],
                                    self.umglobal.settings["umfilesdir"], fle)
                try:
                    txt = urlopen(url).read().decode('utf-8')
                    if txt != '':
                        # Save to a file and make executable
                        self.log.write("Save script = %s" % flePath,
                                       "UM.getScripts", "debug")
                        with open(flePath, 'w') as f:
                            f.write(txt)
                        chmod(flePath, 0o755)
                except:
                    pass

    def loadInfo(self):
        languageDir = self.get_language_dir()
        url = join("file://%s" % languageDir,
                   self.umglobal.settings['up-to-date'])
        self.btnInfo.set_icon_name("help-about")
        if self.upgradables:
            url = join("file://%s" % languageDir,
                       self.umglobal.settings['updates'])
            if self.umglobal.newUpd:
                url = "%s/%s/%s" % (self.umglobal.settings['solydxk'],
                                    self.umglobal.settings["umfilesdir"],
                                    self.umglobal.settings['upd-info'])
        elif self.umglobal.serverUpdVersion is None:
            url = join("file://%s" % languageDir,
                       self.umglobal.settings['not-found'])

        self.log.write("Load info url: %s" % url, "UM.loadInfo", "debug")

        children = self.swInfo.get_children()
        if children:
            children[0].openUrl(url)
        else:
            self.swInfo.add(SimpleBrowser(url))

    def get_language_dir(self):
        # First test if full locale directory exists, e.g. html/pt_BR,
        # otherwise perhaps at least the language is there, e.g. html/pt
        # and if that doesn't work, try html/pt_PT
        lang = self.get_current_language()
        path = join(self.umglobal.htmlDir, lang)
        if not isdir(path):
            base_lang = lang.split('_')[0].lower()
            path = join(self.umglobal.htmlDir, base_lang)
            if not isdir(path):
                path = join(self.umglobal.htmlDir,
                            "{}_{}".format(base_lang, base_lang.upper()))
                if not isdir(path):
                    path = join(self.umglobal.htmlDir, 'en')
        return path

    def get_current_language(self):
        lang = os.environ.get('LANG', 'US').split('.')[0]
        if lang == '':
            lang = 'en'
        return lang

    def pushMessage(self, message):
        if message is not None:
            context = self.statusbar.get_context_id('message')
            self.statusbar.push(context, message)

    def checkFilesDir(self):
        if not exists(self.umglobal.filesDir):
            makedirs(self.umglobal.filesDir)
        oldFiles = glob(join(self.umglobal.scriptDir, 'pre-*')) + \
                   glob(join(self.umglobal.scriptDir, 'post-*')) + \
                   [join(self.umglobal.scriptDir, 'updatemanager.hist')] + \
                   [join(self.umglobal.scriptDir, 'mirrors.list')]
        for fle in oldFiles:
            if exists(fle):
                fleName = basename(fle)
                if not exists(join(self.umglobal.filesDir, fleName)):
                    move(fle, self.umglobal.filesDir)
                else:
                    remove(fle)
        chmod(self.umglobal.filesDir, 0o777)

    def deleteScripts(self, UpdVersion=None):
        UpdVersion = "*"
        if UpdVersion is not None:
            UpdVersion = "*%s" % UpdVersion

        oldFiles = glob(join(
            self.umglobal.filesDir, "pre-%s" % UpdVersion)) + glob(
                join(self.umglobal.filesDir, "post-%s" % UpdVersion))
        for fle in oldFiles:
            remove(fle)
            self.log.write("Cleanup file: %s" % fle, "UM.deleteScripts",
                           "debug")

    # Close the gui
    def on_windowMain_destroy(self, widget):
        # Close the app
        Gtk.main_quit()
コード例 #50
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 == "URL":
                    continue
                if mirror.endswith('/'):
                    mirror = mirror[:-1]

                # Only check Debian repository: SolydXK is on the same server
                httpCode = -1
                dlSpeed = 0
                dl_file = "umfiles/speedtest"
                if "debian" in mirrorData[2].lower():
                    dl_file = self.umglobal.settings["dl-test"]
                url = os.path.join(mirror, dl_file)
                http = "http://"
                if url[0:4] == "http":
                    http = ""
                cmd = "curl --connect-timeout 5 -m 5 -w '%%{http_code}\n%%{speed_download}\n' -o /dev/null -s --location %s%s" % (
                    http, 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 == 302:
            return "302: found (redirect)"
        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
コード例 #51
0
class RefreshThread(threading.Thread):

    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"

    def run(self):

        gtk.gdk.threads_enter()
        vpaned_position = self.builder.get_object("vpaned_main").get_position()
        gtk.gdk.threads_leave()
        try:
            self.log.writelines("++ Starting refresh\n")
            self.log.flush()
            gtk.gdk.threads_enter()

            statusbar = self.builder.get_object("statusbar")
            context_id = statusbar.get_context_id("updatemanager")

            statusbar.push(context_id, _("Starting refresh..."))
            self.window.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
            self.window.set_sensitive(False)
            self.builder.get_object("label_error_detail").set_text("")
            self.builder.get_object("hbox_error").hide()
            self.builder.get_object("scrolledwindow1").hide()
            self.builder.get_object("viewport_error").hide()
            self.builder.get_object("label_error_detail").hide()
            self.builder.get_object("main_image_error").hide()
            # Starts the blinking
            self.statusIcon.set_from_file(self.prefs["icon_busy"])
            self.statusIcon.set_tooltip(_("Checking for updates"))
            self.builder.get_object("vpaned_main").set_position(vpaned_position)
            #self.statusIcon.set_blinking(True)
            gtk.gdk.threads_leave()

            model = gtk.TreeStore(str, str, str, str, int, str, str, str)    # upgrade, pkgname, oldversion, newversion, size, strsize, description, sourcePackage)
            model.set_sort_column_id(1, gtk.SORT_ASCENDING)

            #self.prefs = read_configuration()

            # Check to see if no other APT process is running
            cmd = 'ps -U root -o comm'
            pslist = self.ec.run(cmd, False)
            running = False
            for process in pslist:
                if process.strip() in ["dpkg", "apt-get", "synaptic", "update-manager", "adept", "adept-notifier"]:
                    running = True
                    break
            if running:
                gtk.gdk.threads_enter()
                self.statusIcon.set_from_file(self.prefs["icon_unknown"])
                self.statusIcon.set_tooltip(_("Another application is using APT"))
                statusbar.push(context_id, _("Another application is using APT"))
                self.log.writelines("-- Another application is using APT\n")
                self.log.flush()
                #self.statusIcon.set_blinking(False)
                self.window.window.set_cursor(None)
                self.window.set_sensitive(True)
                gtk.gdk.threads_leave()
                return False

            gtk.gdk.threads_enter()
            statusbar.push(context_id, _("Finding the list of updates..."))
            self.builder.get_object("vpaned_main").set_position(vpaned_position)
            gtk.gdk.threads_leave()
            if self.app_hidden:
                updates = commands.getoutput(self.curdir + "/checkAPT.py | grep \"###\"")
            else:
                updates = commands.getoutput(self.curdir + "/checkAPT.py --use-synaptic %s | grep \"###\"" % self.window.window.xid)

            # Look for updatemanager
            if ("UPDATE###updatemanager###" in updates):
                new_updatemanager = True
            else:
                new_updatemanager = False

            updates = string.split(updates, "\n")

            # Look at the packages one by one
            list_of_packages = ""
            num_updates = 0
            download_size = 0
            num_ignored = 0
            ignored_list = []
            if os.path.exists(self.cfgignored):
                blacklist_file = open(self.cfgignored, "r")
                for blacklist_line in blacklist_file:
                    ignored_list.append(blacklist_line.strip())
                blacklist_file.close()

            if (len(updates) is None):
                self.statusIcon.set_from_file(self.prefs["icon_up2date"])
                self.statusIcon.set_tooltip(_("Your system is up to date"))
                statusbar.push(context_id, _("Your system is up to date"))
                self.log.writelines("++ System is up to date\n")
                self.log.flush()
            else:
                for pkg in updates:
                    values = string.split(pkg, "###")
                    if len(values) == 7:
                        status = values[0]
                        if (status == "ERROR"):
                            error_msg = commands.getoutput(os.path.join(self.curdir, "checkAPT.py"))
                            gtk.gdk.threads_enter()
                            self.statusIcon.set_from_file(self.prefs["icon_error"])
                            self.statusIcon.set_tooltip(_("Could not refresh the list of packages"))
                            statusbar.push(context_id, _("Could not refresh the list of packages"))
                            self.log.writelines("-- Error in checkAPT.py, could not refresh the list of packages\n")
                            self.log.flush()
                            self.builder.get_object("label_error_detail").set_text(error_msg)
                            self.builder.get_object("label_error_detail").show()
                            self.builder.get_object("viewport1").show()
                            self.builder.get_object("scrolledwindow1").show()
                            self.builder.get_object("main_image_error").show()
                            self.builder.get_object("hbox_error").show()
                            #self.statusIcon.set_blinking(False)
                            self.window.window.set_cursor(None)
                            self.window.set_sensitive(True)
                            #statusbar.push(context_id, _(""))
                            gtk.gdk.threads_leave()
                            return False
                        package = values[1]
                        packageIsBlacklisted = False
                        for blacklist in ignored_list:
                            if fnmatch.fnmatch(package, blacklist):
                                num_ignored = num_ignored + 1
                                packageIsBlacklisted = True
                                break

                        if packageIsBlacklisted:
                            continue

                        newVersion = values[2]
                        oldVersion = values[3]
                        size = int(values[4])
                        source_package = values[5]
                        description = values[6]

                        strSize = self.size_to_string(size)

                        if (new_updatemanager):
                            if (package == "updatemanager"):
                                list_of_packages = list_of_packages + " " + package
                                itr = model.insert_before(None, None)
                                model.set_value(itr, INDEX_UPGRADE, "true")
                                model.row_changed(model.get_path(itr), itr)
                                model.set_value(itr, INDEX_PACKAGE_NAME, package)
                                model.set_value(itr, INDEX_OLD_VERSION, oldVersion)
                                model.set_value(itr, INDEX_NEW_VERSION, newVersion)
                                model.set_value(itr, INDEX_SIZE, size)
                                model.set_value(itr, INDEX_STR_SIZE, strSize)
                                model.set_value(itr, INDEX_DESCRIPTION, description)
                                model.set_value(itr, INDEX_SOURCE_PACKAGE, source_package)
                                num_updates = num_updates + 1
                        else:
                            list_of_packages = list_of_packages + " " + package
                            itr = model.insert_before(None, None)
                            model.set_value(itr, INDEX_UPGRADE, "true")
                            download_size = download_size + size
                            model.row_changed(model.get_path(itr), itr)
                            model.set_value(itr, INDEX_PACKAGE_NAME, package)
                            model.set_value(itr, INDEX_OLD_VERSION, oldVersion)
                            model.set_value(itr, INDEX_NEW_VERSION, newVersion)
                            model.set_value(itr, INDEX_SIZE, size)
                            model.set_value(itr, INDEX_STR_SIZE, strSize)
                            model.set_value(itr, INDEX_DESCRIPTION, description)
                            model.set_value(itr, INDEX_SOURCE_PACKAGE, source_package)
                            num_updates = num_updates + 1

                gtk.gdk.threads_enter()

                if (new_updatemanager):
                    self.statusString = _("A new version of the update manager is available")
                    self.statusIcon.set_from_file(self.prefs["icon_updates"])
                    self.statusIcon.set_tooltip(self.statusString)
                    statusbar.push(context_id, self.statusString)
                    self.log.writelines("++ Found a new version of updatemanager\n")
                    self.log.flush()
                else:
                    if self.newUpVersion is not None:
                        self.statusString = _("A new update pack is available (version: %s)" % self.newUpVersion)
                        self.statusIcon.set_from_file(self.prefs["icon_updates"])
                        self.statusIcon.set_tooltip(self.statusString)
                        statusbar.push(context_id, self.statusString)
                        self.log.writelines("++ %s\n" % self.statusString)
                        self.log.flush()
                    elif (num_updates > 0):
                        if (num_updates == 1):
                            if (num_ignored == 0):
                                self.statusString = _("1 recommended update available (%(size)s)") % {'size': self.size_to_string(download_size)}
                            elif (num_ignored == 1):
                                self.statusString = _("1 recommended update available (%(size)s), 1 ignored") % {'size': self.size_to_string(download_size)}
                            elif (num_ignored > 1):
                                self.statusString = _("1 recommended update available (%(size)s), %(ignored)d ignored") % {'size': self.size_to_string(download_size), 'ignored': num_ignored}
                        else:
                            if (num_ignored == 0):
                                self.statusString = _("%(recommended)d recommended updates available (%(size)s)") % {'recommended': num_updates, 'size': self.size_to_string(download_size)}
                            elif (num_ignored == 1):
                                self.statusString = _("%(recommended)d recommended updates available (%(size)s), 1 ignored") % {'recommended': num_updates, 'size': self.size_to_string(download_size)}
                            elif (num_ignored > 0):
                                self.statusString = _("%(recommended)d recommended updates available (%(size)s), %(ignored)d ignored") % {'recommended': num_updates, 'size': self.size_to_string(download_size), 'ignored': num_ignored}
                        self.statusIcon.set_from_file(self.prefs["icon_updates"])
                        self.statusIcon.set_tooltip(self.statusString)
                        statusbar.push(context_id, self.statusString)
                        self.log.writelines("++ Found " + str(num_updates) + " recommended software updates\n")
                        self.log.flush()
                    else:
                        self.statusIcon.set_from_file(self.prefs["icon_up2date"])
                        self.statusIcon.set_tooltip(_("Your system is up to date"))
                        statusbar.push(context_id, _("Your system is up to date"))
                        self.log.writelines("++ System is up to date\n")
                        self.log.flush()

            self.log.writelines("++ Refresh finished\n")
            self.log.flush()
            # Stop the blinking
            #self.statusIcon.set_blinking(False)
            self.builder.get_object("notebook_details").set_current_page(0)
            self.window.window.set_cursor(None)
            self.treeview_update.set_model(model)
            del model
            self.window.set_sensitive(True)
            self.builder.get_object("vpaned_main").set_position(vpaned_position)
            gtk.gdk.threads_leave()

        except Exception, detail:
            print "-- Exception occured in the refresh thread: " + str(detail)
            self.log.writelines("-- Exception occured in the refresh thread: " + str(detail) + "\n")
            self.log.flush()
            gtk.gdk.threads_enter()
            self.statusIcon.set_from_file(self.prefs["icon_error"])
            self.statusIcon.set_tooltip(_("Could not refresh the list of packages"))
            #self.statusIcon.set_blinking(False)
            self.window.window.set_cursor(None)
            self.window.set_sensitive(True)
            statusbar.push(context_id, _("Could not refresh the list of packages"))
            self.builder.get_object("vpaned_main").set_position(vpaned_position)
            gtk.gdk.threads_leave()
コード例 #52
0
class UmRefresh(object):
    def __init__(self, umglobal, indicator):
        self.ec = ExecCmd()
        self.indicator = indicator
        self.umglobal = umglobal
        self.quit = False

    def changeIcon(self, iconName, tooltip):
        if self.umglobal.isKf5:
            # Use this for KDE5
            #print(("> icon: {}, tooltip: {}".format(iconName, tooltip)))
            # tooltop is not showing
            self.indicator.set_icon_full(self.umglobal.settings[iconName],
                                         tooltip)
            # Attention icon is not doing anything
            #self.indicator.set_attention_icon_full(self.umglobal.settings[iconName], tooltip)
            # This isn't working either: Plasma 5 is not being refreshed, 4 not showing anything at all
            #self.indicator.set_title("<strong>{}</strong><br>{}".format(self.umglobal.title, tooltip))
        else:
            # Use this for KDE4
            iconPath = join(self.umglobal.iconsDir,
                            self.umglobal.settings[iconName])
            #print(("> icon: {}, tooltip: {}".format(iconPath, tooltip)))
            self.indicator.set_from_file(iconPath)
            self.indicator.set_tooltip_text(tooltip)

    def refresh(self):
        # Don't refresh if the apt cache is being refreshed
        if not self.isAptExecuting():
            if not self.umglobal.isProcessRunning("updatemanager.py"):
                for fle in glob(join(self.umglobal.filesDir, ".um*")):
                    remove(fle)

            self.umglobal.getLocalInfo()
            if self.umglobal.repos:
                if self.umglobal.hasInternet:
                    # Check update status
                    if self.checkForUpdates():
                        if self.umglobal.newUpd:
                            self.umglobal.updatesText = _(
                                "New update: %s" %
                                self.umglobal.serverUpdVersion)
                            print((self.umglobal.updatesText))
                            self.changeIcon("icon-updates",
                                            self.umglobal.updatesText)
                        else:
                            self.umglobal.updatesText = _(
                                "There are updates available")
                            print((self.umglobal.updatesText))
                            self.changeIcon("icon-updates",
                                            self.umglobal.updatesText)
                    else:
                        print((self.umglobal.connectedText))
                        self.changeIcon("icon-connected",
                                        self.umglobal.connectedText)
                else:
                    print((self.umglobal.disconnectedText))
                    self.changeIcon("icon-disconnected",
                                    self.umglobal.disconnectedText)
                    # Check every 30 seconds if there is a connection
                    GObject.timeout_add_seconds(30, self.refresh)
                    self.umglobal.getServerInfo()
                    return True
            else:
                self.umglobal.errorText = _(
                    "Unable to retrieve sources information")
                print((self.umglobal.errorText))
                self.changeIcon("icon-error", self.umglobal.errorText)

            print("Done refreshing")

    def isAptExecuting(self):
        procLst = self.ec.run("ps -U root -u root -o comm=", False)
        for aptProc in self.umglobal.settings["apt-packages"]:
            if aptProc in procLst:
                return True
        return False

    def checkForUpdates(self):
        # Get updateable packages which are not held back
        #cmd = "env LANG=C aptitude search '~U'"
        cmd = "env LANG=C apt list --upgradable"
        output = self.ec.run(cmd=cmd, realTime=False)

        upgradables = []
        for line in output:
            if '/' in line and 'upgradable' in line:
                upgradables.append(line.split('/')[0])

        if upgradables:
            # Get packages that were kept back by the user
            cmd = "env LANG=C dpkg --get-selections | grep hold$ | awk '{print $1}'"
            keptbacks = self.ec.run(cmd=cmd, realTime=False)
            if keptbacks:
                for upd in upgradables:
                    if upd not in keptbacks:
                        return True
            else:
                return True
        else:
            return False
コード例 #53
0
def getInstalledThemes():
    cmd = '/usr/sbin/plymouth-set-default-theme --list'
    ec = ExecCmd(log)
    instThemes = ec.run(cmd, False)
    return instThemes
コード例 #54
0
class UserShare(object):
    def __init__(self):
        self.ec = ExecCmd()
        self.home = expanduser("~/")
        self.systemNames = self.ec.run("cat /etc/passwd | cut -d':' -f 1")

    def getShares(self, inclInfo=False, inclInfoAsDict=False):
        shares = None
        lst = self.ec.run("net usershare list -l")
        if inclInfo:
            if inclInfoAsDict:
                shares = {}
                for share in lst:
                    if not 'info_fn:' in share:
                        shares[share] = self.getShareInfo(share)
                    else:
                        self.removeCorruptShare(share)
            else:
                shares = []
                for share in lst:
                    if not 'info_fn:' in share:
                        shares.append([share, self.getShareInfo(share)])
                    else:
                        self.removeCorruptShare(share)
        else:
            shares = lst
        return shares

    def getShareInfo(self, share):
        ret = []
        if share is not None and share.strip() != "":
            ret = self.ec.run("net usershare info -l '%s'" % share)
        return ret

    def removeCorruptShare(self, info_fn_line):
        matchObj = re.search("(/.*)\s+is\s+not", info_fn_line)
        if matchObj:
            path = matchObj.group(1)
            if exists(path):
                try:
                    os.remove(path)
                except:
                    # Best effort
                    pass

    def doesShareExist(self, share):
        info = self.getShareInfo(share)
        if info:
            return True
        else:
            return False

    def needRoot(self, path):
        writable = os.access(path, os.W_OK)
        if writable:
            return False
        else:
            return True

    def getPathFromName(self, name):
        path = None
        info = self.getShareInfo(name)
        for line in info:
            if line.startswith("path="):
                path = line.replace("path=", "")
        return path

    def createShare(self,
                    path,
                    name,
                    comment=None,
                    public=True,
                    readonly=True):
        ret = []
        if name in self.systemNames:
            ret.append(
                _("Cannot create share.\nShare name %(share)s is already a valid system user name."
                  ) % {"share": name})
        elif self.doesShareExist(name):
            ret.append(
                _("Cannot create share.\nShare already exists: %(share)s") %
                {"share": name})
        elif not exists(path):
            ret.append(
                _("Cannot create share.\nPath does not exist: %(path)s") %
                {"path": path})
        else:
            if comment is None:
                comment = ""
            guest_ok = "y"
            if not public:
                guest_ok = "n"
            read_only = "R"
            if not readonly:
                read_only = "F"

            if self.needRoot(path):
                ret.append(
                    _("You do not have sufficient permission to create a share on:\n%(path)s"
                      ) % {"path": path})
            else:
                cmd = "net usershare add '%(name)s' '%(path)s' '%(comment)s' Everyone:%(read_only)s guest_ok=%(guest_ok)s" % {
                    "name": name,
                    "path": path,
                    "comment": comment,
                    "read_only": read_only,
                    "guest_ok": guest_ok
                }
                print(cmd)
                ret = self.ec.run(cmd, False)

                if self.doesShareExist(name):
                    if not readonly:
                        cmd = "chmod 777 %(path)s" % {"path": path}
                        print(cmd)
                        ret.extend(self.ec.run(cmd, False))
                else:
                    ret.insert(
                        0,
                        _("Failed to create new share: {} on {}.".format(
                            name, path)))

        return ret

    def removeShare(self, name):
        ret = []
        if self.doesShareExist(name):
            path = self.getPathFromName(name)
            if self.needRoot(path):
                ret.append(
                    _("You do not have sufficient permission on path: %(path)s"
                      ) % {"path": path})
            else:
                cmd = "net usershare delete '%(name)s'" % {"name": name}
                print(cmd)
                ret = self.ec.run(cmd, False)

                if self.doesShareExist(name):
                    ret.insert(
                        0,
                        _("Failed to remove share: {} from {}.".format(
                            name, path)))
                else:
                    if exists(path):
                        cmd = "chmod 755 %(path)s" % {"path": path}
                        print(cmd)
                        ret.extend(self.ec.run(cmd, False))

        return ret
コード例 #55
0
class UmGlobal(object):

    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()

    def collectData(self):
        self.getLocalInfo()
        self.getServerInfo()

    def getServerInfo(self):
        if self.umfilesUrl is not None:
            url = "%s/%s" % (self.umfilesUrl, self.settings['repo-info'])
            #print((">>> url = %s" % url))
            try:
                cont = urlopen(url, timeout=self.settings["timeout-secs"])
                self.hasInternet = True
                for line in cont.readlines():
                    # urlopen returns bytes, need to convert to str
                    line = line.decode('utf-8').strip()
                    elements = line.split("=")
                    parameter = elements[0].strip()
                    value = elements[1].strip()
                    #print((">>> line = %s" % line))
                    #print((">>> parameter = %s" % parameter))
                    #print((">>> value = %s" % value))
                    if len(value) > 0:
                        # Write the parameter, and the value if no hist file exist: assume clean install
                        self.writeNonExistingHist(parameter)
                        if parameter == "upd":
                            self.serverUpdVersion = value

                cont.close()

                # Check for new versions
                if self.serverUpdVersion is not None:
                    self.newUpd = self.isNewServerVersion(self.serverUpdVersion, self.localUpdVersion)

            except Exception as detail:
                print(("There is no internet connection: %s" % detail))
                self.hasInternet = False

    def writeNonExistingHist(self, parameter):
        upHistFile = join(self.filesDir, self.settings['hist'])
        if not exists(upHistFile):
            self.saveHistVersion(parameter, "2000.01.01")
            self.getLocalInfo()

    def isNewServerVersion(self, serverVersion, localVersion):
        isNew = False
        serverVersion = str(serverVersion)
        localVersion = str(localVersion)
        if len(serverVersion) == len(localVersion):
            valArr = serverVersion.split('.')
            instUpArr = localVersion.split('.')
            instDate = date(int(instUpArr[0]), int(instUpArr[1]), int(instUpArr[2]))
            valDate = date(int(valArr[0]), int(valArr[1]), int(valArr[2]))
            if valDate > instDate:
                # Server version is newer
                isNew = True
        return isNew

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

    def getLocalInfo(self):
        # Get configured repos
        self.repos = []
        with open("/etc/apt/sources.list", 'r') as f:
            lines = f.readlines()
        for line in lines:
            line = line.strip()
            matchObj = re.search("^deb\s*(http[:\/a-zA-Z0-9\.\-]*)", line)
            if matchObj:
                repo = matchObj.group(1)
                self.repos.append(repo)

        # Cleanup hist file first
        self.cleanupHist()

        # Get the latest local history versions
        self.localUpdVersion = self.getHistVersion(parameter="upd")
        if self.localUpdVersion is None:
            self.localUpdVersion = "2000.01.01"

    def getHistVersion(self, parameter, version=None):
        upHistFile = join(self.filesDir, self.settings['hist'])
        if exists(upHistFile):
            with open(upHistFile, 'r') as f:
                lines = f.readlines()
            for line in lines[::-1]:
                lst = line.split("=")
                if len(lst) == 2:
                    p = lst[0].strip()
                    v = lst[1].strip()
                    if p == parameter and len(v) == 10:
                        if version is not None:
                            # Get latest with given version
                            if version == v:
                                return v
                        else:
                            # Get latest
                            return v
        return None

    def cleanupHist(self):
        upHistFile = join(self.filesDir, self.settings['hist'])
        if exists(upHistFile):
            # Remove old or incorrect entries
            os.system("sed -r '/=.*[a-zA-Z]+/d' %s" % upHistFile)
            # Remove duplicate lines
            os.system("awk '!a[$0]++' %s" % upHistFile)
            #os.chmod(upHistFile, 0o666)

    def saveHistVersion(self, parameter, newVersion):
        histVersion = self.getHistVersion(parameter, newVersion)
        if histVersion != newVersion:
            # Save the file
            upHistFile = join(self.filesDir, self.settings['hist'])
            with open(upHistFile, 'a') as f:
                line = "{0}={1}\n".format(parameter, newVersion)
                print(("> Save history: {}".format(line)))
                f.write(line)

    def getMirrorData(self, excludeMirrors=[], getDeadMirrors=False):
        mirrorData = []

        mirrorsList = join(self.filesDir, basename(self.settings["mirrors-list"]))
        if getDeadMirrors:
            mirrorsList = "%s.dead" % mirrorsList

        #if os.getuid() != 0 and not exists(mirrorsList):
            #mirrorsList = join('/tmp', basename(self.settings["mirrors-list"]))

        try:
            # Download the mirrors list from the server
            url = self.settings["mirrors-list"]
            if getDeadMirrors:
                url = "%s.dead" % url
            txt = urlopen(url).read().decode('utf-8')
            if txt != '':
                # Save to a file
                with open(mirrorsList, 'w') as f:
                    f.write(txt)
        except:
            pass

        if exists(mirrorsList):
            with open(mirrorsList, 'r') as f:
                lines = f.readlines()
            for line in lines:
                data = line.strip().split(',')
                if len(data) > 2:
                    if getDeadMirrors:
                        blnAdd = False
                        for repo in self.repos:
                            if data[2] in repo:
                                blnAdd = True
                                break
                    else:
                        blnAdd = True
                        for excl in excludeMirrors:
                            if excl in data[2]:
                                blnAdd = False
                                break
                    if blnAdd:
                        #print((">>> append data"))
                        mirrorData.append(data)
        return mirrorData

    def getUmFilesUrl(self):
        if self.localUpdVersion is None:
            self.getLocalInfo()

        xkUrl = self.settings['trail']
        url = "%s/%s" % (xkUrl, self.settings["umfilesdir"])
        return url

    def getSettings(self):
        settings = {}

        section = 'url'
        try:
            settings["trail"] = self.cfg.getValue(section, 'trail')
        except:
			# courtesy from our friends of solydxk
            settings["trail"] = 'http://repository.solydxk.com'
            self.saveSettings(section, 'trail', settings["trail"])

        section = 'localfiles'
        try:
            settings["log"] = self.cfg.getValue(section, 'log')
            settings["not-found"] = self.cfg.getValue(section, 'not-found')
            settings["hist"] = self.cfg.getValue(section, 'hist')
        except:
            settings["log"] = 'updatemanager.log'
            settings["not-found"] = 'notfound.html'
            settings["hist"] = 'updatemanager.hist'
            self.saveSettings(section, 'log', settings["log"])
            self.saveSettings(section, 'not-found', settings["not-found"])
            self.saveSettings(section, 'hist', settings["hist"])

        section = 'serverfiles'
        try:
            settings["repo-info"] = self.cfg.getValue(section, 'repo-info')
            settings["upd-info"] = self.cfg.getValue(section, 'upd-info')
        except:
            settings["repo-info"] = 'repo.info'
            settings["upd-info"] = 'update.html'
            self.saveSettings(section, 'repo-info', settings["repo-info"])
            self.saveSettings(section, 'upd-info', settings["upd-info"])

        section = 'serverscripts'
        try:
            settings["pre-upd"] = self.cfg.getValue(section, 'pre-upd')
            settings["post-upd"] = self.cfg.getValue(section, 'post-upd')

        except:
            settings["pre-upd"] = 'pre-upd-[VERSION]'
            settings["post-upd"] = 'post-upd-[VERSION]'
            self.saveSettings(section, 'pre-upd', settings["pre-upd"])
            self.saveSettings(section, 'post-upd', settings["post-upd"])


        section = 'mirror'
        try:
            settings["mirrors-list"] = self.cfg.getValue(section, 'mirrors-list')
            settings["dl-test"] = self.cfg.getValue(section, 'dl-test')
            settings["timeout-secs"] = int(self.cfg.getValue(section, 'timeout-secs'))
        except:
            settings["mirrors-list"] = 'http://mirror.debian.org/staticlist/Mirrors.masterlist'
            settings["dl-test"] = 'README.mirrors.html'
            settings["timeout-secs"] = 10
            self.saveSettings(section, 'mirrors-list', settings["mirrors-list"])
            self.saveSettings(section, 'dl-test', settings["dl-test"])
            self.saveSettings(section, 'timeout-secs', settings["timeout-secs"])

        section = 'icons'
        try:
            settings["icon-apply"] = self.cfg.getValue(section, 'icon-apply')
            settings["icon-disconnected"] = self.cfg.getValue(section, 'icon-disconnected')
            settings["icon-error"] = self.cfg.getValue(section, 'icon-error')
            settings["icon-exec"] = self.cfg.getValue(section, 'icon-exec')
            settings["icon-info"] = self.cfg.getValue(section, 'icon-info')
            settings["icon-unknown"] = self.cfg.getValue(section, 'icon-unknown')
            settings["icon-base"] = self.cfg.getValue(section, 'icon-base')
            settings["icon-warning"] = self.cfg.getValue(section, 'icon-warning')
        except:
            settings["icon-apply"] = '/usr/share/trail/updatemanager/icons/base-apply.png'
            settings["icon-disconnected"] = '/usr/share/trail/updatemanager/icons/base-disconnected.png'
            settings["icon-error"] = '/usr/share/trail/updatemanager/icons/base-error.png'
            settings["icon-exec"] = '/usr/share/trail/updatemanager/icons/base-exec.png'
            settings["icon-info"] = '/usr/share/trail/updatemanager/icons/base-info.png'
            settings["icon-unknown"] = '/usr/share/trail/updatemanager/icons/base-unknown.png'
            settings["icon-base"] = '/usr/share/trail/updatemanager/icons/base.png'
            settings["icon-warning"] = '/usr/share/trail/updatemanager/icons/base-warning.png'
            self.saveSettings(section, 'icon-apply', settings["icon-apply"])
            self.saveSettings(section, 'icon-disconnected', settings["icon-disconnected"])
            self.saveSettings(section, 'icon-error', settings["icon-error"])
            self.saveSettings(section, 'icon-exec', settings["icon-exec"])
            self.saveSettings(section, 'icon-info', settings["icon-info"])
            self.saveSettings(section, 'icon-unknown', settings["icon-unknown"])
            self.saveSettings(section, 'icon-base', settings["icon-base"])
            self.saveSettings(section, 'icon-warning', settings["icon-warning"])

        section = 'misc'
        try:
            settings["allow-terminal-user-input"] = True
            bln = self.cfg.getValue(section, 'allow-terminal-user-input').lower()
            if bln == "false":
                settings["allow-terminal-user-input"] = False
            settings["hrs-check-status"] = int(self.cfg.getValue(section, 'hrs-check-status'))
            settings["umfilesdir"] = self.cfg.getValue(section, 'umfilesdir')
            settings["apt-packages"] = self.cfg.getValue(section, 'apt-packages').split(",")
            settings["hide-tabs"] = self.cfg.getValue(section, 'hide-tabs').split(",")
            settings["um-dependencies"] = self.cfg.getValue(section, 'um-dependencies').split(",")
            settings["apt-get-string"] = self.cfg.getValue(section, 'apt-get-string')
        except:
            settings["allow-terminal-user-input"] = True
            settings["hrs-check-status"] = 1
            settings["umfilesdir"] = 'umfiles'
            settings["apt-packages"] = ["dpkg", "apt-get", "synaptic", "adept", "adept-notifier"]
            settings["hide-tabs"] = ["maintenance"]
            settings["um-dependencies"] = ["gksu", "apt-show-versions", "deborphan", "apt", "curl", "python3-gi", "python-vte", "gir1.2-vte-2.90", "gir1.2-webkit-3.0", "python3", "gir1.2-gtk-3.0", "python3-pyinotify"]
            settings["apt-get-string"] = 'DEBIAN_FRONTEND=gnome apt-get --assume-yes -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold --force-yes'
            self.saveSettings(section, 'allow-terminal-user-input', str(settings["allow-terminal-user-input"]).lower())
            self.saveSettings(section, 'hrs-check-status', settings["hrs-check-status"])
            self.saveSettings(section, 'umfilesdir', settings["umfilesdir"])
            self.saveSettings(section, 'apt-packages', ",".join(settings["apt-packages"]))
            self.saveSettings(section, 'hide-tabs', ",".join(settings["hide-tabs"]))
            self.saveSettings(section, 'um-dependencies', ",".join(settings["um-dependencies"]))
            self.saveSettings(section, 'apt-get-string', settings["apt-get-string"])

        return settings

    def saveSettings(self, section, name, value):
        self.cfg.setValue(section, name, value)

    def isNumeric(self, n):
        try:
            n = complex(n)
            return True
        except:
            try:
                n = float(n, 0)
                return True
            except:
                try:
                    n = int(n, 0)
                    return True
                except:
                    return False

    def strToNumber(self, stringnr, toInt=False):
        nr = 0
        stringnr = stringnr.strip()
        try:
            if toInt:
                nr = int(stringnr)
            else:
                nr = float(stringnr)
        except ValueError:
            nr = 0
        return nr

    def getScriptPids(self, script, returnExistingPid=False):
        pids = []
        try:
            procs = self.ec.run(cmd="ps -ef | grep '{}'".format(script), realTime=False)
            for pline in procs:
                matchObj = re.search("([0-9]+).*:\d\d\s.*python", pline)
                if matchObj:
                    pids.append(int(matchObj.group(1)))
            return pids
        except:
            return pids

    def isSrciptRunning(self, scriptName):
        pids = self.getScriptPids(scriptName)
        if len(pids) > 0:
            return True
        return False

    def killScriptProcess(self, scriptName):
        msg = _('Please enter your password')
        pids = self.getScriptPids(scriptName)
        for pid in pids:
            print(("Kill %s process with pid: %d" % (scriptName, pid)))
            cmd = "gksudo --message \"<b>%s</b>\" kill %d" % (msg, pid)
            self.ec.run(cmd, False)

    def reloadWindow(self, scriptPath, runAsUser):
        path = self.ec.run(cmd="which python3", returnAsList=False)
        if exists(path):
            try:
                os.execl(path, path, scriptPath, runAsUser)
            except OSError as err:
                self.log.write("Reload UM: %s" % str(err), "UM.reloadWindow", "error")

    def getKernelVersion(self):
        version = self.ec.run(cmd="uname -r", realTime=False)[0]
        try:
            ind = version.rindex("-")
            return version[0:ind]
        except:
            return version

    def getKernelArchitecture(self):
        return self.ec.run(cmd="uname -m", realTime=False)[0]

    def getDistribution(self):
        distribution = ""
        if exists('/etc/trail/info'):
            distribution = self.ec.run("cat /etc/trail/info | grep EDITION | cut -d'=' -f 2", realTime=False, returnAsList=False)
        return distribution

    def isUpgrading(self):
        if exists(self.umfiles['umupd']):
            return True
        else:
            return False

    def isRefreshing(self):
        if exists(self.umfiles['umrefresh']):
            return True
        else:
            return False

    def getLoginName(self):
        return self.ec.run(cmd="logname", realTime=False, returnAsList=False)
コード例 #56
0
ファイル: ati.py プロジェクト: AlbertJP/device-driver-manager
class ATI():
    def __init__(self, distribution, loggerObject):
        self.distribution = distribution.lower()
        self.log = loggerObject
        self.ec = ExecCmd(self.log)
    
    # Called from drivers.py: Check for ATI
    def getATI(self):
        # Check for ATI cards
        hwList = []
        cmdGraph = 'lspci | grep VGA'
        hwGraph = self.ec.run(cmdGraph, False)
        #hwGraph = ['00:01.0 VGA compatible controller: Advanced Micro Devices [AMD] nee ATI Wrestler [Radeon HD 6310]']
        for line in hwGraph:
            hw = line[line.find(': ') + 2:]
            self.log.write('ATI card found: ' + hw, 'ati.getATI', 'info')
            atiChk = re.search('\\b' + hwCodes[1] + '\\b', hw.lower())
            if atiChk:
                # Get the ATI chip set serie
                atiSerie = re.search('\s\d{4,}', hw)
                if atiSerie:
                    self.log.write('ATI chip serie found: ' + atiSerie.group(0), 'ati.getATI', 'info')
                    intSerie = functions.strToInt(atiSerie.group(0))
                    # Only add series from atiStartSerie
                    if intSerie >= atiStartSerie:
                        drv = self.getDriver()
                        status = functions.getPackageStatus(drv)
                        self.log.write('ATI ' + drv + ' status: ' + status, 'ati.getATI', 'debug')
                        hwList.append([hw, hwCodes[1], status])
                    else:
                        self.log.write('ATI chip serie not supported: ' + str(intSerie), 'ati.getATI', 'warning')
                        hwList.append([hw, hwCodes[1], packageStatus[2]])
                else:
                    self.log.write('No supported ATI chip serie found: ' + hw, 'ati.getATI', 'warning')
            else:
                self.log.write('No ATI card found', 'ati.getATI', 'warning')
        
        return hwList
    
    # Check distribution and get appropriate driver
    def getDriver(self):
        drv = ''
        if self.distribution == 'debian':
            drv = 'fglrx-driver'
        else:
            drv = 'fglrx'
        return drv
            
    # Get additional packages
    # The second value in the list is a numerical value (True=1, False=0) whether the package must be removed before installation
    def getAdditionalPackages(self, driver):
        drvList = []
        # Common packages
        drvList.append([driver, 1])
        drvList.append(['fglrx-control', 1])
        drvList.append(['build-essential', 0])
        drvList.append(['module-assistant', 0])
        return drvList
    
    # Install the given packages
    def installATIDriver(self, packageList):
        try:
            removePackages = ''
            installPackages = ''
            # Check if drivers are available in the repositories
            for package in packageList:
                # Build install packages string
                installPackages += ' ' + package[0]
                if package[1] == 1:
                    # Check if package is installed
                    # If it is, it's nominated for removal
                    self.log.write('Is package installed: ' + package[0], 'ati.installATIDriver', 'debug')
                    drvChkCmd = 'apt search ' + package[0] + ' | grep ^i | wc -l'
                    drvChk = self.ec.run(drvChkCmd, False)
                    if functions.strToInt(drvChk[0]) > 0:
                        # Build remove packages string
                        removePackages += ' ' + package[0]
            
            # Remove these packages before installation
            if removePackages != '':
                self.log.write('Remove drivers before reinstallation: ' + removePackages, 'ati.installATIDriver', 'debug')
                nvDrvRemCmd = 'apt-get -y --force-yes remove' + removePackages
                self.ec.run(nvDrvRemCmd)
                
            # Purge Nouveau (TODO: is this really necessary?)
            self.log.write('Purge Nouveau drivers: xserver-xorg-video-nouvea', 'ati.installATIDriver', 'debug')
            self.ec.run('apt-get -y --force-yes remove xserver-xorg-video-nouveau')
            
            # Install the packages
            self.log.write('Install drivers: ' + installPackages, 'ati.installATIDriver', 'debug')
            nvDrvInstCmd = 'apt-get -y --force-yes install' + installPackages
            self.ec.run(nvDrvInstCmd)
            
        except Exception, detail:
            self.log.write(detail, 'ati.installATIDriver', 'exception')
コード例 #57
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)
コード例 #58
0
class UmGlobal(object):
    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()

    def collectData(self):
        # Get the settings
        self.settings = self.getSettings()
        # Check if KDE5 is running
        self.isKf5 = self.isProcessRunning("kf5")
        # Collect local information
        self.getLocalInfo()
        # Collect server information
        self.getServerInfo()

    def getServerInfo(self):
        self.newUpd = False
        self.serverUpdVersion = None
        self.hasInternet = False

        url = "%s/%s/%s" % (self.settings['solydxk'],
                            self.settings["umfilesdir"],
                            self.settings['repo-info'])
        cont = None
        try:
            cont = urlopen(url, timeout=10)
        except Exception as e:
            print(("ERROR: unable to reach %s: %s" % (url, e)))
        else:
            self.hasInternet = True
            for line in cont.readlines():
                # urlopen returns bytes, need to convert to str
                line = line.decode('utf-8').strip()
                elements = line.split("=")
                parameter = elements[0].strip()
                value = elements[1].strip()
                if len(value) > 0:
                    # Write the parameter, and the value if no hist file exist: assume clean install
                    self.writeNonExistingHist(parameter)
                    if parameter == "upd":
                        self.serverUpdVersion = value

            cont.close()

            # Check for new versions
            if self.serverUpdVersion is not None:
                self.newUpd = self.isNewServerVersion(self.serverUpdVersion,
                                                      self.localUpdVersion)

    def writeNonExistingHist(self, parameter):
        upHistFile = join(self.filesDir, self.settings['hist'])
        if not exists(upHistFile):
            self.saveHistVersion(parameter, "2000.01.01")
            self.getLocalInfo()

    def isNewServerVersion(self, serverVersion, localVersion):
        isNew = False
        serverVersion = str(serverVersion)
        localVersion = str(localVersion)
        if len(serverVersion) == len(localVersion):
            valArr = serverVersion.split('.')
            instUpArr = localVersion.split('.')
            instDate = date(int(instUpArr[0]), int(instUpArr[1]),
                            int(instUpArr[2]))
            valDate = date(int(valArr[0]), int(valArr[1]), int(valArr[2]))
            if valDate > instDate:
                # Server version is newer
                isNew = True
        return isNew

    def isPackageInstalled(self, package, version=None):
        try:
            cmd = "env LANG=C apt-cache policy %s | grep Installed:" % package
            lst = self.ec.run(cmd, realTime=False)[0].strip().split(' ')
            if version is not None:
                if lst[1] == version:
                    return True
                else:
                    return False
            else:
                return True
        except:
            return False

    def getLocalInfo(self):
        # Get configured repos
        self.repos = []
        skip_repos = ['backports', 'security', 'updates']
        with open("/etc/apt/sources.list", 'r') as f:
            lines = f.readlines()
        for line in lines:
            line = line.strip()
            matchObj = re.search("^deb\s+(https?:[\/a-zA-Z0-9\.\-]*).*", line)
            if matchObj:
                line = matchObj.group(0)
                repo = matchObj.group(1)
                # Do not add these repositories
                if not any(x in line for x in skip_repos):
                    self.repos.append(repo)

        # Cleanup hist file first
        self.cleanupHist()

        # Get the latest local history versions
        self.localUpdVersion = self.getHistVersion(parameter="upd")
        if self.localUpdVersion is None:
            self.localUpdVersion = "2000.01.01"

    def getHistVersion(self, parameter, version=None):
        upHistFile = join(self.filesDir, self.settings['hist'])
        if exists(upHistFile):
            with open(upHistFile, 'r') as f:
                lines = f.readlines()
            for line in lines[::-1]:
                lst = line.split("=")
                if len(lst) == 2:
                    p = lst[0].strip()
                    v = lst[1].strip()
                    if p == parameter and len(v) == 10:
                        if version is not None:
                            # Get latest with given version
                            if version == v:
                                return v
                        else:
                            # Get latest
                            return v
        return None

    def cleanupHist(self):
        upHistFile = join(self.filesDir, self.settings['hist'])
        if exists(upHistFile):
            # Remove old or incorrect entries
            os.system("sed -r '/=.*[a-zA-Z]+/d' %s" % upHistFile)
            # Remove duplicate lines
            os.system("awk '!a[$0]++' %s" % upHistFile)
            #os.chmod(upHistFile, 0o666)

    def saveHistVersion(self, parameter, newVersion):
        histVersion = self.getHistVersion(parameter, newVersion)
        if histVersion != newVersion:
            # Save the file
            upHistFile = join(self.filesDir, self.settings['hist'])
            with open(upHistFile, 'a') as f:
                line = "{0}={1}\n".format(parameter, newVersion)
                f.write(line)

    def getMirrorData(self, excludeMirrors=[], getDeadMirrors=False):
        mirrorData = []

        mirrorsList = join(self.filesDir,
                           basename(self.settings["mirrors-list"]))
        if getDeadMirrors:
            mirrorsList = "%s.dead" % mirrorsList

        #if os.getuid() != 0 and not exists(mirrorsList):
        #mirrorsList = join('/tmp', basename(self.settings["mirrors-list"]))

        try:
            # Download the mirrors list from the server
            url = self.settings["mirrors-list"]
            if getDeadMirrors:
                url = "%s.dead" % url
            txt = urlopen(url).read().decode('utf-8')
            if txt != '':
                # Save to a file
                with open(mirrorsList, 'w') as f:
                    f.write(txt)
        except:
            pass

        if exists(mirrorsList):
            with open(mirrorsList, 'r') as f:
                lines = f.readlines()
            for line in lines:
                data = line.strip().split(',')
                if len(data) > 2:
                    if getDeadMirrors:
                        blnAdd = False
                        for repo in self.repos:
                            if data[2] in repo:
                                blnAdd = True
                                break
                    else:
                        blnAdd = True
                        for excl in excludeMirrors:
                            if excl in data[2]:
                                blnAdd = False
                                break
                    if blnAdd:
                        mirrorData.append(data)
        return mirrorData

    def getSettings(self):
        settings = {}

        section = 'url'
        try:
            settings["solydxk"] = self.cfg.getValue(section, 'solydxk')
        except:
            settings["solydxk"] = 'http://repository.solydxk.com'
            self.saveSettings(section, 'solydxk', settings["solydxk"])

        section = 'localfiles'
        try:
            settings["log"] = self.cfg.getValue(section, 'log')
            settings["not-found"] = self.cfg.getValue(section, 'not-found')
            settings["up-to-date"] = self.cfg.getValue(section, 'up-to-date')
            settings["updates"] = self.cfg.getValue(section, 'updates')
            settings["hist"] = self.cfg.getValue(section, 'hist')
        except:
            settings["log"] = 'updatemanager.log'
            settings["not-found"] = 'notfound.html'
            settings["up-to-date"] = 'uptodate.html'
            settings["updates"] = 'updates.html'
            settings["hist"] = 'updatemanager.hist'
            self.saveSettings(section, 'log', settings["log"])
            self.saveSettings(section, 'not-found', settings["not-found"])
            self.saveSettings(section, 'up-to-date', settings["up-to-date"])
            self.saveSettings(section, 'updates', settings["updates"])
            self.saveSettings(section, 'hist', settings["hist"])

        section = 'serverfiles'
        try:
            settings["repo-info"] = self.cfg.getValue(section, 'repo-info')
            settings["upd-info"] = self.cfg.getValue(section, 'upd-info')
        except:
            settings["repo-info"] = 'repo.info'
            settings["upd-info"] = 'update.html'
            self.saveSettings(section, 'repo-info', settings["repo-info"])
            self.saveSettings(section, 'upd-info', settings["upd-info"])

        section = 'serverscripts'
        try:
            settings["pre-upd"] = self.cfg.getValue(section, 'pre-upd')
            settings["post-upd"] = self.cfg.getValue(section, 'post-upd')

        except:
            settings["pre-upd"] = 'pre-upd-[VERSION]'
            settings["post-upd"] = 'post-upd-[VERSION]'
            self.saveSettings(section, 'pre-upd', settings["pre-upd"])
            self.saveSettings(section, 'post-upd', settings["post-upd"])

        section = 'mirror'
        try:
            settings["mirrors-list"] = self.cfg.getValue(
                section, 'mirrors-list')
            settings["dl-test"] = self.cfg.getValue(section, 'dl-test')
        except:
            settings[
                "mirrors-list"] = 'http://repository.solydxk.com/umfiles/mirrors.list'
            settings["dl-test"] = 'README.mirrors.html'
            self.saveSettings(section, 'mirrors-list',
                              settings["mirrors-list"])
            self.saveSettings(section, 'dl-test', settings["dl-test"])

        section = 'icons'
        try:
            settings["icon-connected"] = self.cfg.getValue(
                section, 'icon-connected')
            settings["icon-disconnected"] = self.cfg.getValue(
                section, 'icon-disconnected')
            settings["icon-error"] = self.cfg.getValue(section, 'icon-error')
            settings["icon-execute"] = self.cfg.getValue(
                section, 'icon-execute')
            settings["icon-updates"] = self.cfg.getValue(
                section, 'icon-updates')
            settings["icon-warning"] = self.cfg.getValue(
                section, 'icon-warning')
        except:
            settings["icon-connected"] = 'connected.svg'
            settings["icon-disconnected"] = 'disconnected.svg'
            settings["icon-error"] = 'error.svg'
            settings["icon-execute"] = 'execute.svg'
            settings["icon-updates"] = 'updates.svg'
            settings["icon-warning"] = 'warning.svg'
            self.saveSettings(section, 'icon-connected',
                              settings["icon-connected"])
            self.saveSettings(section, 'icon-disconnected',
                              settings["icon-disconnected"])
            self.saveSettings(section, 'icon-error', settings["icon-error"])
            self.saveSettings(section, 'icon-execute',
                              settings["icon-execute"])
            self.saveSettings(section, 'icon-updates',
                              settings["icon-updates"])
            self.saveSettings(section, 'icon-warning',
                              settings["icon-warning"])

        section = 'misc'
        try:
            settings["allow-terminal-user-input"] = True
            bln = self.cfg.getValue(section,
                                    'allow-terminal-user-input').lower()
            if bln == "false":
                settings["allow-terminal-user-input"] = False
            settings["hrs-check-status"] = int(
                self.cfg.getValue(section, 'hrs-check-status'))
            settings["umfilesdir"] = self.cfg.getValue(section, 'umfilesdir')
            settings["apt-packages"] = self.cfg.getValue(
                section, 'apt-packages').split(",")
            settings["hide-tabs"] = self.cfg.getValue(section,
                                                      'hide-tabs').split(",")
            settings["apt-get-string"] = self.cfg.getValue(
                section, 'apt-get-string')
            settings["autostart"] = True
            if not exists(self.autostartDestFile):
                settings["autostart"] = False
        except:
            settings["allow-terminal-user-input"] = True
            settings["hrs-check-status"] = 1
            settings["umfilesdir"] = 'umfiles'
            settings["apt-packages"] = [
                "dpkg", "apt-get", "synaptic", "adept", "adept-notifier"
            ]
            settings["hide-tabs"] = ["maintenance"]
            settings[
                "apt-get-string"] = 'DEBIAN_FRONTEND=gnome apt-get --assume-yes -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold --force-yes'
            settings["autostart"] = True
            if not exists(self.autostartDestFile):
                settings["autostart"] = False
            self.saveSettings(
                section, 'allow-terminal-user-input',
                str(settings["allow-terminal-user-input"]).lower())
            self.saveSettings(section, 'hrs-check-status',
                              settings["hrs-check-status"])
            self.saveSettings(section, 'umfilesdir', settings["umfilesdir"])
            self.saveSettings(section, 'apt-packages',
                              ",".join(settings["apt-packages"]))
            self.saveSettings(section, 'hide-tabs',
                              ",".join(settings["hide-tabs"]))
            self.saveSettings(section, 'apt-get-string',
                              settings["apt-get-string"])

        # Check if on Debian 8
        force = self.get_apt_force()
        if force not in settings["apt-get-string"]:
            settings["apt-get-string"] = settings["apt-get-string"].replace(
                "--force-yes", force)
            self.saveSettings(section, 'apt-get-string',
                              settings["apt-get-string"])

        return settings

    def saveSettings(self, section, name, value):
        self.cfg.setValue(section, name, value)

    def isNumeric(self, n):
        try:
            n = complex(n)
            return True
        except:
            try:
                n = float(n, 0)
                return True
            except:
                try:
                    n = int(n, 0)
                    return True
                except:
                    return False

    def strToNumber(self, stringnr, toInt=False):
        nr = 0
        stringnr = stringnr.strip()
        try:
            if toInt:
                nr = int(stringnr)
            else:
                nr = float(stringnr)
        except ValueError:
            nr = 0
        return nr

    def getProcessPids(self, processName, fuzzy=True):
        if fuzzy:
            pids = self.ec.run(
                cmd=
                "ps -ef | grep -v sudo | grep -v grep | grep '%s' | awk '{print $2}'"
                % processName,
                realTime=False)
        else:
            pids = self.ec.run(
                cmd="pidof {}".format(processName, realTime=False))
        return pids

    def isProcessRunning(self, processName, fuzzy=True, excludeSelf=True):
        pids = self.getProcessPids(processName, fuzzy)
        if len(pids) > 0:
            return True
        return False

    def killScriptProcess(self, scriptName):
        msg = _('Please enter your password')
        pids = self.getProcessPids(scriptName)
        for pid in pids:
            print(("Kill %s process with pid: %s" % (scriptName, pid)))
            cmd = "gksudo --message \"<b>%s</b>\" kill %s" % (msg, pid)
            self.ec.run(cmd, False)

    def reloadWindow(self, scriptPath, runAsUser):
        path = self.ec.run(cmd="which python3", returnAsList=False)
        if exists(path):
            try:
                os.execl(path, path, scriptPath, runAsUser)
            except OSError as err:
                print(("Reload UM: %s" % str(err)))

    def getKernelVersion(self):
        version = self.ec.run(cmd="uname -r", realTime=False)[0]
        try:
            ind = version.rindex("-")
            return version[0:ind]
        except:
            return version

    def getKernelArchitecture(self):
        return self.ec.run(cmd="uname -m", realTime=False)[0]

    def getDistribution(self):
        distribution = ""
        if exists('/etc/solydxk/info'):
            distribution = self.ec.run(
                "cat /etc/solydxk/info | grep EDITION | cut -d'=' -f 2",
                realTime=False,
                returnAsList=False)
        return distribution

    def isUpgrading(self):
        if exists(self.umfiles['umupd']):
            return True
        else:
            return False

    def isRefreshing(self):
        if exists(self.umfiles['umrefresh']):
            return True
        else:
            return False

    def getLoginName(self):
        return self.ec.run(cmd="logname", realTime=False, returnAsList=False)

    # Only allow numbers in entry field
    # umglobal.onlyNumbers(self.txtField)
    def onlyNumbers(self, widget):
        def filter(entry, *args):
            text = entry.get_text().strip().lower()
            entry.set_text(''.join([i for i in text if i in '0123456789']))

        widget.connect('changed', filter)

    def get_apt_force(self):
        # --force-yes is deprecated in stretch
        force = '--force-yes'
        ver = self.strToNumber(
            self.ec.run(
                cmd=
                "head -c 1 /etc/debian_version | sed 's/[a-zA-Z]/0/' 2>/dev/null || echo 0",
                realTime=False,
                returnAsList=False))
        print((ver))
        if ver == 0 or ver > 8:
            force = '--allow-downgrades --allow-remove-essential --allow-change-held-packages'
        return force