You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
calculate-utils-2.2-lib/pym/server/share.py

140 lines
5.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#-*- coding: utf-8 -*-
# Copyright 2008-2010 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from cl_datavars import DataVars
from cl_print import color_print
# Перевод модуля
import cl_lang
tr = cl_lang.lang()
tr.setLocalDomain('cl_lib')
tr.setLanguage(sys.modules[__name__])
class shareVars:
"""Общие методы для классов модулей серверных программ"""
# Переменная объект Vars
clVars = False
def createClVars(self, clVars=False, returnImportVar=False):
"""Создает объект Vars"""
# Словарь импортируемых переменных из ini Файлов
dictImportVars = {}
if not clVars:
clVars = DataVars()
clVars.flServer()
dictImportVars = clVars.flIniFile()
# Устанавливаем у объекта объект Vars
self.clVars = clVars
if returnImportVar:
return dictImportVars
return True
def deleteServiceVarsInFile(self, service):
"""Удаляет переменные сервиса из ini файлов
После запуска этого метода объект self.clVars должен быть пересоздан
"""
importVarsDict = self.createClVars(False,True)
serviceNameVars = "_%s_" %service
for location in importVarsDict.keys():
for nameVar in importVarsDict[location]:
# Если имя сервиса присутствует в переменной -
# Удаляем переменную
if serviceNameVars in nameVar:
if not self.clVars.Delete(nameVar, location, "server"):
return False
self.clVars = False
return True
def saveVarsClient(self, listVarName):
"""Записывает переменные для клиента calcualte-client"""
#считаем переменные для клиента
dictVar = {}
flagError = False
for varName in listVarName:
value = self.clVars.Get(varName)
if not value and value != "":
self.printERROR(_("Variables %s is empty")%varName)
flagError = True
break
dictVar[varName] = value
if flagError:
return False
#Запишем переменные в клиентскую секцию
for name,value in dictVar.items():
value = str(value)
if not value.strip():
self.clVars.Delete(name)
if not self.clVars.Write(name,value,True,"remote","client"):
self.printERROR(_("Error in writing variable %s")%name)
flagError = True
break
if flagError:
return False
return True
def reloadDefaultVar(self, nameVar):
"""При получениии значения переменной снова
вызывается метод заполнения переменной"""
self.clVars.Set(nameVar,"",True)
self.clVars.__getattribute__(nameVar).countFill = 0
self.clVars.__getattribute__(nameVar).fillStart = True
return True
class servicesAPI(color_print):
"""Методы сервисов используемые другими сервисами"""
# Путь к модулю сервера
__pathServer__ = "/usr/lib/calculate/calculate-server/pym"
# Названия импортированных классов
__imports_names__ = []
# Импортированные классы
__imports_classes__ = {}
def __getServiceObj__(self, serviceName):
"""Получаем объект сервиса"""
if not serviceName in __imports_names__:
try:
classImport = getattr(__import__("cl_ldap", globals(),\
locals(),[]), serviceName)
except (ImportError, AttributeError):
self.printERROR(_("Class of service '%s' not found")\
%serviceName)
return False
__imports_classes__[serviceName] = classImport
__imports_names__.append(serviceName)
retObj = classImport()
else:
retObj = __imports_classes__[serviceName]()
return retObj
def searchUnixUser(self, userName, servUnixObj=None):
"""Поиск пользователя в LDAP ветке Unix сервиса"""
if not servUnixObj:
servUnixObj = self.__getServiceObj__("unix")
if not servUnixObj:
exit(1)
return servUnixObj.searchUnixUser(userName)
def searchPasswdUser(self, userName, servUnixObj=None):
"""Поиск пользователя в /etc/passwd"""
if not servUnixObj:
servUnixObj = self.__getServiceObj__("unix")
if not servUnixObj:
exit(1)
return servUnixObj.searchPasswdUser(userName)