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.

185 lines
6.6 KiB

  1. #-*- coding: utf-8 -*-
  2. # Copyright 2008-2010 Mir Calculate Ltd. http://www.calculate-linux.org
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os, sys, re
  16. from cl_print import color_print
  17. from cl_datavars import DataVars
  18. from server.utils import execProg
  19. from cl_lang import lang
  20. lang().setLanguage(sys.modules[__name__])
  21. from cl_abstract import abs_api
  22. class DataVarsLdap(DataVars):
  23. """Хранение переменных"""
  24. # Имя секции в calculate2.env
  25. envSection = "ldap"
  26. def importLdap(self, **args):
  27. '''Импорт переменных для calculate-ldap'''
  28. # Импорт переменных
  29. self.importData(self.envSection, ('cl_vars_ldap','cl_fill_ldap'))
  30. class shareVars:
  31. """share methods template vars"""
  32. # template variables
  33. clVars = False
  34. def createClVars(self, clVars=False):
  35. """Создает объект Vars"""
  36. if not clVars:
  37. clVars = DataVarsLdap()
  38. # Импортируем переменные
  39. clVars.importLdap()
  40. # Заменяем значения переменных переменными из env файлов
  41. clVars.flIniFile()
  42. # Устанавливаем у объекта атрибут объект переменных
  43. self.clVars = clVars
  44. return True
  45. class serviceAPI(color_print, shareVars, abs_api):
  46. '''Methods ldap service'''
  47. prioritet = 25
  48. nameService = "ldap"
  49. nameDaemon = 'slapd'
  50. _templDict = {'name':nameDaemon}
  51. # files
  52. pidFile = '/var/run/openldap/%(name)s.pid' %_templDict
  53. # command
  54. cmdPath = '/etc/init.d/%(name)s' %_templDict
  55. _templDict.update({'cmd':cmdPath})
  56. cmdStart = '%(cmd)s start' %_templDict
  57. cmdReStart = '%(cmd)s restart' %_templDict
  58. cmdStop = '%(cmd)s stop' %_templDict
  59. cmdShowDaemons = 'rc-update show default'
  60. reShowDaemons = re.compile("(.+)\s+\|\s+.+")
  61. cmdAddRunlevel = 'rc-update add %(name)s default' %_templDict
  62. cmdDelRunlevel = 'rc-update del %(name)s default' %_templDict
  63. def getServiceName(self):
  64. '''Get name service'''
  65. return self.nameService
  66. def isSetup(self):
  67. '''Is setup service (True/False)'''
  68. self.createClVars(self.clVars)
  69. return self.clVars.Get('sr_ldap_set') == "on"
  70. def _getRunlevelDaemons(self):
  71. """Получаем всех демонов в default уровне"""
  72. textLines = execProg(self.cmdShowDaemons)
  73. if textLines is False:
  74. self.printERROR(_("ERROR") + ": " + self.cmdShowDaemons)
  75. return False
  76. else:
  77. daemons = []
  78. for line in textLines:
  79. res = self.reShowDaemons.search(line)
  80. if res:
  81. daemon = res.groups(0)[0]
  82. daemons.append(daemon)
  83. return daemons
  84. def isStart(self):
  85. '''Run ldap server (True/False)'''
  86. if os.access(self.pidFile, os.R_OK):
  87. pid = open(self.pidFile).read().strip()
  88. if pid:
  89. procDir = "/proc"+"/"+pid
  90. if os.access(procDir, os.F_OK):
  91. return True
  92. return False
  93. def start(self):
  94. '''Запускает LDAP сервер'''
  95. if execProg(self.cmdStart) is False:
  96. self.printERROR(_("Can't execute '%s'") %self.cmdStart)
  97. self.printNotOK(_("Starting LDAP") + " ...")
  98. return False
  99. else:
  100. return True
  101. def restart(self):
  102. '''Перезапускает LDAP сервер'''
  103. if execProg(self.cmdReStart) is False:
  104. self.printERROR(_("Can't execute '%s'") %self.cmdReStart)
  105. self.printNotOK(_("Restarting LDAP")+ " ...")
  106. return False
  107. else:
  108. return True
  109. def stop(self):
  110. '''Останавливает LDAP сервер'''
  111. if execProg(self.cmdStop) is False:
  112. self.printERROR(_("Can't execute '%s'") %self.cmdStop)
  113. self.printNotOK(_("Stopping LDAP")+ " ...")
  114. return False
  115. else:
  116. return True
  117. def isRunlevel(self):
  118. '''Находится ли LDAP в автозагрузке'''
  119. daemons = self._getRunlevelDaemons()
  120. if daemons is False:
  121. return False
  122. if self.nameDaemon in daemons:
  123. return True
  124. else:
  125. return False
  126. def addRunlevel(self):
  127. '''Add daemon to runlevel'''
  128. if not self.isRunlevel():
  129. if execProg(self.cmdAddRunlevel) is False:
  130. self.printERROR(_("Can't execute '%s'") %self.cmdAddRunlevel)
  131. self.printNotOK(_("service %(name)s added to runlevel")\
  132. %self._templDict + " ...")
  133. return False
  134. return True
  135. def delRunlevel(self):
  136. '''Delete daemon from runlevel'''
  137. if self.isRunlevel():
  138. if execProg(self.cmdDelRunlevel) is False:
  139. self.printERROR(_("Can't execute '%s'") %self.cmdDelRunlevel)
  140. self.printNotOK(_("service %(name)s removed from runlevel")\
  141. %self._templDict + " ...")
  142. return False
  143. return True
  144. def getRunPrioritet(self):
  145. '''Get run daemon prioritet'''
  146. return self.prioritet
  147. def delVarsFromEnv(self):
  148. '''Delete template vars in env files
  149. '''
  150. self.createClVars(self.clVars)
  151. deleteVariables = ("sr_ldap_set",)
  152. locations = map(lambda x: x[0], self.clVars.Get("cl_env_data"))
  153. for varName in deleteVariables:
  154. for locate in locations:
  155. if not self.clVars.Delete(varName, location=locate,
  156. header=self.clVars.envSection):
  157. fileName = filter(lambda x: x[0] == locate,
  158. self.clVars.Get("cl_env_data"))[0][1]
  159. self.printERROR(_("Can't delete variable '%(name)s' "
  160. "in file %(file)s") %{'name':varName,
  161. 'file':fileName})
  162. return False
  163. return True