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-3-unix/pym/cl_ldap_api.py

185 rivejä
6.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 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_lang import lang
lang().setLanguage(sys.modules[__name__])
from cl_abstract import abs_api
class DataVarsLdap(DataVars):
"""Хранение переменных"""
# Имя секции в calculate2.env
envSection = "ldap"
def importLdap(self, **args):
'''Импорт переменных для calculate-ldap'''
# Импорт переменных
self.importData(self.envSection, ('cl_vars_ldap','cl_fill_ldap'))
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 True
class serviceAPI(color_print, shareVars, abs_api):
'''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 getServiceName(self):
'''Get name service'''
return self.nameService
def isSetup(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 isStart(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):
'''Запускает LDAP сервер'''
if execProg(self.cmdStart) is False:
self.printERROR(_("Can't execute '%s'") %self.cmdStart)
self.printNotOK(_("Starting LDAP") + " ...")
return False
else:
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
else:
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
def isRunlevel(self):
'''Находится ли LDAP в автозагрузке'''
daemons = self._getRunlevelDaemons()
if daemons is False:
return False
if self.nameDaemon in daemons:
return True
else:
return False
def addRunlevel(self):
'''Add daemon to runlevel'''
if not self.isRunlevel():
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 delRunlevel(self):
'''Delete daemon from runlevel'''
if self.isRunlevel():
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 getRunPrioritet(self):
'''Get run daemon prioritet'''
return self.prioritet
def delVarsFromEnv(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