Browse Source

Создана структура модуля

legacy27
parent
commit
169141c918
  1. 15
      README
  2. BIN
      i18n/cl_ldap_ru.mo
  3. 30
      ldif/base.ldif
  4. 62
      pym/cl_fill_ldap.py
  5. 474
      pym/cl_ldap_api.py
  6. 53
      pym/cl_ldap_service.py
  7. 109
      pym/cl_ldap_setup_cmd.py
  8. 83
      pym/cl_share_cmd.py
  9. 108
      pym/cl_vars_ldap.py
  10. 0
      pym/ldap/__init__.py
  11. 33
      pym/ldap/datavars.py
  12. 40
      pym/ldap/ldap.py
  13. 0
      pym/ldap/utils/__init__.py
  14. 47
      pym/ldap/utils/cl_ldap_setup.py
  15. 20
      pym/ldap/variables/__init__.py
  16. 37
      pym/ldap/variables/action.py
  17. 20
      pym/ldap/variables/ldap.py
  18. 74
      pym/ldap/wsdl_ldap.py
  19. 65
      scripts/cl-ldap-setup
  20. 5
      setup.cfg
  21. 84
      setup.py

15
README

@ -1,15 +0,0 @@
AUTHOR: Calculate Ltd. <support@calculate.ru>
INSTALL
-------
calculate-ldap needs the following library version installed, in order to run:
python >= 2.5
python-ldap >= 2.0.0
pyxml >= 0.8
calculate-lib >= 2.2.0.0
To install calculate-ldap, just execute the install script 'setup.py'.
Example:
./setup.py install

BIN
i18n/cl_ldap_ru.mo

30
ldif/base.ldif

@ -1,30 +0,0 @@
# Directory Server
dn: #-ld_base_dn-#
objectClass: dcObject
objectClass: organization
dc: #-ld_base_root-#
o: Calculate Directory Server
# Services
dn: #-ld_services_dn-#
objectClass: top
objectClass: organizationalUnit
ou: Services
# Admin
dn: #-ld_admin_dn-#
cn: #-ld_admin_login-#
sn: #-ld_admin_login-#
objectClass: person
objectClass: top
description: LDAP Administrator stuff
userPassword: #-ld_admin_hash-#
# Bind
dn: #-ld_bind_dn-#
cn: #-ld_bind_login-#
sn: #-ld_bind_login-#
objectClass: person
objectClass: top
description: LDAP Proxy User
userPassword: #-ld_bind_hash-#

62
pym/cl_fill_ldap.py

@ -1,62 +0,0 @@
#-*- coding: utf-8 -*-
# Copyright 2008-2010 Mir 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 os
from cl_datavars import glob_attr
from cl_utils import genpassword
from encrypt import getHash
class fillVars(glob_attr):
addDn = lambda x,*y: ",".join(y)
genDn = lambda x,*y: "=".join(y)
def get_ld_temp_dn(self):
#DN временного пользователя root (для инициализации базы данных)
return self.addDn(self.genDn("cn", "ldaproot"), self.Get('ld_base_dn'))
def get_ld_temp_pw(self):
"""пароль временного пользователя root"""
return genpassword()
def get_ld_temp_hash(self):
"""hash пароля временного root"""
return getHash(self.Get('ld_temp_pw'), self.Get('ld_encrypt'))
def get_ld_ldap_access_pw_conf(self):
"""строки доступа к аттрибуту userPassword в slapd.conf"""
return ' by dn="%s" write' %self.Get("ld_admin_dn")
def get_ld_ldap_access_dn_conf(self):
"""строки доступа к LDAP DN сервиса в slapd.conf"""
templStart = 'access to dn.regex=".*%(repl_dn)s$"\n'\
' by dn="%(admin_dn)s" write\n'\
' by dn="%(repl_dn)s" write\n'\
' by dn="%(bind_dn)s" read\n'
templMail = ' by dn="%(mail_dn)s" read\n'
templEnd = ' by * none'
templ = ""
if self.Get("ld_repl_set")=="on" and self.Get("ld_repl_id")!="":
templ += templStart
templDict = {'admin_dn':self.Get("ld_admin_dn"),
'repl_dn':self.Get("ld_repl_dn"),
'bind_dn':self.Get("ld_bind_dn")}
mailDn = self.clGetVar("calculate-mail", "cl_mail_dn")
if mailDn:
templDict.update({'mail_dn':mailDn})
templ += templMail
templ += templEnd
return templ%templDict
return ""

474
pym/cl_ldap_api.py

@ -1,474 +0,0 @@
#-*- coding: utf-8 -*-
# Copyright 2008-2010 Mir 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 os, sys, re
#from cl_print import color_print
from cl_datavars import DataVars
from server.utils import execProg
from cl_template import template
from cl_api import packagesAPI, APIError
from server.ldap import iniLdapParser, ldapFunction, shareldap
from server.utils import genSleep
from cl_utils import removeDir, _error
from cl_lang import lang
tr = lang()
tr.setLocalDomain('cl_ldap')
tr.setLanguage(sys.modules[__name__])
__version__ = "2.2.0.0"
__app__ = "calculate-ldap"
from cl_abstract import abs_api_service
class DataVarsLdap(DataVars):
"""Хранение переменных"""
# Имя секции в calculate2.env
envSection = "ldap"
def importLdap(self, **args):
'''Импорт переменных для calculate-ldap'''
# Импорт переменных
self.importData(self.envSection, ('cl_vars_ldap','cl_fill_ldap'))
class Template:
"""Templates methods"""
def applyTemplates(self):
"""Apply templates"""
clTempl = template(self.clVars)
dirsFiles = clTempl.applyTemplates()
if clTempl.getError():
self.printERROR(clTempl.getError().strip())
return False
else:
return dirsFiles
class shareVars:
"""share methods template vars"""
# template variables
clVars = False
def createClVars(self, clVars=False):
"""Создает объект Vars"""
if not clVars:
clVars = DataVarsLdap()
# Импортируем переменные
clVars.importLdap()
# Заменяем значения переменных переменными из env файлов
clVars.flIniFile()
# Устанавливаем у объекта атрибут объект переменных
self.clVars = clVars
return self.clVars
class internalMethods(abs_api_service, shareVars, Template):
'''Methods ldap service'''
prioritet = 25
nameService = "ldap"
nameDaemon = 'slapd'
_templDict = {'name':nameDaemon}
# files
pidFile = '/var/run/openldap/%(name)s.pid' %_templDict
# command
cmdPath = '/etc/init.d/%(name)s' %_templDict
_templDict.update({'cmd':cmdPath})
cmdStart = '%(cmd)s start' %_templDict
cmdReStart = '%(cmd)s restart' %_templDict
cmdStop = '%(cmd)s stop' %_templDict
cmdShowDaemons = 'rc-update show default'
reShowDaemons = re.compile("(.+)\s+\|\s+.+")
cmdAddRunlevel = 'rc-update add %(name)s default' %_templDict
cmdDelRunlevel = 'rc-update del %(name)s default' %_templDict
def get_service_name(self):
'''Get name service'''
return self.nameService
def get_pkg_name(self):
'''Get name service'''
return __app__
def get_vars(self):
'''Get Service vars'''
return self.createClVars(self.clVars)
def is_setup(self):
'''Is setup service (True/False)'''
self.createClVars(self.clVars)
return self.clVars.Get('sr_ldap_set') == "on"
def _getRunlevelDaemons(self):
"""Получаем всех демонов в default уровне"""
textLines = execProg(self.cmdShowDaemons)
if textLines is False:
self.printERROR(_("ERROR") + ": " + self.cmdShowDaemons)
return False
else:
daemons = []
for line in textLines:
res = self.reShowDaemons.search(line)
if res:
daemon = res.groups(0)[0]
daemons.append(daemon)
return daemons
def is_start(self):
'''Run ldap server (True/False)'''
if os.access(self.pidFile, os.R_OK):
pid = open(self.pidFile).read().strip()
if pid:
procDir = "/proc"+"/"+pid
if os.access(procDir, os.F_OK):
return True
return False
def start(self):
'''Start LDAP server'''
if not self.is_start():
if execProg(self.cmdStart) is False:
self.printERROR(_("Can't execute '%s'") %self.cmdStart)
self.printNotOK(_("Starting LDAP") + " ...")
return False
return True
def restart(self):
'''Restart LDAP server'''
if self.is_start():
if execProg(self.cmdReStart) is False:
self.printERROR(_("Can't execute '%s'") %self.cmdReStart)
self.printNotOK(_("Restarting LDAP")+ " ...")
return False
else:
return self.start()
return True
def stop(self):
'''Stop LDAP server'''
if self.is_start():
if execProg(self.cmdStop) is False:
self.printERROR(_("Can't execute '%s'") %self.cmdStop)
self.printNotOK(_("Stopping LDAP")+ " ...")
return False
return True
def is_runlevel(self):
'''Находится ли LDAP в автозагрузке'''
daemons = self._getRunlevelDaemons()
if daemons is False:
return False
if self.nameDaemon in daemons:
return True
else:
return False
def add_runlevel(self):
'''Add daemon to runlevel'''
if not self.is_runlevel():
if execProg(self.cmdAddRunlevel) is False:
self.printERROR(_("Can't execute '%s'") %self.cmdAddRunlevel)
self.printNotOK(_("service %(name)s added to runlevel")\
%self._templDict + " ...")
return False
return True
def del_runlevel(self):
'''Delete daemon from runlevel'''
if self.is_runlevel():
if execProg(self.cmdDelRunlevel) is False:
self.printERROR(_("Can't execute '%s'") %self.cmdDelRunlevel)
self.printNotOK(_("service %(name)s removed from runlevel")\
%self._templDict + " ...")
return False
return True
def get_prioritet(self):
'''Get run daemon prioritet'''
return self.prioritet
def del_vars_from_env(self):
'''Delete template vars in env files'''
self.createClVars(self.clVars)
deleteVariables = ("sr_ldap_set",)
locations = map(lambda x: x[0], self.clVars.Get("cl_env_data"))
for varName in deleteVariables:
for locate in locations:
if not self.clVars.Delete(varName, location=locate,
header=self.clVars.envSection):
fileName = filter(lambda x: x[0] == locate,
self.clVars.Get("cl_env_data"))[0][1]
self.printERROR(_("Can't delete variable '%(name)s' "
"in file %(file)s") %{'name':varName,
'file':fileName})
return False
return True
def updateVars(self):
self.createClVars()
return True
def get_service_info(self, request):
'''Get service information'''
res = ""
if request == "scheme":
self.createClVars(self.clVars)
res = self.clVars.Get('ld_ldap_scheme_conf')
elif request == "access_pw":
self.createClVars(self.clVars)
res = self.clVars.Get('ld_ldap_access_pw_conf')
elif request == "access_dn":
self.createClVars(self.clVars)
res = self.clVars.Get('ld_ldap_access_dn_conf')
return res
def scheme(self):
'''include lines in slapd.conf'''
return self.get_service_info('scheme')
def access_pw(self):
'''Access userPasswod lines in slapd.conf'''
return self.get_service_info('access_pw')
def access_dn(self):
'''Access DN lines in slapd.conf'''
return self.get_service_info('access_dn')
def apply_templates(self):
'''Apply package templates'''
if self.is_setup():
self.clVars.Set("ac_ldap_update","up", force=True)
return Template.applyTemplates(self)
return True
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(
cls, *args, **kwargs)
return cls._instance
class allMethods(Singleton, internalMethods, shareldap):
"""Методы севисa Ldap"""
# Базовый ldif файл
ldifFileBase = '/usr/lib/calculate-2.2/calculate-ldap/ldif/base.ldif'
apiFile = '/usr/lib/calculate-2.2/calculate-ldap/pym/cl_ldap_api.py'
libAPIObj = packagesAPI()
def removeLdapDatabase(self):
"""Удаляем предыдущую базу данных"""
pathDatabase = "/var/lib/openldap-data"
#if os.path.exists(pathDatabase) and os.listdir(pathDatabase):
#if os.system("rm /var/lib/openldap-data/* &>/dev/null") !=0:
#self.printERROR("Can't remove /var/lib/openldap-data/*")
#return False
#return True
if os.path.exists(pathDatabase):
fileOrDirNames = os.listdir(pathDatabase)
if fileOrDirNames:
for fileOrDirName in fileOrDirNames:
fullFileOrDirName = os.path.join(pathDatabase,
fileOrDirName)
if os.path.isdir(fullFileOrDirName):
try:
removeDir(pathDatabase)
except:
self.printERROR(_("Can't remove directory %s")\
%fullFileOrDirName)
return False
else:
try:
os.remove(fullFileOrDirName)
except:
self.printERROR(_("Can't remove file %s")\
%fullFileOrDirName)
return False
self.printOK(_("Erased LDAP Database") + " ...")
return True
def connectLdapServer(self):
"""Соединяемся с LDAP сервером
используем DN и пароль временного админстратора
"""
# Если раннее была ошибка то выходим
if self.getError():
self.printERROR (_("ERROR") + ": " +\
self.getError().strip())
return False
tmpDn = self.clVars.Get("ld_temp_dn")
tmpPw = self.clVars.Get("ld_temp_pw")
ldapObj = ldapFunction(tmpDn, tmpPw)
# Генератор задержек
wait = genSleep()
while ldapObj.getError():
try:
# Задержка
wait.next()
except StopIteration:
break
# Очистка ошибки
_error.error = []
ldapObj = ldapFunction(tmpDn, tmpPw)
self.ldapObj = ldapObj
self.conLdap = ldapObj.conLdap
if ldapObj.getError():
# Удаляем одинаковые ошибки
listError = []
for e in ldapObj.error:
if not e in listError:
listError.append(e)
_error.error = listError
self.printERROR(_("Can not connected to LDAP server"))
return False
return True
def setup(self, force=False):
"""Настройка LDAP сервиса (создание дерева)"""
# Принудительная установка
if self.clVars.Get("sr_ldap_set") == "on" and not force:
self.printWARNING (_("WARNING") + ": " +\
_("LDAP server is configured")+ ".")
return True
if not force:
# предупреждение при выполнении этой программы будут изменены
# конфигурационные файлы и база данных сервиса LDAP а также
# конфигурационные файлы установленных сервисов
self.printWARNING (_("WARNING") + ": " +\
_("Executing of the program will change") + " " +\
_("the configuration files and database of LDAP service")+\
".")
# если вы готовы продолжить работу программы нажмите Y если нет n
messDialog = \
_("If you are ready to continue executing the program")+", "+\
_("input 'yes'") +", "+ _("if not 'no'")
if not dialogYesNo(messDialog):
return True
else:
# делаем backup
# Проверим запущен ли ldap
if not self.is_start():
# Запускаем LDAP сервер
if not self.start():
return False
#if not self.backupServer():
#return False
if self.is_runlevel():
# Удаляем из автозапуска демона
if not self.del_runlevel():
return False
listAPIObj = self.libAPIObj.all.APIList()
listAPIObjReverse = self.libAPIObj.all.APIListReverse()
if filter(lambda x:\
x.api.get_pkg_name()=="calculate_ldap",listAPIObj):
self.printERROR(_("Can not found API module in package "
"calculate-ldap"))
self.printWARNING(_("Run: cl-ldap-setup --install"))
return False
# Останавливаем все установленные сервисы
for obj in listAPIObjReverse:
apiObj = obj.api
if hasattr(apiObj, 'stop') and not apiObj.stop():
return False
# Удаляем из автозагрузки все установленные сервисы
for obj in listAPIObjReverse:
apiObj = obj.api
if hasattr(apiObj, 'del_runlevel') and not apiObj.del_runlevel():
return False
# Удаляем из крона скрипт для чистки удаленых пользователей
# создаем объект репликации
#objRepl = servRepl()
#if not objRepl.cronReplicationOFF():
#return False
# Удаляем из share файл .replrun
#if not self.servSambaObj.delReplFile(self.clVars):
#return False
# Удаляем переменные
for obj in listAPIObjReverse:
apiObj = obj.api
if hasattr(apiObj,'del_vars_from_env') and \
not apiObj.del_vars_from_env():
return False
# Получим путь к ldap файлу
ldapParser = iniLdapParser()
ldapFile = ldapParser.nameIniFile
# Удаляем ldap файл
if os.path.exists(ldapFile):
os.remove(ldapFile)
self.clVars.Write("sr_ldap_set", "off",force=True)
self.clVars.Set("sr_ldap_set", "on", force=True)
self.clVars.Set("ac_ldap_setup","up", force=True)
# Первый проход
self.clVars.Set("cl_pass_step", "1", True)
if self.applyTemplates() is False:
self.printERROR(_("Can not apply templates") + ":" + " " +\
_("first pass"))
return False
# Удаляем старую базу данных
if not self.removeLdapDatabase():
return False
# Запускаем LDAP сервер
if not self.start():
return False
# Соединяемся с LDAP временным пользователем
if not self.connectLdapServer():
return False
# Получаем текст нужного ldif-a
baseLdif = self.createLdif(self.ldifFileBase)
# Если нет ошибок при соединении применяем ldif
if not self.ldapObj.getError():
self.ldapObj.ldapAdd(baseLdif)
if self.ldapObj.getError():
print _("LDAP Error") + ": " + self.ldapObj.getError().strip()
return False
self.printOK(_("Added ldif file") + " ...")
# Второй проход,
# удаляем временного пользователя root из конфигурационного файла
self.clVars.Set("cl_pass_step","2",True)
if self.applyTemplates() is False:
self.printERROR(_("Can not apply profiles") +":"+ _("second pass"))
return False
# Перезапускаем LDAP сервер
if not self.restart():
return False
# Записываем данные администратора сервера
ldapParser.setVar("admin",
{"DN":self.clVars.Get("ld_admin_dn"),
"PASS":self.clVars.Get("ld_admin_pw")})
# Устанавливаем автозапуск демона
if not self.add_runlevel():
return False
# Записываем переменные для пользователя
#clientVars = ["ur_organization", "ur_signature"]
#if not self.saveVarsClient(clientVars):
#return False
#self.apply_templates()
self.clVars.Write("sr_ldap_set","on",force=True)
self.printOK(_("LDAP service configured") + " ...")
return True
REGISTERED_METHODS = ['access_pw', 'access_pw', 'add_runlevel',
'apply_templates', 'get_pkg_name', 'get_prioritet', 'get_service_info',
'get_service_name', 'get_vars', 'is_runlevel', 'is_setup', 'is_start',
'restart', 'scheme', 'setup', 'start', 'stop']
class serviceAPI(object):
"""Proxy object"""
def __init__(self):
self.__subject = allMethods()
for attr in dir(self.__subject):
if attr in REGISTERED_METHODS:
object.__setattr__(self, attr, getattr(self.__subject, attr))

53
pym/cl_ldap_service.py

@ -1,53 +0,0 @@
#-*- coding: utf-8 -*-
# Copyright 2008-2010 Mir 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.
from cl_ldap_api import allMethods, __app__
from cl_utils import appendProgramToEnvFile, removeProgramToEnvFile
import sys
from cl_lang import lang
lang().setLanguage(sys.modules[__name__])
class ldapService(allMethods):
def installProg(self):
'''Install this program'''
apiDict = self.clVars.Get("cl_api")
apiDict.update({__app__:self.apiFile})
self.clVars.Write("cl_api", force=True)
if not appendProgramToEnvFile(__app__, self.clVars):
self.printERROR(_("Can not save '%s'") %__app__ + " " +\
_("to %s") %self.clVars.Get("cl_env_path")[0])
return False
self.printOK(_("Save install variables"))
return True
def uninstallProg(self):
'''Uninstall this program'''
apiDict = self.clVars.Get("cl_api")
if __app__ in apiDict:
apiDict.pop(__app__)
self.clVars.Write("cl_api", force=True)
if not removeProgramToEnvFile(__app__, self.clVars):
self.printERROR(_("Can not remove '%s' to %s")%(__app__,
self.clVars.Get("cl_env_path")[0]))
return False
self.printOK(_("Delete install variables"))
return True
def printVars(self, *arg, **argv):
"""Печать существующих переменных"""
self.clVars.printVars(*arg, **argv)

109
pym/cl_ldap_setup_cmd.py

@ -1,109 +0,0 @@
#-*- coding: utf-8 -*-
# Copyright 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.
from cl_ldap_api import __app__, __version__
from cl_ldap_service import ldapService
from cl_opt import opt
import sys
from cl_share_cmd import share_cmd
# Перевод сообщений для программы
from cl_lang import lang
lang().setLanguage(sys.modules[__name__])
# Использование программы
USAGE = _("%prog [options]")
# Коментарии к использованию программы
COMMENT_EXAMPLES = _("Create LDAP tree")
# Пример использования программы
EXAMPLES = _("%prog")
# Описание программы (что делает программа)
DESCRIPTION = _("Creating LDAP tree")
# Опции командной строки
CMD_OPTIONS = [{'shortOption':"f",
'longOption':"force",
'help':_("forced setup service ldap")},
{'longOption':"install",
'help':_("configure the system to install this package")},
{'longOption':"uninstall",
'help':_("configure the system to uninstall this package")}]
class ldap_setup_cmd(share_cmd):
def __init__(self):
# Объект опций командной строки
self.optobj = opt(package=__app__,
version=__version__,
usage=USAGE,
examples=EXAMPLES,
comment_examples=COMMENT_EXAMPLES,
description=DESCRIPTION,
option_list=CMD_OPTIONS +\
opt.variable_control+opt.color_control,
check_values=self.checkOpts)
# Создаем объект логики
self.logicObj = ldapService()
# Создаем переменные
self.logicObj.createClVars()
# Названия несовместимых опций
self.optionsNamesIncompatible = ["install", "uninstall", "f"]
def getIncompatibleOptions(self, optObj):
"""Получаем несовместимые опции"""
retList = []
for nameOpt in self.optionsNamesIncompatible:
retList.append(getattr(optObj, nameOpt))
return retList
def _getNamesAllSetOptions(self):
"""Выдает словарь измененных опций"""
setOptDict = self.optobj.values.__dict__.items()
defaultOptDict = self.optobj.get_default_values().__dict__.items()
return dict(set(setOptDict) - set(defaultOptDict)).keys()
def getStringIncompatibleOptions(self):
"""Форматированная строка несовместимых опций разделенных ','"""
listOpt = list(set(self.optionsNamesIncompatible) &\
set(self._getNamesAllSetOptions()))
return ", ".join(map(lambda x: len(x) == 1 and "'-%s'"%x or "'--%s'"%x,\
listOpt))
def checkOpts(self, optObj, args):
"""Check command line opt and arg"""
if len(filter(lambda x: x, self.getIncompatibleOptions(optObj)))>1:
errMsg = _("incompatible options")+":"+" %s"\
%self.getStringIncompatibleOptions()
self.optobj.error(errMsg)
return False
if args:
errMsg = _("incorrect argument") + ":" + " %s" %" ".join(args)
self.optobj.error(errMsg)
return False
return optObj, args
def setup(self, force=False):
"""Setup program"""
return self.logicObj.setup(force=force)
def install(self):
"""Инсталяция программы"""
return self.logicObj.installProg()
def uninstall(self):
"""Удаление программы"""
return self.logicObj.uninstallProg()

83
pym/cl_share_cmd.py

@ -1,83 +0,0 @@
#-*- coding: utf-8 -*-
# Copyright 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_print import color_print
from cl_utils import _error
# Перевод сообщений для программы
from cl_lang import lang
lang().setLanguage(sys.modules[__name__])
class share_cmd(color_print, _error):
"""Класс общих методов обработки опций командной строки"""
def printVars(self, optObj):
"""Печать переменных"""
if optObj.v:
varsFilter = None
varsNames = []
format = "default"
# Фильтрование переменных
if optObj.filter:
optCmd = optObj.filter
if ',' in optCmd:
varsNames = optCmd.split(",")
elif '*' in optCmd:
varsFilter = optCmd.replace("*", ".*")
else:
varsNames.append(optCmd)
if optObj.xml:
format = "xml"
try:
v = int(optObj.v)
except:
v = 1
self.logicObj.printVars(varsFilter, varsNames, outFormat=format,
verbose=v)
def setVars(self, optObj):
"""Установка переменных"""
if optObj.set:
for vals in optObj.set:
for val in vals.split(','):
k,o,v = val.partition('=')
if self.logicObj.clVars.exists(k):
if not self.logicObj.clVars.SetWriteVar(k,v):
return False
else:
self.printERROR(_('variable %s not found')%k)
return False
return True
def writeVars(self, optObj):
"""Запись переменных"""
if optObj.set:
if not self.logicObj.clVars.WriteVars():
errMsg = self.getError()
if errMsg:
self.printERROR(errMsg.strip())
self.printERROR(_('Can not write template variables'))
return False
return True
def setPrintNoColor(self, optObj):
"""Установка печати сообщений без цвета"""
if optObj.color and optObj.color=="never":
color_print.colorPrint = lambda *arg : sys.stdout.write(arg[-1]) or\
sys.stdout.flush()

108
pym/cl_vars_ldap.py

@ -1,108 +0,0 @@
#-*- coding: utf-8 -*-
# Copyright 2008-2010 Mir 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.
from cl_ldap_api import __version__, __app__
class Data:
#базовый суффикс LDAP
ld_base_dn = {}
#bind суффикс LDAP
ld_bind_dn = {}
#пользователь только для чтения
ld_bind_login = {}
#hash пароля для пользователя для чтения
ld_bind_hash = {}
#пароль для пользователя для чтения
ld_bind_pw = {}
#алгоритм шифрования паролей
ld_encrypt = {}
#имя для базового суффикса LDAP
ld_base_root = {}
#временный пользователь root для инициализации базы данных
ld_temp_dn = {}
#hash пароля временного root
ld_temp_hash = {}
#пароль временного пользователя root
ld_temp_pw = {}
#DN пользователя root
ld_admin_dn = {}
#имя пользователя root для LDAP
ld_admin_login = {}
#hash пароля root
ld_admin_hash = {}
#пароль root
ld_admin_pw = {}
#Имя для всех сервисов
ld_services= {}
#DN всех сервисов
ld_services_dn = {}
#Настроен или нет сервис LDAP
sr_ldap_set = {'mode':"w",'value':'off'}
# имя программы
cl_name = {'value':__app__}
# версия программы
cl_ver = {'value':__version__}
# действие программа устанавливает сервис
ac_ldap_setup = {'value':'down'}
# действие программа обновляет конфигурационные файлы
ac_ldap_update = {'value':'down'}
# include строки в slapd.conf
ld_ldap_scheme_conf = {'value':\
"include\t\t/etc/openldap/schema/core.schema\n"\
"include\t\t/etc/openldap/schema/cosine.schema\n"\
"include\t\t/etc/openldap/schema/nis.schema\n"\
"include\t\t/etc/openldap/schema/inetorgperson.schema\n"\
"include\t\t/etc/openldap/schema/misc.schema"}
# строки доступа к аттрибуту userPassword в slapd.conf
ld_ldap_access_pw_conf = {}
# строки доступа к LDAP DN сервиса в slapd.conf
ld_ldap_access_dn_conf = {}
ld_repl_set = {'value':'off'}
ld_repl_id = {}
ld_repl_servers_info = {}
ld_repl_servers_ref = {}
# lib vars
cl_pass_step = {}
cl_api = {}
cl_env_path = {}

0
pym/__init__.py → pym/ldap/__init__.py

33
pym/ldap/datavars.py

@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
# Copyright 2016 Mir Calculate. 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 calculate.lib.datavars import DataVars
from calculate.lib.utils.tools import AddonError
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_ldap3', sys.modules[__name__])
class DataVarsLdap(DataVars):
"""Variable class for desktop package"""
var_module = "ldap"
def importLdap(self, **args):
"""Import desktop variables"""
self.importVariables()
self.importVariables('calculate.%s.variables' % self.var_module)
self.defaultModule = self.var_module

40
pym/ldap/ldap.py

@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-
# Copyright 2016 Mir Calculate. 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 calculate.core.server.func import MethodsInterface
_ = lambda x: x
from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate)
setLocalTranslate('cl_ldap3', sys.modules[__name__])
__ = getLazyLocalTranslate(_)
class LdapError(Exception):
pass
class Ldap(MethodsInterface):
"""Основной объект для выполнения действий связанных
с настройкой LDAP сервиса
"""
class Method(object):
Setup = "ldap_setup"
All = (Setup,)
def init(self):
pass

0
pym/ldap/utils/__init__.py

47
pym/ldap/utils/cl_ldap_setup.py

@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
# Copyright 2016 Mir Calculate. 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 calculate.core.server.func import Action, Tasks
from calculate.lib.cl_lang import setLocalTranslate, getLazyLocalTranslate
from calculate.lib.cl_template import TemplatesError
from calculate.lib.utils.files import FilesError
from ..ldap import LdapError
_ = lambda x: x
setLocalTranslate('cl_ldap3', sys.modules[__name__])
__ = getLazyLocalTranslate(_)
class ClLdapSetupAction(Action):
"""
Действие обновление конфигурационных файлов
"""
# ошибки, которые отображаются без подробностей
native_error = (FilesError,
TemplatesError,
LdapError)
successMessage = __("SUCCESS")
failedMessage = __("FAILED")
interruptMessage = __("INTERRUPT")
# список задач для действия
tasks = [
{'name': 'test',
'message': 'test'
}
]

20
pym/ldap/variables/__init__.py

@ -0,0 +1,20 @@
#-*- coding: utf-8 -*-
# Copyright 2016 Mir Calculate. 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 action
import ldap
section = "ldap"

37
pym/ldap/variables/action.py

@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-
# Copyright 2016 Mir Calculate. 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 calculate.lib.datavars import ActionVariable
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_ldap3', sys.modules[__name__])
class Actions(object):
Setup = "ldap_setup"
class VariableAcLdapSetup(ActionVariable):
"""
Action variable which has value "on" for prepare squash
"""
def action(self, cl_action):
if cl_action == Actions.Setup:
return "on"
return "off"

20
pym/ldap/variables/ldap.py

@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Copyright 2016 Mir Calculate. 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 calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_ldap3', sys.modules[__name__])

74
pym/ldap/wsdl_ldap.py

@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
# Copyright 2016 Mir Calculate. 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 calculate.lib.datavars import VariableError, DataVarsError
from calculate.core.server.func import WsdlBase
from .ldap import Ldap, LdapError
from .variables.action import Actions as LdapActions
from utils.cl_ldap_setup import ClLdapSetupAction
_ = lambda x: x
from calculate.lib.cl_lang import setLocalTranslate, getLazyLocalTranslate
setLocalTranslate('cl_ldap3', sys.modules[__name__])
__ = getLazyLocalTranslate(_)
class Wsdl(WsdlBase):
methods = [
#
# Настроить службу
#
{
# идентификатор метода
'method_name': Ldap.Method.Setup,
# категория метода
'category': __('LDAP'),
# заголовок метода
'title': __("Setup"),
# иконка для графической консоли
'image': 'setup',
# метод присутствует в графической консоли
'gui': True,
# консольная команда
'command': 'cl-ldap-setup',
# права для запуска метода
'rights': ['ldap'],
# объект содержащий модули для действия
'logic': {'Ldap': Ldap},
# описание действия
'action': ClLdapSetupAction,
# объект переменных
'datavars': "ldap",
'native_error': (VariableError, DataVarsError, LdapError),
# значения по умолчанию для переменных этого метода
'setvars': {'cl_action!': LdapActions.Setup},
# описание груп (список лямбда функций)
'groups': [
lambda group: group(
_("Repository"),
brief=(),
hide=(),
normal=(),
expert=()),
],
'brief': {'next': __("Perform"),
'name': __("Setup LDAP"),}
},
]

65
scripts/cl-ldap-setup

@ -1,65 +0,0 @@
#!/usr/bin/python
#-*- coding: utf-8 -*-
# Copyright 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
import os
sys.path.insert(0,os.path.abspath('/usr/lib/calculate-2.2/calculate-lib/pym'))
sys.path.insert(0,\
os.path.abspath('/usr/lib/calculate-2.2/calculate-ldap/pym'))
from cl_ldap_setup_cmd import ldap_setup_cmd
from cl_lang import lang
tr = lang()
tr.setGlobalDomain('cl_ldap')
tr.setLanguage(sys.modules[__name__])
if __name__ == "__main__":
obj = ldap_setup_cmd()
ret = obj.optobj.parse_args()
if ret is False:
sys.exit(1)
opts, args = ret
# Установка цвета при печати сообщений
obj.setPrintNoColor(opts)
# Установка переменных
if not obj.setVars(opts):
sys.exit(1)
# Печать переменных
obj.printVars(opts)
# Если нет печати переменных выполняем логику программы
if not opts.v and not opts.filter and not opts.xml:
if not filter(lambda x: x[1], obj.optobj.values.__dict__.items()):
# Setup
if not obj.setup():
sys.exit(1)
elif opts.f:
# Force setup
if not obj.setup(force=True):
sys.exit(1)
elif opts.install:
# Install
if not obj.install():
sys.exit(1)
elif opts.uninstall:
# Uninstall
if not obj.uninstall():
sys.exit(1)
# Запись переменных
if not obj.writeVars(opts):
sys.exit(1)
sys.exit(0)

5
setup.cfg

@ -1,5 +0,0 @@
[install]
install-scripts=/usr/bin
install-purelib=/usr/lib/calculate-2.2
install-platlib=/usr/lib/calculate-2.2
install-data=/usr/lib/calculate-2.2/calculate-ldap

84
setup.py

@ -1,9 +1,10 @@
#!/usr/bin/env python
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# setup.py --- Setup script for calculate-ldap
#Copyright 2010 Calculate Pack, http://www.calculate-linux.org
# Copyright 2016 Mir Calculate. 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
@ -16,67 +17,28 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import stat
from distutils.core import setup
__version__ = "2.2.0.0"
__app__ = "calculate-ldap"
__version__ = "3.5.0_alpha1"
import os
from glob import glob
from distutils.core import setup
from distutils.command import install_data as module_install_data
from distutils.util import change_root, convert_path
data_files = []
data_dirs_ldif = ['ldif']
data_dirs_share = ['i18n']
share_calculate_dir = "/usr/share/calculate"
def __scanDir(scanDir, prefix, replace_dirname, dirData, flagDir=False):
"""Scan directory"""
files = []
dirs = []
if flagDir or stat.S_ISDIR(os.stat(scanDir)[stat.ST_MODE]):
for fileOrDir in os.listdir(scanDir):
absPath = os.path.join(scanDir,fileOrDir)
statInfo = os.stat(absPath)[stat.ST_MODE]
if stat.S_ISREG(statInfo):
files.append(absPath)
elif stat.S_ISDIR(statInfo):
dirs.append(absPath)
if replace_dirname:
listDirs = list(scanDir.partition("/"))[1:]
listDirs.insert(0,replace_dirname)
scanDir = "".join(listDirs)
if prefix:
scanDir = os.path.join(prefix,scanDir)
dirData.append((scanDir, files))
for sDir in dirs:
__scanDir(sDir, prefix, replace_dirname, dirData, True)
return dirData
def create_data_files(data_dirs, prefix="", replace_dirname=""):
"""Create data_files"""
data_files = []
for data_dir in data_dirs:
data = []
data_files += __scanDir(data_dir, prefix, replace_dirname, data)
return data_files
data_files += create_data_files (data_dirs_share, share_calculate_dir)
data_files += create_data_files (data_dirs_ldif)
packages = [
"calculate."+str('.'.join(root.split(os.sep)[1:]))
for root, dirs, files in os.walk('pym/ldap')
if '__init__.py' in files
]
setup(
name = __app__,
version = __version__,
description = "The program for configuring LDAP server",
author = "Mir Calculate Ltd.",
author_email = "support@calculate.ru",
url = "http://calculate-linux.org",
license = "http://www.apache.org/licenses/LICENSE-2.0",
package_dir = {'calculate-ldap': "."},
packages = ['calculate-ldap.pym'],
data_files = data_files,
scripts=["./scripts/cl-ldap-setup"]
)
name=__app__,
version=__version__,
description="LDAP service for Calculate utilities",
author="Calculate Ltd.",
author_email="support@calculate.ru",
url="http://calculate-linux.org",
license="http://www.apache.org/licenses/LICENSE-2.0",
package_dir = {'calculate.ldap': "pym/ldap"},
packages = packages)
Loading…
Cancel
Save