#-*- 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_lang import lang lang().setLanguage(sys.modules[__name__]) 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 serviceAPI(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''' 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" 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 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