Browse Source

Modified api methods.

tags/3.5.0_alpha1
Самоукин Алексей 10 years ago
parent
commit
994d290752
5 changed files with 196 additions and 63 deletions
  1. +26
    -0
      pym/cl_fill_ldap.py
  2. +93
    -36
      pym/cl_ldap_api.py
  3. +29
    -26
      pym/cl_ldap_service.py
  4. +19
    -0
      pym/cl_ldap_version.py
  5. +29
    -1
      pym/cl_vars_ldap.py

+ 26
- 0
pym/cl_fill_ldap.py View File

@@ -34,3 +34,29 @@ class fillVars(glob_attr):
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 ""

+ 93
- 36
pym/cl_ldap_api.py View File

@@ -18,22 +18,36 @@ 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_lang import lang
lang().setLanguage(sys.modules[__name__])

from cl_abstract import abs_api
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
@@ -49,9 +63,9 @@ class shareVars:
clVars.flIniFile()
# Устанавливаем у объекта атрибут объект переменных
self.clVars = clVars
return True
return self.clVars

class serviceAPI(color_print, shareVars, abs_api):
class serviceAPI(abs_api_service, shareVars, Template):
'''Methods ldap service'''
prioritet = 25
nameService = "ldap"
@@ -70,11 +84,20 @@ class serviceAPI(color_print, shareVars, abs_api):
cmdAddRunlevel = 'rc-update add %(name)s default' %_templDict
cmdDelRunlevel = 'rc-update del %(name)s default' %_templDict

def getServiceName(self):
def get_service_name(self):
'''Get name service'''
return self.nameService

def isSetup(self):
def get_pkg_name(self):
'''Get name service'''
from cl_ldap_service import __app__
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"
@@ -94,7 +117,7 @@ class serviceAPI(color_print, shareVars, abs_api):
daemons.append(daemon)
return daemons

def isStart(self):
def is_start(self):
'''Run ldap server (True/False)'''
if os.access(self.pidFile, os.R_OK):
pid = open(self.pidFile).read().strip()
@@ -105,33 +128,35 @@ class serviceAPI(color_print, shareVars, abs_api):
return False

def start(self):
'''Запускает LDAP сервер'''
if execProg(self.cmdStart) is False:
self.printERROR(_("Can't execute '%s'") %self.cmdStart)
self.printNotOK(_("Starting LDAP") + " ...")
return False
else:
return True
'''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):
'''Перезапускает LDAP сервер'''
if execProg(self.cmdReStart) is False:
self.printERROR(_("Can't execute '%s'") %self.cmdReStart)
self.printNotOK(_("Restarting LDAP")+ " ...")
return False
'''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 True
return self.start()
return True

def stop(self):
'''Останавливает LDAP сервер'''
if execProg(self.cmdStop) is False:
self.printERROR(_("Can't execute '%s'") %self.cmdStop)
self.printNotOK(_("Stopping LDAP")+ " ...")
return False
else:
return True
'''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 isRunlevel(self):
def is_runlevel(self):
'''Находится ли LDAP в автозагрузке'''
daemons = self._getRunlevelDaemons()
if daemons is False:
@@ -141,9 +166,9 @@ class serviceAPI(color_print, shareVars, abs_api):
else:
return False

def addRunlevel(self):
def add_runlevel(self):
'''Add daemon to runlevel'''
if not self.isRunlevel():
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")\
@@ -151,9 +176,9 @@ class serviceAPI(color_print, shareVars, abs_api):
return False
return True

def delRunlevel(self):
def del_runlevel(self):
'''Delete daemon from runlevel'''
if self.isRunlevel():
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")\
@@ -161,13 +186,12 @@ class serviceAPI(color_print, shareVars, abs_api):
return False
return True

def getRunPrioritet(self):
def get_prioritet(self):
'''Get run daemon prioritet'''
return self.prioritet

def delVarsFromEnv(self):
'''Delete template vars in env files
'''
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"))
@@ -182,3 +206,36 @@ class serviceAPI(color_print, shareVars, abs_api):
'file':fileName})
return False
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("cl_ldap_update_action","up", force=True)
return Template.applyTemplates(self)
return True

+ 29
- 26
pym/cl_ldap_service.py View File

@@ -14,42 +14,31 @@
# See the License for the specific language governing permissions and
# limitations under the License.

__version__ = "2.2.0.0"
__app__ = "calculate-ldap"
from cl_ldap_version import __version__, __app__

import os, sys

from server.utils import dialogYesNo
from cl_print import color_print

from cl_ldap_api import serviceAPI, shareVars
from cl_template import template
from server.services import services
from cl_ldap_api import serviceAPI, shareVars, 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, appendProgramToEnvFile,\
removeProgramToEnvFile

import cl_overriding
from cl_lang import lang
lang().setLanguage(sys.modules[__name__])

class ldapService(shareVars, shareldap):
class ldapService(shareVars, shareldap, Template):
"""Методы севис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'
APIObj = serviceAPI()
servObj = services()

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
libAPIObj = packagesAPI()

def removeLdapDatabase(self):
"""Удаляем предыдущую базу данных"""
@@ -59,12 +48,23 @@ class ldapService(shareVars, shareldap):
self.printERROR("Can't remove /var/lib/openldap-data/*")
return False
return True
# TEST
if os.path.exists(pathDatabase) and os.listdir(pathDatabase):
removeDir(pathDatabase)
self.printOK(_("Erased LDAP Database") + " ...")
return True

def getApiAttrLib(self, attr):
try:
value = eval('self.libAPIObj.%s'%attr)
except APIError, e:
self.printERROR(str(e))
cl_overriding.exit(1)
except Exception, e:
self.printERROR(str(e))
return False
return value

def connectLdapServer(self):
"""Соединяемся с LDAP сервером

@@ -151,24 +151,25 @@ class ldapService(shareVars, shareldap):
else:
# делаем backup
# Проверим запущен ли ldap
if not self.APIObj.isStart():
if not self.APIObj.is_start():
# Запускаем LDAP сервер
if not self.APIObj.start():
return False
#if not self.backupServer():
#return False
if self.APIObj.isRunlevel():
if self.APIObj.is_runlevel():
# Удаляем из автозапуска демона
if not self.APIObj.delRunlevel():
if not self.APIObj.del_runlevel():
return False
# Останавливаем все установленные сервисы
if not self.servObj.stopAllServices():
if not self.getApiAttrLib("all.stop"):
return False
# Останавливаем LDAP
if self.APIObj.isStart():
if self.APIObj.is_start():
self.APIObj.stop()
# Удаляем из автозагрузки все установленные сервисы
if not self.servObj.delRunlevelAllServices():
if not self.getApiAttrLib("all.del_runlevel"):
return False
# Удаляем из крона скрипт для чистки удаленых пользователей
# создаем объект репликации
@@ -179,7 +180,7 @@ class ldapService(shareVars, shareldap):
#if not self.servSambaObj.delReplFile(self.clVars):
#return False
# Удаляем переменные
if not self.servObj.delVarsFromAllServices():
if not self.getApiAttrLib("all.del_vars_from_env"):
return False
# Получим путь к ldap файлу
ldapParser = iniLdapParser()
@@ -228,7 +229,7 @@ class ldapService(shareVars, shareldap):
{"DN":self.clVars.Get("ld_admin_dn"),
"PASS":self.clVars.Get("ld_admin_pw")})
# Устанавливаем автозапуск демона
if not self.APIObj.addRunlevel():
if not self.APIObj.add_runlevel():
return False
# Записываем переменные для пользователя
#clientVars = ["ur_organization", "ur_signature"]
@@ -236,6 +237,8 @@ class ldapService(shareVars, shareldap):
#return False
self.clVars.Write("sr_ldap_set","on",force=True)
self.printOK(_("LDAP service configured") + " ...")
# test
print self.getApiAttrLib("calculate_ldap.apply_templates")
return True
def printVars(self, *arg, **argv):


+ 19
- 0
pym/cl_ldap_version.py View File

@@ -0,0 +1,19 @@
#-*- 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.

__version__ = "2.2.0.0"
__app__ = "calculate-ldap"

+ 29
- 1
pym/cl_vars_ldap.py View File

@@ -14,7 +14,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from cl_ldap_service import __version__, __app__
from cl_ldap_version import __version__, __app__

#__version__ = "2.2.0.0"
#__app__ = "calculate-ldap"

class Data:
#базовый суффикс LDAP
@@ -77,6 +80,31 @@ class Data:
# действие программа устанавливает сервис
cl_ldap_setup_action = {'value':'down'}

# действие программа обновляет конфигурационные файлы
cl_ldap_update_action = {'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 = {}


Loading…
Cancel
Save