def checkPermFiles(self): """Check permission files""" checkThisFiles = [migrateGroups.fileGroups, migrateUsers.filePasswd, migrateShadow.fileShadow] checkNewFiles = map(lambda x: pathJoin(self.prefixNewSystem,x), checkThisFiles) parentDir = lambda x: "".join(os.path.split(x)[:-1]) notRead = lambda x: not os.access(x, os.R_OK) notWrite = lambda x: not os.access(x, os.W_OK) filesNotRead = filter(notRead,checkThisFiles) if filesNotRead: raise MigrationError(_("Failed to read files") + ": " +\ ", ".join(filesNotRead)) filesNotWrite = filter(notWrite,checkNewFiles) if filesNotWrite: raise MigrationError(_("Failed to write to files") + ": " +\ ", ".join(filesNotWrite)) # Check permissions backup files checkNewBackupFiles = map(lambda x:pathJoin(self.prefixNewSystem,x+"-"), checkThisFiles) notWriteBackup = lambda x: not os.access(x, os.W_OK) and \ (os.path.exists(x) or \ not os.access(os.path.dirname(x), os.W_OK)) filesNotWrite = filter(notWriteBackup, checkNewBackupFiles) if filesNotWrite: raise MigrationError(_("Failed to write to files") + ": " +\ ", ".join(filesNotWrite)) return True
def processingFile(self,pathname,prefix): try: if pathname.endswith(".clt"): targetDir = pathJoin(self.target,path.dirname(pathname)) if not path.exists(targetDir): os.makedirs(targetDir) copy2(pathname,pathJoin(self.target,pathname)) except Exception,e: raise InstallError(_("Failed to copy '%(src)s' to '%(dst)s'")% {'src':pathname,'dst':pathJoin(self.target,pathname)})
def scanProtectDirs(self, configPath, protectPaths): configFiles = [] scanObj = scanDirectory() scanObj.processingFile = lambda path, prefix: configFiles.append(path) or True configPath = os.path.realpath(configPath) for pPath in protectPaths: realPath = pathJoin(configPath, pPath) if os.path.exists(realPath): scanObj.scanningDirectory(realPath) configFiles = map(lambda x: x.partition(configPath)[2], configFiles) configFiles = map(lambda x: pathJoin("/", x), configFiles) return configFiles
def saveNewFiles(self): """Save /etc/passwd /etc/group /etc/shadow to new system""" listFilesThisSystem = [migrateGroups.fileGroups,migrateUsers.filePasswd, migrateShadow.fileShadow] listFiles = map(lambda x:(pathJoin(self.prefixNewSystem,x), pathJoin(self.prefixNewSystem,x+"-")), listFilesThisSystem) listData = [self.dataGroups, self.dataUsers, self.dataShadow] allData = zip(listFiles,listData) for fileNames, data in allData: buff = "\n".join(map(lambda x: ":".join(x), data)) + "\n" for fileName in fileNames: FD = open(fileName, "w+") FD.write(buff) FD.close()
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 createDir(self, configPath, dstDir): """Create need dirs""" if os.path.exists(dstDir): return True def splPath(path): listPath = [] if path in ("", "/"): return [] base, p = os.path.split(path) listPath.append(p) while not base in ("", "/"): base, p = os.path.split(base) listPath.append(p) listPath.reverse() return listPath notFoundPaths = [] path = "/" for p in splPath(dstDir): path = os.path.join(path, p) if not os.path.exists(path): notFoundPaths.append(path) for mkPath in notFoundPaths: srcPath = pathJoin(configPath, mkPath) dMode, dUid, dGid = getModeFile(srcPath) os.mkdir(mkPath, dMode) os.chown(mkPath, dUid, dGid) return True
def getNewDataSystemGroups(self): """Get data system groups in new system""" fileName = pathJoin(self.prefixNewSystem, self.fileGroups) return filter(lambda x:\ self._reNumb.match(x[2]) and\ (int(x[2])>self.maxGid or int(x[2])<self.minGid), self.getData(fileName=fileName))
def getNewDataSystemUsers(self): """Get data system users in new system""" fileName = pathJoin(self.prefixNewSystem, self.filePasswd) return filter(lambda x:\ self._reNumb.match(x[2]) and\ (int(x[2]>self.maxId) or int(x[2])<self.minId), self.getData(fileName=fileName))
def __init__(self, sysThisMigrateUsers, sysNewMigrateUsers, newMigrateUsers, thisMigrateUsers, prefixNewSystem): self.prefixNewSystem = prefixNewSystem self.sysThisMigrateUsers = sysThisMigrateUsers self.sysNewMigrateUsers = sysNewMigrateUsers self.newMigrateUsers = newMigrateUsers self.thisMigrateUsers = thisMigrateUsers self.newFileName = pathJoin(self.prefixNewSystem, self.fileShadow)
def addObject(self,filename): """ Add object to content """ if filename != '/': filename = self._fixNameByPrefix(filename) newfilename = pathJoin(self.prefix,filename) self.addDir(path.dirname(filename)) if path.islink(newfilename): self.addLink(filename) elif path.isdir(newfilename): self.addDir(filename) elif path.isfile(newfilename): self.addFile(filename)
def fillContents(allContent,protected,prefix='/'): """ Fill dict file - package """ dbPath = pathJoin(prefix,'var/db/pkg') for contentFile in glob.glob(dbPath+"/*/*/CONTENTS"): for objFile in filter(lambda x:x.startswith('obj '), readLinesFile(contentFile)): res = PkgContents.reObj.search(objFile.strip()) if res: fn = res.groupdict()['filename'] if filter(lambda x:fn.startswith(x),protected): pkg = reVerSplit.search(os.path.dirname(contentFile)) if pkg: pkg = "%s/%s"%(pkg.groups()[:2]) allContent[fn] = pkg
def copyConfigFiles(self, configPath, configProtect): """Копирование конфигурационных файлов""" configDstFiles = self.scanProtectDirs(configPath, configProtect) if configDstFiles: self.logger.warn(_("Replaced file:")) for dst in configDstFiles: src = pathJoin(configPath, dst) if src != dst: dstDir = os.path.dirname(dst) self.createDir(configPath, dstDir) copy2(src, dst) sMode, sUid, sGid = getModeFile(src) os.chown(dst, sUid, sGid) os.chmod(dst, sMode) self.logger.warn(" " * 5 + dst) 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 applyTemplates(self,directory,grubDirectory): """Apply templates for root of system.""" self.clVars.Set("cl_chroot_path",directory, True) self.clVars.Set("cl_chroot_grub",grubDirectory, True) clTemplateCltPath = \ filter(lambda x:path.exists(x), map(lambda x:pathJoin(directory,x), self.clVars.Get('cl_template_clt_path'))) self.clVars.Set('cl_template_clt_path',clTemplateCltPath,True) self.clTempl = ProgressTemplate(self.setProgress,self.clVars, cltFilter=False, printSUCCESS=self.printSUCCESS, printWARNING=self.printWARNING, askConfirm=self.askConfirm, printERROR=self.printERROR) dirsFiles = self.clTempl.applyTemplates() if self.clTempl.getError(): raise InstallError(self.clTempl.getError()) else: return dirsFiles
def getNewData(self): """Get data migrate groups in new system""" fileName = pathJoin(self.prefixNewSystem, self.fileGroups) return filter(lambda x:\ self._reNumb.match(x[2]) and self.minGid<=int(x[2])<=self.maxGid, self.getData(fileName=fileName))
def createHome(userdata): if not userdata[5].startswith('/dev/'): homedir = pathJoin(self.prefixNewSystem,userdata[5]) if not path.exists(homedir): os.mkdir(homedir) os.chown(homedir,int(userdata[2]),int(userdata[3]))
def addFile(self,filename): newfilename = pathJoin(self.prefix,filename) filename = self.reCfg.sub("/",filename) self.content[filename] = {'type':'obj', 'md5':hashlib.md5(readFile(newfilename)).hexdigest(), 'mtime':str(int(os.stat(newfilename).st_mtime))}
def getNewData(self): """Get data migrate users in new system""" fileName = pathJoin(self.prefixNewSystem, self.filePasswd) return filter(lambda x:\ self._reNumb.match(x[2]) and self.minId<=int(x[2])<=self.maxId, self.getData(fileName=fileName))
def addLink(self,filename): newfilename = pathJoin(self.prefix,filename) filename = self.reCfg.sub("/",filename) self.content[filename] = {'type':'sym', 'target':os.readlink(newfilename), 'mtime':str(int(os.lstat(newfilename).st_mtime))}