def installGrub2Bootloader(self,target): """ Install grub2 boot loader """ for bootPath in ("/boot","/"): bootDisk = self.clVars.Select("os_install_disk_dev", where="os_install_disk_mount",eq=bootPath,limit=1) if bootDisk: self.setActivePartition(bootDisk) break cmdGrubInstall = self.clVars.Get('os_grub2_path') if not cmdGrubInstall: raise DistributiveError(_("Failed to install the bootloader")) for mbrDisk in self.clVars.Get('os_install_mbr'): process("sync").success() if self.clVars.Get('os_install_scratch') == "on" and \ self.clVars.Get('cl_action') != "system": prefixBoot = "/mnt/scratch" else: prefixBoot = "/" grubProcess = process(cmdGrubInstall, "--boot-directory=%s"%pathJoin(prefixBoot, target.getBootDirectory()), mbrDisk, "-f", stderr=STDOUT,envdict=os.environ) if grubProcess.failed(): raise DistributiveError(_("Failed to install the bootloader"))
def processingFile(self, textConfigFile, rootPath=None): self.patchFiles = [] retTextConfigFile = textConfigFile for i in range(0,4): patchDryRun = process('/usr/bin/patch','--dry-run', '-p%d'%i,cwd=rootPath,) patchDryRun.write(self.text) if patchDryRun.success(): break patchDryRun = process('/usr/bin/patch','-R','--dry-run', '-p%d'%i,cwd=rootPath,) patchDryRun.write(self.text) if patchDryRun.success(): return "" else: self.setError(_("Patching failed")) return False patchRun = process('/usr/bin/patch', '-p%d'%i,cwd=rootPath) patchRun.write(self.text) if patchRun.success(): for line in patchRun: if line.startswith("patching file"): self.patchFiles.append(line[13:].strip()) return patchRun.read() return ""
def doubleExec(self,*args): """ Running double exec command with 2 seconds interval """ if process(*args).failed(): sleep(2) return process(*args).failed() return False
def recreatePartitionTableDos(self,device,data): """ Create DOS partition table by /sbin/fdisk """ NEW_PARTITION_TABLE = "o\n" NEW_PRIMARY_PARTITION = "n\np\n\n\n" NEW_EXTENDED_PARTITION = "n\ne\n\n" NEW_LOGICAL_PARTITION = "n\n\n" MAX_SIZE = "\n" WRITE_AND_QUIT = "w\nq\n" fdiskProg = getProgPath('/sbin/fdisk') fdisk = process(fdiskProg,device[0]) fdisk.write(NEW_PARTITION_TABLE) num = 1 for size in map(lambda x:str(Sizes().to_K(int(x))) \ if x.isdigit() else x, map(operator.itemgetter(3),data)): if num == 4: fdisk.write(NEW_EXTENDED_PARTITION+MAX_SIZE) num += 1 size = MAX_SIZE if size == "allfree" else "+%sK\n"%size if num < 4: fdisk.write(NEW_PRIMARY_PARTITION+size) else: fdisk.write(NEW_LOGICAL_PARTITION+size) num +=1 fdisk.write(WRITE_AND_QUIT) fdisk.success() self._waitDevice(device[0]+str(num-1))
def _packInitRamfs(self,newInitramfsFile=None): """Pack initramfs""" self.prevDir = os.getcwd() try: # get file list for pack fileList = reduce(lambda x,y: x +map(lambda z:path.join(y[0],z),y[1]) +map(lambda z:path.join(y[0],z),y[2]), os.walk(self.tmpPath), []) fileList = map(lambda x:x[len(self.tmpPath)+1:],fileList) # change dir for cpio os.chdir(self.tmpPath) # create cpio process cpioProcess = process("cpio", "-o", "--quiet", "-H","newc") # send file list to cpio process cpioProcess.write("\n".join(fileList)) cpioProcess.write("\n") # get result of cpio cpioData = cpioProcess.read() cpioRes = cpioProcess.returncode() except KeyboardInterrupt: os.chdir(self.prevDir) raise KeyboardInterrupt except Exception,e: print e.__repr__() cpioRes = 255
def installLegacyGrubBootloader(self,target): """ Install legecy grub boot loader Perform grub installation to disk, which has root partition """ cmdGrub = varsShare().getProgPath('/sbin/grub') if not cmdGrub: raise DistributiveError(_("Failed to install the bootloader")) grubProcess = process(cmdGrub, "--device-map=%s/boot/grub/device.map"%target.getDirectory(), "--batch",stderr=STDOUT) bootDisk = self.Select('os_install_disk_grub', where='os_install_disk_mount', _in=('/','/boot'), sort='DESC',limit=1) if not bootDisk: raise DistributiveError(_("Failed to determine the boot disk")) self.setActivePartition(bootDisk) for mbrDisk in self.clVars.Get('os_install_mbr'): mbrDiskNum = self.Select("os_device_map", where="os_device_dev", eq=mbrDisk) if not mbrDiskNum and mbrDiskNum != 0: raise DistributiveError(_("Failed to determine mbr")) for line in ("root (hd%s)"%bootDisk, "setup (hd%d)"%mbrDiskNum, "quit"): grubProcess.write("%s\n"%line) if grubProcess.failed(): raise DistributiveError(_("Failed to install the bootloader"))
def createCryptDir(self,userName,uid,gud,userDir): """ Создать шифрование домашней директории, или подключить существующую """ userPwd = getKey(userName) 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): raise DesktopError(_("Failed to mount ecrypted data")) except CommonError as e: raise DesktopError(_("Failed to mount ecrypted data")+": \"%s\""%str(e)) else: tf = None try: # если профиль содержит только данные от бутстрапа core if isBootstrapDataOnly(userDir): if childMounts(userDir): raise DesktopError( _("Failed to create encrypt 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: 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 encrypt user profile")) finally: if tf: tf.close()
def _createLogicalVolume(self,vgname,lvname,size): if size.isdigit(): size = str(Sizes().to_K(int(size))) if size == "allfree": sizeparam = "-l100%FREE" else: sizeparam = "-L%sK"%size lvCreateProg = getProgPath('/sbin/lvcreate') return process(lvCreateProg,sizeparam,vgname,"-n",lvname).success()
def getLvmData(self): """Get route table, exclude specifed iface""" pvDisplayProg = checkUtils('/sbin/pvdisplay') pvDisplay = process(pvDisplayProg,"--noh","-Co", "lv_name,vg_name,pv_name") for line in pvDisplay: line = line.split() if len(line) == 3: yield line
def get(self): displayEnv = process('/bin/bash',"-c","source /etc/profile;env", stdout=PIPE) for line in displayEnv: if line.startswith("CONFIG_PROTECT_MASK="): configProtectMask=line.rstrip().partition('=')[2].split() break else: configProtectMask = [] return configProtectMask
def getOrig(x): try: nameParam = filter(lambda x:x.startswith("ID_NET_NAME_PATH="), process("udevadm","test-builtin","net_id", "/sys/class/net/%s"%x)) if nameParam: return nameParam[0].partition('=')[2].strip() or x except Exception as e: print str(e) return x return x
def get(self): # find grub2-install grubInstall = getProgPath('/usr/sbin/grub2-install') if grubInstall: return grubInstall # find grub-install and check, that this is grub2-install (ver 1.99) grubInstall = getProgPath('/usr/sbin/grub-install') if grubInstall and filter(lambda x:"1.99" in x or "2.00" in x, process(grubInstall,'-v')): return grubInstall return ""
def _unpackInitRamfs(self): """Unpack initramfs""" self.prevDir = os.getcwd() if not path.exists(self.tmpPath): os.mkdir(self.tmpPath) os.chdir(self.tmpPath) cpioProcess = process("cpio", "-di") gzipInitrd = gzip.open(self.initrdFile,'r') cpioProcess.write(gzipInitrd.read()) res = cpioProcess.success() os.chdir(self.prevDir) return res
def remountNTFS(self): """ Remount NTFS partitions """ for disk in self.clVars.Select('os_disk_dev', where='os_disk_format',like='ntfs'): mountDir = self._getFreeDirectory('/var/lib/calculate/mount.ntfs') try: os.mkdir(mountDir) except: continue if process('/bin/mount',disk,mountDir).success(): for i in (0.2,0.5,1,2,4,5): if process('/bin/umount',mountDir).success(): break else: self.printWARNING(_("Unable to umount %s")%mountDir) try: os.rmdir(mountDir) except: self.printWARNING(_("Unable to remove directory %s")%mountDir)
def get(self): """Root filesystem device""" record = readFile('/proc/cmdline').strip() re_resRealRoot=re.search('(?:^|\s)real_root=(\S+)(\s|$)',record) re_resFakeRoot=re.search('(?:^|\s)root=(\S+)(\s|$)',record) # param real_root priority that root re_res = re_resRealRoot or re_resFakeRoot if re_res: rootparam=re_res.group(1) # check root for /dev/sd view if re.match("^\/dev\/[a-z]+.*$", rootparam): return getUdevDeviceInfo( name=rootparam.strip()).get('DEVNAME',rootparam) # check root set by uuid if re.match("^UUID=.*$",rootparam): uuid = rootparam[5:].strip("\"'") blkidProcess = process('/sbin/blkid','-c','/dev/null','-U', uuid) if blkidProcess.success(): return getUdevDeviceInfo( name=blkidProcess.read().strip()).get('DEVNAME','') # check root set by label if re.match("^LABEL=.*$",rootparam): uuid = rootparam[6:].strip("\"'") blkidProcess = process('/sbin/blkid','-c','/dev/null','-L', uuid) if blkidProcess.success(): return getUdevDeviceInfo( name=blkidProcess.read().strip()).get('DEVNAME','') # get device mounted to root dfProcess = process('df','/',envdict={'LANG':'C'}) if dfProcess.failed(): return "" dfLines = dfProcess.readlines() if len(dfLines)>1: root_dev = dfLines[1].split(" ")[0].strip() if root_dev: return {'none':'/dev/ram0'}.get(root_dev,root_dev) return ""
def installSyslinuxBootloader(self,target): """Install boot loader by syslinux Perform syslinux installation to flash. """ if not self.clVars.Get('os_install_mbr'): return ddProcess = process("/bin/dd","if=/usr/share/syslinux/mbr.bin", "of=%s"%self.clVars.Get('os_install_mbr')[0], stderr=STDOUT) if ddProcess.failed(): raise DistributiveError( _("Failed to write the master boot record\n%s")% ddProcess.read()) target.close() installRootDev = self.clVars.Get('os_install_root_dev') syslinuxProcess = process("/usr/bin/syslinux", installRootDev, stderr=STDOUT) if syslinuxProcess.failed(): raise DistributiveError(_("Failed to install syslinux\n%s")% syslinuxProcess.read()) # is partition active return self.setActivePartition(self.clVars.Get('os_install_root_dev'))
def umountSleepPath(self, rpath): """ Отмонтировать указанный путь, а также отключить используемые в этом пути loop устройства и raid """ # check for mount loops = getLoopFromPath(rpath) if loops: setLoops = set(map(lambda x:x.partition('/dev/')[2],loops)) mdInfo = getMdRaidDevices() for k,v in mdInfo.items(): if setLoops & set(v): self.umountSleepPath('/dev/%s'%k) process('/sbin/mdadm','--stop','/dev/%s'%k).success() for loop in loops: self.umountSleepPath(loop) process('/sbin/losetup','-d',loop).success() if isMount(rpath): for waittime in [0,0.5,1,2]: time.sleep(waittime) if not self.execProg("umount %s"%rpath) is False \ or not isMount(rpath): if not isMount(rpath): return True self.execProg("fuser -km %s"%rpath) for waittime in [0.5, 0.5, 0.5, 0.5, 0.5, 0.5]: time.sleep(waittime) if not self.execProg("umount %s"%rpath) is False \ or not isMount(rpath): if not isMount(rpath): return True self.execProg("umount -l %s"%rpath) else: if isMount(rpath): self.printERROR(_("Failed to unmount directory %s")%rpath) return False return True
def getCfgFiles(protected_dirs=['/etc'],prefix='/'): """ Get protected cfg files """ reCfg = re.compile(r"/\._cfg\d{4}_",re.S) findParams = ["find"]+map(lambda x:pathJoin(prefix,x),protected_dirs)+\ ["-name","._cfg????_*","!","-name",".*~","!","-iname",".*.bak", "-printf",r"%T@ %p\n"] mapCfg = {} for filetime,sep,filename in map(lambda x:x.partition(' '), filter(None,process(*findParams))): origFilename = reCfg.sub(r'/',filename) if not origFilename in mapCfg: mapCfg[origFilename] = [] mapCfg[origFilename].append((int(filetime.split('.')[0]),filename)) return mapCfg
def get(self): def get_linguas(lines): linguas = map(lambda x:x.strip().rpartition('=')[-1].strip('"\''), filter(lambda x: x.startswith("LINGUAS="), lines)) return linguas[-1] if linguas else "" makeconf = '/etc/make.conf' infocommand = ['emerge','--info'] defaultLinguas = "bg en de es fr it pl pt_BR ru uk" # get linguas from make.conf, emerge --info or default curlanguage = self.Get('os_install_locale_language') return get_linguas(readLinesFile(makeconf)) or \ " ".join(filter(lambda x:x=="en" or x==curlanguage, get_linguas( process(*infocommand).readlines() or "").split())) or \ defaultLinguas
def get(self): """Get current framebuffer resolution""" resolution = "" fbres = getProgPath('/sbin/fbres') if fbres: processFbres = process(fbres,stderr=STDOUT) textLines = processFbres.readlines() if textLines: cxx11,cyx11 = \ self.Get('os_install_x11_resolution').partition('x')[0::2] cxfb, cyfb = textLines[0].partition('x')[0::2] if not filter(lambda x:not x.isdigit(), [cxfb,cyfb,cxx11,cyx11])and \ int(cxx11) >= int(cxfb) and int(cyx11) >= int(cyfb): resolution = "%s-32"%textLines[0] return resolution or "1024x768-32"
def userLogout(self, datavars=None): """ Raise user logout throught dbus """ self.initVars(datavars) if not self.clVars.Get('ur_login') in \ self.clVars.Get('cl_desktop_online_user'): raise DesktopError(_("X session users not found")) urLogin = self.clVars.Get('ur_login') display = self.clVars.Select('cl_desktop_online_display', where='cl_desktop_online_user',eq=urLogin,limit=1) session = self.clVars.Get('cl_desktop_xsession') if session == 'xfce': logoutCommand = "/usr/bin/qdbus org.xfce.SessionManager " \ "/org/xfce/SessionManager Logout False False" elif session == 'kde': logoutCommand = "/usr/bin/kquitapp ksmserver" elif session == 'gnome': logoutCommand = "/usr/bin/qdbus org.gnome.SessionManager " \ "/org/gnome/SessionManager Logout 1" else: raise DesktopError(_("Unable to detect the X session")) if process("su",urLogin,"-c", ("DISPLAY=:%s "%display)+logoutCommand).failed(): raise DesktopError(_("Unable to send the logout command")) for i in range(0,20): if filter(lambda x: "xdm/xdm\x00--logout" in x, getRunCommands()): break time.sleep(0.5) if filter(lambda x: "xdm/xdm\x00--logout" in x, getRunCommands()): self.startTask(_("Waiting for completion of the user logout")) for i in range(0,300): if not filter(lambda x: "xdm/xdm\x00--logout" in x, getRunCommands()): return True time.sleep(1) self.endTask() else: raise DesktopError(_("Unable to wait for completion " "of the user logout")) if self.clVars.Get('ur_login') in \ self.clVars.Get('cl_desktop_online_user'): raise DesktopError(_("Wrong logout")) return True
def getResByXDpyInfo(self): """Get resolution by xdpyinfo utility""" try: processXDpy = process('xdpyinfo') if processXDpy.failed(): return "" except OSError: return "" lines = processXDpy.readlines() reRes = re.compile("dimensions:\s+(\d+)x(\d+)\s+pixels") searchRes=False for line in lines: searchRes = reRes.search(line) if searchRes: break if searchRes: return "%sx%s"%(searchRes.group(1), searchRes.group(2)) return ""
def get(self): image = self.Get('cl_image') try: if image: image = image.convertToDirectory() chrootPath = image.getDirectory() chrootPath = image.getDirectory() else: chrootPath = self.Get("cl_chroot_path") nvidiaeclass = path.join(chrootPath, 'usr/portage/eclass/nvidia-driver.eclass') if not os.access(nvidiaeclass,os.R_OK): return "" category = "0300" vendor = "10de:" lsPciProg = getProgPath("/usr/sbin/lspci") nvidiacards = filter(lambda x:" %s: "%category in x, process(lsPciProg,"-d",vendor,"-n")) if not nvidiacards: return "" cardsid = \ map(lambda x:x.groups()[0], filter(lambda x:x, map(lambda x:re.search("[0-9a-fA-F]{4}:([0-9a-fA-F]{4})",x), nvidiacards))) if not cardsid: return "" eclassdata = readFile(nvidiaeclass) drv_categories = re.findall('^drv_([^=]+)="', eclassdata, re.M) drvs = map(lambda x:(x[0],x[1].replace('\\\n','').split()), re.findall('\ndrv_(%s)="(.*?)"'%"|".join(drv_categories), eclassdata,re.S)) mask_categories = re.findall('^mask_([^=]+)="', eclassdata, re.M) masks = dict(map(lambda x:(x[0],x[1].replace('\\\n','')), re.findall('\nmask_(%s)="(.*?)"'%"|".join(drv_categories), eclassdata,re.S))) drvsForCardsid = filter(lambda x:set(x[1])&set(cardsid),drvs) if drvsForCardsid and drvsForCardsid[0][0] in masks: return masks[drvsForCardsid[0][0]] finally: if image: image.close() return ""
def userLogout(self, urLogin): """ Выполнить logout пользователя через dbus """ display = self.clVars.Select('cl_desktop_online_display', where='cl_desktop_online_user',eq=urLogin,limit=1) session = self.clVars.Get('cl_desktop_xsession') if session == 'xfce': logoutCommand = "/usr/bin/qdbus org.xfce.SessionManager " \ "/org/xfce/SessionManager Logout False False" elif session == 'kde': logoutCommand = "/usr/bin/kquitapp ksmserver" elif session == 'gnome': logoutCommand = "/usr/bin/qdbus org.gnome.SessionManager " \ "/org/gnome/SessionManager Logout 1" else: raise DesktopError(_("Unable to detect the X session")) if process("su",urLogin,"-c", ("DISPLAY=:%s "%display)+logoutCommand).failed(): raise DesktopError(_("Unable send logout command")) return True
def get(self,hr=False): xSession = 0 foundTwoSession = False resWho = process("who") xData = [[]] if resWho.success(): listProcessing = lambda x: (x[0], x[1], x[-1]) \ if len(x)>=5 else [] xData = groupby( sorted( filter(lambda x: x[0]!="root", map(lambda x: (x[0],self._getDisplay(x[1],x[2])), filter(lambda x: x and\ (x[2].startswith("(:") or \ x[1].startswith(":")), map(lambda x: listProcessing(\ filter(lambda y: y, x.split())), resWho)))), key=lambda x:x[0]), lambda x:x[0]) xData = map(lambda x:(x[0][0],x[0][1],len(x)), map(lambda x:list(x[1]), xData)) return xData
def recreatePartitionTableGpt(self,device,data): """ Create GPT partition table by /sbin/gdisk """ NEW_PARTITION_TABLE = "3\no\ny\n" NEW_PARTITION = "n\n\n\n" NEW_BIOSBOOT_PARTITION = "n\n\n\n%s\nef02\n" MAX_SIZE = "\n\n" WRITE_AND_QUIT = "w\ny\n" fdiskProg = getProgPath('/usr/sbin/gdisk') fdisk = process(fdiskProg,device[0]) fdisk.write(NEW_PARTITION_TABLE) num = 1 biosBootCreated = False for size in map(lambda x:str(Sizes().to_K(int(x))) \ if x.isdigit() else x, map(operator.itemgetter(3),data)): if num == 4: fdisk.write(NEW_BIOSBOOT_PARTITION%"+2M") biosBootCreated = True num += 1 if size == "allfree": if biosBootCreated: size = MAX_SIZE else: size = "-2M\n\n" else: size = "+%sK\n\n"%size fdisk.write(NEW_PARTITION+size) num +=1 if not biosBootCreated: fdisk.write(NEW_BIOSBOOT_PARTITION%"") fdisk.write(WRITE_AND_QUIT) fdisk.success() self._waitDevice(device[0]+str(num-1))
def searchInside(self,searchFunc): """Search data in file list of initramfs""" cpioProcess = process("cpio", "-tf", stdin=process("gzip", "-dc", self.initrdFile)) return filter(searchFunc,cpioProcess)
def _removeVolumeGroup(self,vgname): vgRemoveProg = getProgPath('/sbin/vgremove') # double remove volume group return process(vgRemoveProg,vgname,"-f").success() or \ process(vgRemoveProg,vgname,"-f").success()
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
def setActivePartition(self,partition): """Change partition id, specified by systemid,set active""" deviceName = detectDeviceForPartition(partition) if deviceName is None: raise DistributiveError( _("Failed to determine the parent device for %s")%partition) # device hasn't any partition elif deviceName == "": return True fdiskProg, gdiskProg, partedProg = checkUtils('/sbin/fdisk', '/usr/sbin/gdisk','/usr/sbin/parted') disk = self.clVars.Select('os_install_disk_parent', where='os_install_disk_dev',eq=partition, limit=1) parttable = self.clVars.Select('os_device_table',where='os_device_dev', eq=disk,limit=1) partitionNumber = \ getUdevDeviceInfo(name=partition).get('ID_PART_ENTRY_NUMBER','') or \ getUdevDeviceInfo(name=partition).get('UDISKS_PARTITION_NUMBER','') devicePartitionCount = countPartitions(deviceName) if deviceName and not partitionNumber: raise DistributiveError( _("Failed to determine the partition number for %s")%partition) bootFlag = "boot" if parttable == "dos" else "legacy_boot" if parttable == "dos": fdisk = process(fdiskProg, "-l",deviceName) DEVICENUM,AFLAG = 0,1 changeActive = \ map(lambda x:x[DEVICENUM], filter(lambda x:x[DEVICENUM] != partitionNumber and \ x[AFLAG] == "*" or \ x[DEVICENUM] == partitionNumber and \ not x[AFLAG] == "*", list(map(lambda x:[str(x[0]),x[1][1].strip()], # enumerate partitions enumerate(filter(None, map(lambda x:x.split()[:2], # drop string before information about partitions dropwhile(lambda x:not x.lstrip().startswith("Device"), fdisk.readlines()))))))[1:])) else: parted = process(partedProg, "-m",deviceName,"print") DEVICENUM,FLAGS = 0,6 changeActive = \ map(lambda x:x[DEVICENUM], filter(lambda x:x[DEVICENUM] != partitionNumber and \ bootFlag in x[FLAGS].strip(';').split(', ') or \ x[DEVICENUM] == partitionNumber and \ not bootFlag in x[FLAGS].strip(';').split(', '), filter(lambda x:len(x)>=7, map(lambda x:x.split(':'), parted.readlines()[2:])))) if not changeActive: return True if parttable == "dos": pipe = Popen([fdiskProg,deviceName], stdin=PIPE, stdout=PIPE,stderr=PIPE) for partnum in changeActive: pipe.stdin.write("a\n%s\n"%partnum) pipe.stdin.write("w\n") pipe.stdin.close() pipe.wait() elif parttable == "gpt": pipe = Popen([gdiskProg,deviceName], stdin=PIPE, stdout=PIPE,stderr=PIPE) if devicePartitionCount > 1: pipe.stdin.write("x\n") for partnum in changeActive: pipe.stdin.write("a\n%s\n2\n\n"%partnum) pipe.stdin.write("w\nY\n") else: pipe.stdin.write("x\na\n2\n\nw\nY\n") pipe.stdin.close() pipe.wait() for waittime in (0.1,0.2,0.5,1,2,4): if path.exists(partition): return True else: sleep(waittime) raise InstallError( _("Failed to find partition %s after changing the activity")% partition)