Browse Source

Added template functions clget() and clvar().

Fix config headed from not protected dirs.
develop
Самоукин Алексей 11 years ago
parent
commit
7080809f3a
  1. 15
      pym/cl_abstract.py
  2. 63
      pym/cl_template.py
  3. 97
      pym/server/services.py

15
pym/cl_abstract.py

@ -50,3 +50,18 @@ class abs_api:
def delVarsFromEnv(self):
'''Delete template vars in env files
'''
@abstractmethod
def getServiceInfo(self):
'''Get Service information
'''
@abstractmethod
def getVars(self):
'''Get Service vars
'''
@abstractmethod
def getPkgName(self):
'''Get package name
'''

63
pym/cl_template.py

@ -2271,6 +2271,9 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
def __init__(self, objVar):
# Если не определен словарь функций шаблона
# import services api
from server.services import services
self.services = services
if not self.templateFunction:
# префикс функций шаблона
pref = "func"
@ -3125,6 +3128,49 @@ os_disk_install not found mount point '\' and '\%s'")%mountPoint)
textTemplateTmp[resS.end():]
return textTemplateTmp
def funcClGet(self, funArgv, resS, localVars, textTemplateTmp):
"""Функция шаблона clget(), выдает данные пакета или всех пакетов.
первый аргумент:
'all' - все пакеты,
имя_пакета - данный пакет
второй аргумент:
строка запроса данных
"""
terms = funArgv.replace(" ","").split(",")
if not terms[0].strip() or\
(len(terms)==2 and not terms[1].strip()) or len(terms)!=2:
self.printErrTemplate()
cl_overriding.exit(1)
pkgName = terms[0]
request = terms[1]
servApiObj = self.services()
replace = servApiObj.clGet(pkgName, request)
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
textTemplateTmp[resS.end():]
return textTemplateTmp
def funcClVar(self, funArgv, resS, localVars, textTemplateTmp):
"""Функция шаблона clvar(), выдает значение переменной пакета.
первый аргумент:
имя_пакета - данный пакет
второй аргумент:
название переменной
"""
terms = funArgv.replace(" ","").split(",")
if not terms[0].strip() or\
(len(terms)==2 and not terms[1].strip()) or len(terms)!=2:
self.printErrTemplate()
cl_overriding.exit(1)
pkgName = terms[0]
varName = terms[1]
servApiObj = self.services()
replace = servApiObj.clGetVar(pkgName, varName)
textTemplateTmp = textTemplateTmp[:resS.start()] + replace +\
textTemplateTmp[resS.end():]
return textTemplateTmp
def printErrTemplate(self):
"""Печать ошибки при обработке функций шаблона"""
cl_overriding.printERROR(_("error in template %s")%self.nameTemplate)
@ -3219,6 +3265,11 @@ class template(_file,_terms,_warning,xmlShare,templateFormat,_shareTemplate):
# Название файла шаблона директории
templDirNameFile = ".calculate_directory"
titleEnd = "For modify this file, create %(conf_path)s.clt template."
protectPaths = []
if "CONFIG_PROTECT" in os.environ:
protectPaths = ["/etc"] + filter(lambda x: x.strip(),
os.environ["CONFIG_PROTECT"].split(" "))
protectPaths = map(lambda x: os.path.normpath(x), protectPaths)
def __init__(self, objVar, servDir=False, dirsFilter=[], filesFilter=[],
cltObj=True, cltFilter=True, printWarning=True):
@ -3450,9 +3501,15 @@ re.M|re.S)
def getTitle(self, comment, commentList, configPath=""):
"""Выдает заголовок шаблона ( версия и.т.д)"""
if configPath:
commentList = commentList +\
[self.titleEnd%{'conf_path':configPath}]
if configPath and self.protectPaths:
flagFoundPath = False
for protectPath in self.protectPaths:
if configPath.startswith(protectPath + "/"):
flagFoundPath = True
break
if flagFoundPath:
commentList = commentList +\
[self.titleEnd%{'conf_path':configPath}]
if comment:
commentFirst = comment
commentInsert = comment

97
pym/server/services.py

@ -19,6 +19,7 @@ import sys, os
from cl_print import color_print
from cl_datavars import DataVars
import cl_overriding
# translate language
import cl_lang
tr = cl_lang.lang()
@ -69,8 +70,35 @@ class services(color_print):
return False
return apiObjects
def runMethodToAllServices(self, methodName, sortedServices="normal"):
"""Stopped all setup services"""
def runMethodToPkg(self, pkgName, methodName, argv=[]):
"""Execute method from pkg"""
allServObjs = self.allServicesApi()
if allServObjs is False:
return False
allSetupServObjs = filter(lambda x:\
x.isSetup() and x.getPkgName()==pkgName,
allServObjs)
if not allSetupServObjs:
return False
pkgObj = allSetupServObjs[0]
if not hasattr(pkgObj, methodName):
self.printERROR(_("Can not found method %(method)s in \
API object service %(service)s") %{'method':methodName,
'service':pkgObj.getServiceName()})
cl_overriding.exit(1)
if argv:
res = getattr(pkgObj, methodName)(*argv)
else:
res = getattr(pkgObj, methodName)()
return res
def runMethodFromAllServices(self, methodName, sortedServices="normal",
argv=[], result='bool'):
"""Execute method from all setup services"""
if not result in ('bool', 'list'):
self.printERROR(_("Method: runMethodFromAllServices()"))
self.printERROR(_("Can't result argv in bool or list"))
cl_overriding.exit(1)
allServObjs = self.allServicesApi()
if allServObjs is False:
return False
@ -110,32 +138,75 @@ class services(color_print):
else:
smpPrioritet = smpPrioritetNormal
allSetupServObjs.sort(smpPrioritet)
if result=='list':
data = []
for service in allSetupServObjs:
if hasattr(service, methodName):
if not getattr(service, methodName)():
return False
else:
if not hasattr(service, methodName):
self.printERROR(_("Can not found method %(method)s in \
API object service %(service)s") %{'method':methodName,
'service':service.getServiceName()})
return False
return True
cl_overriding.exit(1)
if argv:
res = getattr(service, methodName)(*argv)
else:
res = getattr(service, methodName)()
if result=='bool':
if res is False:
return False
elif result=='list':
serviceName = service.getServiceName()
data.append((serviceName, res))
if result=='bool':
return True
elif result=='list':
return data
def stopAllServices(self):
"""Stop all services that were setup"""
return self.runMethodToAllServices("stop", sortedServices="reverse")
return self.runMethodFromAllServices("stop", sortedServices="reverse")
def startAllServices(self):
"""Start all services that were setup"""
return self.runMethodToAllServices("start")
return self.runMethodFromAllServices("start")
def delRunlevelAllServices(self):
"""Delete all services that were setup from runlevel"""
return self.runMethodToAllServices("delRunlevel",
return self.runMethodFromAllServices("delRunlevel",
sortedServices="reverse")
def delVarsFromAllServices(self):
"""Delete template vars from all services"""
return self.runMethodToAllServices("delVarsFromEnv",
return self.runMethodFromAllServices("delVarsFromEnv",
sortedServices="reverse")
def getInfoFromAllServices(self, request):
"""Get info from all services"""
return self.runMethodFromAllServices("getServiceInfo", argv=[request],
result='list')
def clGetVar(self, pkgName, varName):
"""Get variable value from pkg"""
clVars = self.runMethodToPkg(pkgName, 'getVars')
if clVars is False:
return ""
try:
value = clVars.Get(varName)
except:
self.printERROR(_("Can not found variable %(var)s "
"in package %(pkg)s") %{'var':varName,
'pkg':pkgName})
cl_overriding.exit(1)
return value
def clGet(self, pkgNameOrAll, request):
"""Get info from service or all services"""
res = ""
if pkgNameOrAll == "all":
listData = self.getInfoFromAllServices(request)
if not listData:
return res
res = "\n".join(map(lambda x: x[1], listData))
else:
res = self.runMethodToPkg(pkgNameOrAll, "getServiceInfo",
argv=[request])
if not res:
res = ""
return res
Loading…
Cancel
Save