Exemple #1
0
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)
Exemple #2
0
def getUserPassword(flag="dialog", pwDialog=False):
        """Получить пароль у пользователя

        flag - опция "dalog" или "stdin" - откуда получаем пароль
        pwDialog  - структура для вывода приглашения в режиме диалога
        """
        userPwd = ""
        if flag == "dialog":
            if not pwDialog:
                pwDialog = [_("New password"),
                            _("Retype the new password")]
            pwdA = getpass.getpass(pwDialog[0]+":")
            pwdB = getpass.getpass(pwDialog[1]+":")
        elif flag == "stdin":
            pwdA = sys.stdin.readline().rstrip()
            pwdB = sys.stdin.readline().rstrip()
        else:
            cl_overriding.printERROR(_("ERROR in function getUserPassword, \
incorrect option 'flag=%s'")%flag)
            return False
        if not pwdA or not (pwdA == pwdB):
            cl_overriding.printERROR(_("ERROR") + ": " +\
            _("wrong password")+ ": " + _("try again"))
            return False
        userPwd = pwdA
        return userPwd
    def __writeVarValue(self, vname, val, location, header):
        """Записать значение в calculate.ini

        Параметры:
        vname       имя переменной
        val         значение переменной
        location    расположение ini файла ('default', 'local', 'remote')
        header      раздел ini файла ('client', 'server', 'main')

        Возвращаемые значение:
        True        запись успешна
        False       запись не удалaсь
        """
        # получаем путь до ini файла
        name_calculate_ini = self.__getPathCalculateIni(location)
        # извлекаем из полного имени файла путь
        onlydir = os.path.split(name_calculate_ini)[0]
        try:
            # проверяем чтобы путь до ини файла существовал
            if not os.path.exists(onlydir):
                # создаем его если отсутствует
                os.makedirs(onlydir)
        except OSError(nerr, msg):
            cl_overriding.printERROR(str(nerr) + " " + str(msg))
            return False
        config = iniParser(name_calculate_ini)
        # Получаем секцию конфигурационного файла
        if not header:
            header = self.__getSection(vname)
        return config.setVar(header, {vname: convertStrListDict(val)})
Exemple #4
0
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 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 GetIniVar(self, section_dot_nameVar):
        """Получить значение переменной из конфигурационного файла

        section_dot_nameVar - "имя_секции.имя_переменной_профиля"
        """
        calculate_ini_files = self.Get("cl_env_path")
        section, spl, name_var = section_dot_nameVar.rpartition(".")
        if section and name_var:
            pass
        elif name_var:
            section = "main"
        else:
            cl_overriding.printERROR(_("error Datavars.GetIniVar: empty section"))
            return False
        # Значение переменной в env файлах
        valueVar = ""
        for name_calculate_ini in calculate_ini_files:
            # проверить сущестование ini файла
            if os.path.exists(name_calculate_ini):
                # получить объект настроенный на ini
                config = iniParser(name_calculate_ini)
                # получаем значение переменной из секции
                data = config.getVar(section, name_var, checkExistVar=True)
                if data is False:
                    return False
                existsVar, value = data
                if existsVar:
                    valueVar = value
        return valueVar.encode("UTF-8")
Exemple #7
0
 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 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)
Exemple #10
0
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
Exemple #11
0
 def addHandler(self):
     """Добавление обработчика"""
     if not self.logger.handlers:
         try:
             handler = logging.handlers.RotatingFileHandler(self.filename,
                                               maxBytes=self.maxBytes,
                                               backupCount=self.backupCount)
         except Exception, e:
             cl_overriding.printERROR("logging - "+" "+self.programName+\
                                      " - "+str(e))
             return False
         handler.setLevel(self.level)
         handler.setFormatter(self.formatter)
         self.logger.addHandler(handler)
Exemple #12
0
 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)
Exemple #13
0
 def __Set(self, nameVar, value, force=False):
     nameMethod = "get_" + nameVar
     if not hasattr(self, nameVar) and self.__findVarData(nameVar):
         dictVar, methodFill = self.__findVarData(nameVar)
         varobj = var(self)
         # Устанавливаем аттрибуты
         self.__setAttributesVar(varobj, nameVar, dictVar)
         if methodFill:
             varobj.Fill = methodFill
         setattr(self, nameVar, varobj)
     if hasattr(self, nameVar):
         if not force and "r" in getattr(self, nameVar).mode:
             cl_overriding.printERROR(_("Attempt to rewrite a variable for reading") + ": %s" % nameVar)
             return False
         getattr(self, nameVar).fillStart = False
         return getattr(self, nameVar).Set(value)
Exemple #14
0
 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