def str2dict(s): """Convert string to dictionary: String format: {'key1':'value1','key2':'val\'ue2'} """ value = r'(?:\\\\|\\\'|[^\'])' pair = r""" \s*' # begin key (%(v)s*) ' # end key \s*:\s* # delimeter key/value ' # begin value (%(v)s*) '\s* # end value """ % {"v":value} reDict = re.compile(pair, re.X) reMatchDict = re.compile(""" ^{ # begin dict ((%(v)s,)* # many pair with comma at end %(v)s)? # pair without comma }$ # end dict """ % {'v':pair}, re.X) if reMatchDict.match(s.strip()): d = dict(reDict.findall(s)) replaceSlash = MultiReplace({'\\\\':'\\','\\\'':'\''}) for i in d.keys(): d[i] = replaceSlash(d[i]) return d else: cl_overriding.printERROR(_("wrong dictionary value: %s"%s)) cl_overriding.exit(1)
def str2list(s): """Convert string to list: String format: ['value1','val\'ue2'] """ value = r'(?:\\\\|\\\'|[^\'])' element = r""" \s*' # begin value (%(v)s*) '\s* # end value """ % {"v":value} reList = re.compile(element, re.X) reMatchList = re.compile(""" ^\[ # begin dict ((%(v)s,)* # many elements with comma at end %(v)s)? # element without comma \]$ # end dict """ % {'v':element}, re.X) if reMatchList.match(s.strip()): replaceSlash = MultiReplace({'\\\\':'\\','\\\'':'\''}) return [replaceSlash(i) for i in reList.findall(s)] else: cl_overriding.printERROR(_("wrong list value: %s"%s)) cl_overriding.exit(1)
def getVars(self, varsFilter=None, varsNames=[], verbose=1): """Словарь переменных для печати""" # проверка фильтра reFilter = False if varsFilter: try: reFilter = re.compile("%s" % varsFilter) except: cl_overriding.printERROR(_("wrong variable filter '%s'") % str(varsFilter)) cl_overriding.exit(1) ret = {} dictServicesVars = {} for section, moduleVar, fillobj in self._importList: dataVar = moduleVar.Data dictVars = dir(dataVar) for nameVar in dictVars: if not "__" in nameVar and ( not (getattr(dataVar, nameVar).has_key("hide") and getattr(dataVar, nameVar)["hide"]) or verbose > 1 or varsFilter ): if varsNames and not nameVar in varsNames: continue if reFilter and not reFilter.search(nameVar): continue self.Get(nameVar) variable = getattr(self, nameVar) service = variable.service.lower() ret[nameVar] = variable if not service in dictServicesVars: dictServicesVars[service] = {} dictServicesVars[service][nameVar] = variable return ret, dictServicesVars
def get_cl_env_location(self): """Aliases to env files""" envData = self.Get("cl_env_data") if envData: return map(lambda x: x[0], envData) else: cl_overriding.printERROR(_("Error:") + " " +\ _("Template variable cl_env_data is empty")) cl_overriding.exit(1)
def defaultPrint(self, string): try: self._printSysOut.write(string) except UnicodeError: self._printSysOut.write(string.encode('utf-8')) try: self._printSysOut.flush() except IOError: cl_overriding.exit(1)
def defined(self, vname): """Имеет ли значение переменная""" try: value = self.Get(vname) except: cl_overriding.printERROR(_("error, variable %s not found") % str(vname)) cl_overriding.exit(1) if value: return True else: return False
def __getSection(self, vname): """секция для записи в ini файл переменной vname - имя переменной """ if not hasattr(self, vname): try: self.Get(vname) except self.DataVarsError, e: cl_overriding.printERROR(_("Template variable %s not found") % vname) cl_overriding.printERROR(e) cl_overriding.exit(1)
def getHash(password, encr): """Получить хеш пароля password - пароль encr - алгоритм шифрования, например 'ssha' """ encryptObj = encrypt() hashPwd = encryptObj.getHashPasswd(password, encr.lower()) if hashPwd: return hashPwd else: encryptObj.printERROR(_("Password encryption error, " "method getHash()")) cl_overriding.exit(1)
def getApiClass(self, apiFile): importPath, moduleName = os.path.split(apiFile) moduleName = moduleName.rpartition(".py")[0] if not importPath in sys.path: sys.path.insert(0, importPath) try: className = getattr(__import__(moduleName, globals(), locals(), ['serviceAPI']), 'serviceAPI') except (ImportError, AttributeError), e: self.printERROR(str(e).strip()) self.printERROR(_("Failed to import module %s")% apiFile) cl_overriding.exit(1)
def checkUtils(*utils): """Check utils, exit if it not found and return fullpath""" retval = [] for util in utils: utilPath = getProgPath(util) if not utilPath: cl_overriding.printERROR(_("Command not found '%s'")% path.basename(util)) cl_overriding.exit(1) retval.append(utilPath) if len(retval) == 1: return retval[0] else: return retval
def __getPathCalculateIni(self, location): """Получить путь к ini файлу по алиасу пути""" retData = self.Get("cl_env_data") ini_dict = {} ini_dict.update(retData) if location in ini_dict.keys(): name_calculate_ini = ini_dict[location] else: cl_overriding.printERROR( _("Unable to find alias '%s' of the path to the file " "storing template variables templates") % location ) cl_overriding.exit(1) return pathJoin(self.Get("cl_chroot_path"), name_calculate_ini)
def runMethodToPkg(self, pkgName, methodName, argv=[]): """Execute method from pkg""" pkgObj = self.getPkgApi(pkgName) if pkgObj is None: return "" if not hasattr(pkgObj, methodName) or\ not callable(getattr(pkgObj, methodName)): self.printERROR(_("Method %(method)s not found in object API of" " service %(service)s") %{'method':methodName, 'service':pkgObj.getServiceName()}) cl_overriding.exit(1) if argv: res = getattr(pkgObj, methodName)(*argv) else: res = getattr(pkgObj, methodName)() return res
def getAllPkgApi(self): """get all packages api objects""" self.createClLibVars(clLibVars=self.clLibVars) apiDict = self.clLibVars.Get('cl_api') if not apiDict or not type(apiDict) is dict: return [] apiFiles = apiDict.values() apiObjects = [] for apiFile in apiFiles: className = self.getApiClass(apiFile) try: apiObjects.append(className()) except: self.printERROR(_("Failed to create an API object")) self.printERROR(_("Module %s")% apiFile) cl_overriding.exit(1) return apiObjects
def printLine(self, argL, argR, offsetL=0, printBR=True): """Печатает справа и слева консоли цветные сообщения""" #Допустимые цвета colorDict = {\ # цвет по умолчанию '':self.defaultPrint, # ярко зеленый 'greenBr':self.greenBrightPrint, # ярко голубой 'blueBr':self.blueBrightPrint, # ярко красный 'redBr':self.redBrightPrint, # ярко желтый 'yellowBr':self.yellowBrightPrint, } # cмещение от левого края консоли #offsetL = 0 for color,leftString in argL: offsetL += self.lenString(leftString) if colorDict.has_key(color): # печатаем и считаем смещение colorDict[color](leftString) else: colorDict[''](leftString) # cмещение от правого края консоли offsetR = 0 for color,rightString in argR: offsetR += self.lenString(rightString) # Добавляем пробелы if offsetR: self.printRight(offsetL, offsetR) for color,rightString in argR: if colorDict.has_key(color): # печатаем и считаем смещение colorDict[color](rightString) else: colorDict[''](rightString) if printBR: self._printSysOut.write("\n") try: self._printSysOut.flush() except IOError: cl_overriding.exit(1)
def getPkgApi(self, pkgName): """get package api""" if not pkgName in self.apiObjs: self.createClLibVars(clLibVars=self.clLibVars) apiDict = self.clLibVars.Get('cl_api') if not apiDict or not type(apiDict) is dict: return None if not pkgName in apiDict: return None apiFile = apiDict[pkgName] className = self.getApiClass(apiFile) try: apiObject = className() except Exception, e: self.printERROR(str(e).strip()) self.printERROR(_("Failed to create an API object")) self.printERROR(_("Module %s")% apiFile) cl_overriding.exit(1) self.apiObjs[pkgName] = apiObject return apiObject
def get_os_net_domain(self): """Get net domain name""" if path.exists('/proc/self/fd/1') and \ readlink('/proc/self/fd/1') == '/dev/console' and \ self.Get('os_root_dev') == '/dev/nfs': return "local" textLines = self._runos("hostname -d 2>&1") if textLines is False: cl_overriding.printERROR(_("Error executing 'hostname -d'")) return cl_overriding.exit(1) domain = "" if textLines: domain = textLines[0] if not domain: cl_overriding.printERROR(_("Error:") + " " +\ _("Domain name not found")) cl_overriding.printERROR(\ _("Command 'hostname -d' returns an empty value")) return cl_overriding.exit(1) elif re.search("^hostname: ",domain): return "local" else: return domain
def defaultPrint(self, string): self._printSysOut.write(string) try: self._printSysOut.flush() except IOError: cl_overriding.exit(1)