Exemplo n.º 1
0
    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)})
Exemplo n.º 2
0
    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")
Exemplo n.º 3
0
 def get_cl_assemble_dev(self):
     """Used devices for system assembling"""
     envFile = '/etc/calculate/assemble.env'
     envData = iniParser(envFile)
     return map(lambda x:_toUNICODE(envData.getVar(x,
                          'os_assemble_root_dev')).encode('utf-8'),
                 self.Get('cl_assemble_distro'))
Exemplo n.º 4
0
 def get_cl_assemble_distro(self):
     """Current assembling systems"""
     envFile = '/etc/calculate/assemble.env'
     envData = iniParser(envFile)
     return filter(lambda x:envData.getVar(x,
                           'os_assemble_root_dev'),
         map(lambda x:_toUNICODE(x).encode('utf-8').rpartition(
                                                 '/profiles/')[2],
                envData.getAllSectionNames()))
Exemplo n.º 5
0
 def _getFromEnv(self,var):
     """Get variable from env"""
     section = self.Get('os_assemble_system_profile').rpartition(
                          '/profiles/')[2]
     envFile = '/etc/calculate/assemble.env'
     envData = iniParser(envFile)
     res = envData.getVar(section,var)
     if res != False:
         res = _toUNICODE(res).encode('utf-8')
     return res
Exemplo n.º 6
0
 def isAssemble(self, showError=True):
     """Detect system assembling"""
     if self.logicObj.clVars.Get("cl_builder_distro") and self.logicObj.clVars.Get("cl_builder_path"):
         inidata = iniParser(self.envFile)
         res = inidata.getVar(self.__sectionName(), "cl_assemble_step_world", checkExistVar=True)
         if not res[0] or not "finish" in _toUNICODE(res[1]).encode("utf-8"):
             if showError:
                 self.printERROR(_("System assemble not completed."))
             return False
         return True
     else:
         return False
Exemplo n.º 7
0
 def convert(self):
     """Конвертирование переменных сервера в словарь новых переменных"""
     parserObj = iniParser(self.envPath)
     clientVars = parserObj.getAreaVars("client")
     # convertVars = {"service":{"name":"value", ...}, ...}
     convertVars = {}
     for nameVar in clientVars.keys():
         if nameVar in self.convertData.keys():
             service = self.convertData[nameVar]["service"]
             nameVarService = self.convertData[nameVar]["replace"]
             value = convertStrListDict(clientVars[nameVar].encode("UTF-8"))
             if not service in convertVars.keys():
                 convertVars[service] = {}
             convertVars[service][nameVarService] = value
     return convertVars
Exemplo n.º 8
0
    def flIniFile(self):
        """Заместить значение переменных значениями из ини файлов

        Возвращаемые значения:
        cловарь импортированных переменных -    переменные считаны
        False  -  файл не был обнаружен
        """
        # Cловарь переменных из ini файлов
        importVars = {}
        calculate_ini_files = self.Get("cl_env_path")
        # активные секции (секции из которых будут использованы переменные)
        act_section = self.__getActiveSections()
        set_act_section = set(act_section)
        i = 0
        # Алиасы к путям env
        locations = self.Get("cl_env_location")
        for name_calculate_ini in calculate_ini_files:
            # проверить сущестование ini файла
            if os.path.exists(name_calculate_ini):
                # получить объект настроенный на ini
                config = iniParser(name_calculate_ini)
                # получаем все секции из конфигурационного файла
                allsect = config.getAllSectionNames()
                if not allsect:
                    continue
                # находим встречающиеся у обоих секции
                act_sect = tuple(set(allsect) & set_act_section)
                # словарь переменных для ini - файла
                importFileVars = {}
                # получаем все переменные из всех секций
                for section in act_sect:
                    allvars = config.getAreaVars(section)
                    if allvars == False:
                        return False
                    # словарь переменных для ini - файла
                    importFileVars = {}
                    # принудительно переписать все переменные окружения
                    # полученные из ini
                    for (k, v) in allvars.items():
                        k = k.encode("UTF-8")
                        value = convertStrListDict(v.encode("UTF-8"))
                        self.Set(k, value, True)
                        importFileVars[k] = value
                if i < 3:
                    importVars[locations[i]] = importFileVars
            i += 1
        return importVars
Exemplo n.º 9
0
 def GetRemoteInfo(self, envFile):
     """
     Get information variables from server env
     """
     optionsInfo = {}
     # get ini object
     config = iniParser(envFile)
     # get all section from ini object
     allsect = config.getAllSectionNames()
     if allsect:
         # sectin - service name
         for section in allsect:
             allvars = config.getAreaVars(section)
             if allvars == False:
                 return False
             # get service option
             options = {}
             for varName, value in allvars.items():
                 varName = varName.encode("UTF-8")
                 value = value.encode("UTF-8")
                 options[varName] = value
             if options:
                 optionsInfo[section] = options
     return optionsInfo
Exemplo n.º 10
0
    def __deleteVarValue(self, vname, location, header):
        """Удалить переменную в calculate.ini

        Параметры:
        vname       имя переменной
        location    расположение ini файла ('default', 'local', 'remote')

        Возвращаемые значение:
        True        удалено успешна
        False       удаление не удалось
        """
        # получаем путь до ini файла
        name_calculate_ini = self.__getPathCalculateIni(location)
        # извлекаем из полного имени файла путь
        onlydir = os.path.split(name_calculate_ini)[0]
        # проверяем чтобы путь до ини файла существовал
        if not os.path.exists(onlydir):
            return False
        config = iniParser(name_calculate_ini)
        # Получаем секцию конфигурационного файла
        if not header:
            header = self.__getSection(vname)
        # Удаляем переменную
        allVars = config.getAreaVars(header)
        if allVars is False:
            return False
        if vname in allVars.keys():
            retDelVar = config.delVar(header, vname)
            retDelArea = True
            if not config.getAreaVars(header):
                retDelArea = config.delArea(header)
            if retDelArea and retDelVar:
                return True
            else:
                return False
        return True