コード例 #1
0
ファイル: net.py プロジェクト: nocl/calculate-3-install
 def get(self):
     """Net setup (networkmanager or openrc)"""
     if filter(lambda x:x.lower() == ("networkmanager"),
        listDirectory('/etc/runlevels/boot')+
        listDirectory('/etc/runlevels/default')) \
         or self.Get('os_root_type') == "livecd":
         nm = "networkmanager"
     else:
         nm = ""
     for val,comment in self.Get('os_install_net_conf_available'):
         if nm == val and not (self.Get('os_root_dev') == '/dev/nfs' and \
             self.Get('os_install_root_type') == "livecd"):
             return nm
     else:
         return "openrc"
コード例 #2
0
    def setupOpenGL(self):
        """Setup opengl for current video driver"""
        defaultGL = "xorg-x11"
        pathGlModules = path.join(self.clVars.Get('cl_chroot_path'),
                                 'usr/lib/opengl')
        openGLenv = path.join(self.clVars.Get('cl_chroot_path'),
                                 'etc/env.d/03opengl')

        openGlMods = filter(lambda x:x != "global",
                               listDirectory(pathGlModules))
        mapGL_drivers = {'fglrx':"ati" if "ati" in openGlMods
                                 else defaultGL,
                         'nvidia':"nvidia" if "nvidia" in openGlMods
                                  else defaultGL}
        x11_driver = self.clVars.Get('os_install_x11_video_drv')
        if x11_driver in mapGL_drivers:
            newModuleName = mapGL_drivers[x11_driver]
        else:
            newModuleName = defaultGL
        curModuleName = map(lambda x:x.strip().rpartition('=')[-1].strip('"\''),
                   filter(lambda x: x.startswith("OPENGL_PROFILE="),
                          open(openGLenv,'r')))
        curModuleName = curModuleName[-1] if curModuleName else ""
        if curModuleName == newModuleName:
            return True
        res,errmes = runOsCommand('eselect opengl set %s'%newModuleName)
        if res == 0:
            return True
        else:
            return False
コード例 #3
0
ファイル: hardware.py プロジェクト: nocl/calculate-3-lib
 def get(self):
     for cdrom in ifilter(lambda x:x.startswith('/sys/block/sr'),
                  listDirectory('/sys/block',fullPath=True)):
         if getUdevDeviceInfo(path=cdrom).get('ID_CDROM','') == "1":
             return "on"
     else:
         return "off"
コード例 #4
0
 def canInstallGrub2(self,target):
     """Check that system has grub2 in current and installed system"""
     if self.clVars.Get('os_grub2_path'):
         return bool(
                filter(lambda x:x.startswith('grub-1.99') or \
                                x.startswith('grub-2'),
                listDirectory('/var/db/pkg/sys-boot')))
     return False
コード例 #5
0
ファイル: distr.py プロジェクト: nocl/calculate-3-install
 def listdistr(pathname):
     if path.exists(path.join(pathname,'etc/make.profile')) or \
        path.exists(path.join(pathname,'livecd')) or \
        pathname.startswith('/dev/'):
         return [pathname]
     else:
         # discard inner directories
         return filter(lambda x:not path.isdir( path.join(pathname,x)),
                       listDirectory(pathname))
コード例 #6
0
 def choice(self):
     if self.Get("cl_ebuild_phase"):
         return [""]
     return (
         [""]
         + ["all"]
         + sorted(
             set(
                 chain(
                     *map(
                         lambda x: map(
                             lambda y: y[0].rpartition("-")[0] if y[2].startswith("r") else y[0],
                             imap(lambda y: y.rpartition("-"), listDirectory(x)),
                         ),
                         listDirectory("/var/db/pkg", onlyDir=True, fullPath=True),
                     )
                 )
             )
         )
     )
コード例 #7
0
ファイル: env.py プロジェクト: nocl/calculate-3-lib
 def get(self):
     sitePackages = map(lambda x:path.join(x,"calculate"),
                    filter(lambda x:x.endswith('site-packages') and \
                                    x.startswith('/usr/lib'),sys.path))
     retList = []
     for module,modDir in chain(*map(lambda x:map(lambda y:(path.basename(y),y),
                          listDirectory(x,True,True)),sitePackages)):
         if path.exists(path.join(modDir,"cl_wsdl_%s.py"%module)):
             if not "calculate-%s"%module in retList:
                 retList.append("calculate-%s"%module)
     return retList
コード例 #8
0
ファイル: distr.py プロジェクト: nocl/calculate-3-install
 def _findLatestFile(self,dirs,reMatch,keyfunc):
     """Find latest file in dirs, which match by reMatch,
     comparable part get by keyfunc"""
     existsdirs = filter(path.exists,dirs)
     listimgs = reduce(lambda x,y:x + \
                           map(lambda x:reMatch.search(path.join(y,x)),
                               listDirectory(y)),
                       existsdirs,[])
     listimgs = filter(lambda x:x, listimgs)
     if listimgs:
         return max(listimgs,key=keyfunc).group()
     return ""
コード例 #9
0
ファイル: variable.py プロジェクト: nocl/calculate-3-core
 def get(self):
     sitePackages = map(lambda x:path.join(x,"calculate"),
                    filter(lambda x:x.endswith('site-packages') and \
                                    x.startswith('/usr/lib'),sys.path))
     retList = []
     for module,modDir in chain(
                          *map(lambda x:map(lambda y:(path.basename(y),y),
                          listDirectory(x,True,True)),sitePackages)):
         if path.exists(path.join(modDir,"datavars.py")):
             retList.append(module)
     return sorted(retList,
            key=lambda x:{'lib':0,'install':1,'core':2}.get(x,x))
コード例 #10
0
ファイル: cert_func.py プロジェクト: nocl/calculate-3-console
def getRunProc():
    """List run program"""
    def getCmd(procNum):
        cmdLineFile = '/proc/%s/cmdline'%procNum
        try:
            if os.path.exists(cmdLineFile):
                return [open(cmdLineFile,'r').read().strip(), procNum]
        except:
            pass
        return ["", procNum]
    if not os.access('/proc',os.R_OK):
        return []
    return map(getCmd,
           filter(lambda x:x.isdigit(),
           listDirectory('/proc')))
コード例 #11
0
 def _initModulesData(self):
     def holderlistdir(dirpath):
         dirs = listDirectory(path.join(sysModules,dirpath,"holders"))
         return reduce(lambda x,y:x+[y]+holderlistdir(path.join(dirpath,
                                                      "holders",y)),
                       dirs, [])
     sysModules = '/sys/module'
     holderPath = lambda x: path.join(sysModules,x,"holders")
     refPath = lambda x: path.join(sysModules,x,"refcnt")
     self.loadModules = filter(lambda x: access(holderPath(x),R_OK) and
                                    access(refPath(x),R_OK),
                          listDirectory(sysModules))
     self.useModules = map(lambda x:int(open(refPath(x),'r').read().strip()),
                                  self.loadModules)
     self.depModules = map(lambda x: holderlistdir(x),
                           self.loadModules)
コード例 #12
0
ファイル: system.py プロジェクト: nocl/calculate-3-lib
 def get(self):
     """Root device type (ram, hdd, livecd)"""
     def link2pair(linkfile):
         """Return pair (target,link) from link"""
         basedir = path.dirname(linkfile)
         targetfile = os.readlink(linkfile)
         return (path.normpath(os.path.join(basedir,targetfile)),linkfile)
     rootDev = self.Get("os_root_dev")
     if rootDev:
         if any(x in rootDev for x in ("/dev/ram","/dev/nfs")):
             return "livecd"
         idDict = dict(map(link2pair,
                  filter(lambda x:path.islink(x),
                  map(lambda x:path.join('/dev/disk/by-id',x),
                  listDirectory('/dev/disk/by-id')))))
         if "usb-" in idDict.get(rootDev,""):
             return "usb-hdd"
     return "hdd"
コード例 #13
0
ファイル: kernel.py プロジェクト: nocl/calculate-3-install
 def get(self):
     bootdir = path.join(self.Get('cl_chroot_path'),'boot')
     modulesdir = path.join(self.Get('cl_chroot_path'),'lib/modules')
     validKernel = listDirectory(modulesdir)
     kernelFiles = self.getFilesByType(bootdir,"Linux kernel")
     installMarch = self.Get('os_install_arch_machine')
     kernelsWithVer = \
         map(lambda x:(x[0],(getTupleVersion("".join(x[1].groups()[0:3:2])),
                             path.getmtime(x[0]))),
         # convert version to tuple( versionTuple, mtime)
         # version detect, for this version lib contains moudules
         # kernel arch equal install arch
         ifilter(lambda x:x[1] and x[1].group() in validKernel and
                    installMarch in x[0].rpartition('/')[2],
         # (filename,version)
         imap(lambda x:(x[0],self.reFindVer.search(x[1])),
         kernelFiles)))
     if kernelsWithVer:
         return path.split(max(kernelsWithVer,key=itemgetter(1))[0])[-1]
     else:
         return "vmlinuz"
コード例 #14
0
 def holderlistdir(dirpath):
     dirs = listDirectory(path.join(sysModules,dirpath,"holders"))
     return reduce(lambda x,y:x+[y]+holderlistdir(path.join(dirpath,
                                                  "holders",y)),
                   dirs, [])
コード例 #15
0
ファイル: desktop.py プロジェクト: nocl/calculate-3-desktop
    def createCryptDir(self,userName,uid,gid,userDir,recreateOnError=False):
        """
        Создать шифрование домашней директории, или подключить существующую

        userName,uid,gid,userDir: параметры пользовательской учётной записи
        recreateOnError: пересоздать профиль при ошбиках (используется при доменной
        ученой записи, так пользователь при этом ничего не теряет - профиль на сервере)
        """
        userPwd = getKey(userName)
        error = ""
        # проверить наличие пароля в ключах ядра
        if not userPwd or userPwd == "XXXXXXXX":
            raise DesktopError(_("User password not found"))
        ecryptfsPath = path.join('/home/.ecryptfs',userName)
        # если шифрование уже используется
        if path.exists(ecryptfsPath):
            for d in (".ecryptfs",".Private"):
                source,target = path.join(ecryptfsPath,d),path.join(userDir,d)
                if not path.lexists(target):
                    os.symlink(source,target)
            # попытаться подключить шифрованные данные
            try:
                if not mountEcryptfs(userName,userPwd,userDir):
                    error = _("Failed to mount ecrypted data")
            except CommonError as e:
                error = _("Failed to mount ecrypted data")+": \"%s\""%str(e)
        # если при подключении произошли ошибки
        if error:
            # заархивировать текущий профиль и удалить его
            if recreateOnError:
                self.printSUCCESS(_("Recreating encrypted data"))
                if self.getMountUserPaths(userDir):
                    raise DesktopError(_("Failed to use directory encryption"))
                for source in (userDir,ecryptfsPath):
                    if path.exists(source):
                        if listDirectory(source):
                            target = source+".bak"
                            newtarget = target
                            if path.exists(target):
                                removeDir(target)
                            os.rename(source,newtarget)
                        else:
                            os.rmdir(source)
                self.createUserDir(userName,uid,gid,userDir)
            # ошибка создания шифрования
            else:
                raise DesktopError(error)
        # если нет шифрованных данных
        if not path.exists(ecryptfsPath):
            tf = None
            try:
                # если профиль содержит только данные от бутстрапа core
                if isBootstrapDataOnly(userDir):
                    if childMounts(userDir):
                        raise DesktopError(
                            _("Failed to create the encrypted user profile")+":"+
                            _("User home directory contains mount points"))
                    # поместить данные во временный tarfile
                    calculateName = ".calculate"
                    calculatePath = path.join(userDir,calculateName)
                    tf = tempfile.TemporaryFile()
                    with tarfile.open(fileobj=tf,mode='w:') as tarf:
                        tarf.add(calculatePath,calculateName)
                    tf.flush()
                    tf.seek(0)
                    # удалить эти данные
                    shutil.rmtree(calculatePath)

                # создать шифрованные данные
                e = process('/usr/bin/ecryptfs-setup-private','-u',userName,
                            '-b','-l',userPwd,stderr=STDOUT)
                if e.failed():
                    raise DesktopError(e.read())
                # если были данные от бутстрапа, то распаковать их
                if tf:
                    with tarfile.open(fileobj=tf,mode='r:') as tarf:
                        tarf.extractall(userDir)
            except Exception as e:
                # в случае ошибки сохраняем архив (с данными bootstrap)
                # из памяти в файловую систему
                if tf:
                    tf.seek(0)
                    bakArchName = path.join(userDir,".calculate.tar.bz2")
                    with open(bakArchName,'w') as f:
                        f.write(tf.read())
                raise DesktopError(str(e)+
                    _("Failed to create the encrypted user profile"))
            finally:
                if tf:
                    tf.close()
        return True