Merge branch 'master' of git.calculate.ru:/calculate-lib

develop
Самоукин Алексей 14 years ago
commit 133ba00dad

Binary file not shown.

@ -18,6 +18,7 @@ import os
import sys
from cl_utils import convertStrListDict, fillstr, getpathenv, runOsCommand,\
pathJoin
from cl_vars_share import varsShare as glob_attr
import re
from cl_lang import lang
from cl_template import iniParser
@ -750,90 +751,6 @@ storage of variables templates")%location)
self.SetList(nameVar, listValues, force, spl)
return True
class glob_attr:
"""Глобальные аттрибуты для методов заполнения переменных"""
def _runos(self, cmd, env={}):
"""Вернуть результат выполнения команды ОС"""
if not env:
env.update(os.environ.items() + [("PATH",getpathenv())] +\
env.items())
retCode, programOut = runOsCommand(cmd, None, env_dict=env)
if not retCode:
return programOut
return False
def get_composite_from_xorgconf(self,chroot="/"):
xorgConfig = os.path.join(chroot,
"etc/X11/xorg.conf")
try:
confLines = open(xorgConfig,"r").readlines()
except:
return None
flagStartExtensions = False
lineCompositeTmp = ""
lineComposite = ""
for line in confLines:
if flagStartExtensions:
if 'EndSection' in line:
lineComposite = lineCompositeTmp
break
elif 'Section' in line:
break
if 'Option' in line and '"Composite"' in line:
lineCompositeTmp = line
else:
if '"Extensions"' in line and 'Section' in line:
flagStartExtensions = True
if lineComposite:
listOpt = filter(lambda x: x.strip(), lineComposite.split('"'))
if len(listOpt) == 3:
ret = listOpt[2].lower()
if ret in ("on","true","yes","1"):
return "on"
elif ret in ("off","false","no","0"):
return "off"
return None
def getValueFromCmdLine(self,option,num):
"""Get value of parameter from boot params
Parameters:
option param name
num number part of value parameter (, split)
"""
cmdLine = "/proc/cmdline"
calculateParam = "calculate"
# try get timezone from kernel calculate param
try:
for param in open(cmdLine,"r").read().split(" "):
parname,op,value = param.partition("=")
if parname == calculateParam and op == "=":
values = value.split(",")
if len(values) > num and values[num].strip():
return values[num].strip()
except IOError,e:
return ""
def getValueFromConfig(self,config,name):
"""Get value of parameter from bash type file
Parameters:
config config file name
name param name
"""
reMatch = re.compile("^%s\s*=\s*\"?(.*?)\"?$"%name, re.I)
try:
if os.path.exists(config):
for line in open(config,"r").readlines():
match = reMatch.match(line)
if match:
return match.groups()[0].strip()
except:
pass
return False
class _varsXML:
declaration = '<?xml version="1.0" encoding="UTF-8"?>\n'
rootElementStart = '<variables>\n'
@ -894,4 +811,4 @@ class _varsXML:
"rootStart":self.rootElementStart,
"vars":self.varsXML,
"rootEnd":self.rootElementEnd}
return self.templateDoc %dictXML
return self.templateDoc %dictXML

@ -17,229 +17,21 @@
import re
import os
import types
import filecmp
import pwd, grp
import cl_overriding
from cl_ldap import ldapUser
from cl_datavars import glob_attr
from cl_vars_share import varsShare, clLocale
from os.path import exists as pathexists
from os import path
from cl_utils import isMount
class clLocale:
lang = {
#Belarussian
'be_BY' : {
'locale':'be_BY.UTF-8',
'keymap':'by',
'dumpkeys_charset': 'koi8-u',
'consolefont':'Cyr_a8x16',
'xkblayout':'us,by',
'language':'be',
},
#Bulgarian
'bg_BG' : {
'locale':'bg_BG.UTF-8',
'keymap':'bg_bds-utf8',
'dumpkeys_charset': '',
'consolefont':'ter-m14n',
'xkblayout':'us,bg',
'language':'bg',
},
#Belgian
'fr_BE' : {
'locale':'fr_BE.UTF-8',
'keymap':'be-latin1',
'dumpkeys_charset':'',
'consolefont':'lat9w-16',
'xkblayout':'us,be',
'language':'fr',
},
#Brazilian Portuguese
'pt_BR' : {
'locale':'pt_BR.UTF-8',
'keymap':'br-abnt2',
'dumpkeys_charset':'',
'consolefont':'lat9w-16',
'xkblayout':'pt,us',
'language':'pt',
},
#Canadian French
'fr_CA' : {
'locale':'fr_CA.UTF-8',
'keymap':'cf',
'dumpkeys_charset':'',
'consolefont':'default8x16',
'xkblayout':'us,ca_enhanced',
'language':'fr',
},
#Danish
'da_DK' : {
'locale':'da_DK.UTF-8',
'keymap':'dk-latin1',
'dumpkeys_charset':'',
'consolefont':'lat0-16',
'xkblayout':'us,dk',
'language':'da',
},
#French
'fr_FR' : {
'locale':'fr_FR.UTF-8',
'keymap':'fr-latin9',
'dumpkeys_charset':'',
'consolefont':'lat0-16',
'xkblayout':'fr,us',
'language':'fr',
},
#German
'de_DE' : {
'locale':'de_DE.UTF-8',
'keymap':'de-latin1',
'dumpkeys_charset':'',
'consolefont':'lat9w-16',
'xkblayout':'de,us',
'language':'de',
},
#Icelandic
'is_IS' : {
'locale':'is_IS.UTF-8',
'keymap':'is-latin1',
'dumpkeys_charset':'',
'consolefont':'cp850-8x16',
'xkblayout':'us,is',
'language':'is',
},
#Italian
'it_IT' : {
'locale':'it_IT.UTF-8',
'keymap':'it',
'dumpkeys_charset':'',
'consolefont':'default8x16',
'xkblayout':'us,it',
'language':'it',
},
#Norwegian
'nn_NO' : {
'locale':'nn_NO.UTF-8',
'keymap':'no-latin1',
'dumpkeys_charset':'',
'consolefont':'lat9w-16',
'xkblayout':'us,no',
'language':'nn',
},
#Polish
'pl_PL' : {
'locale':'pl_PL.UTF-8',
'keymap':'pl',
'dumpkeys_charset':'',
'consolefont':'lat2-16',
'xkblayout':'us,pl',
'language':'pl',
},
#Russian
'ru_RU' : {
'locale':'ru_RU.UTF-8',
'keymap':'-u ruwin_cplk-UTF-8',
'dumpkeys_charset':'',
'consolefont':'ter-k14n',
'xkblayout':'us,ru(winkeys)',
'language':'ru',
},
#Spanish
'es_ES' : {
'locale':'es_ES.UTF-8',
'keymap':'es euro2',
'dumpkeys_charset':'',
'consolefont':'lat0-16',
'xkblayout':'es,us',
'language':'es',
},
#Swedish
'sv_SE' : {
'locale':'sv_SE.UTF-8',
'keymap':'sv-latin1',
'dumpkeys_charset':'',
'consolefont':'lat0-16',
'xkblayout':'us,se',
'language':'sv',
},
#Ukrainian
'uk_UA' : {
'locale':'uk_UA.UTF-8',
'keymap':'ua-utf',
'dumpkeys_charset':'koi8-u',
'consolefont':'ter-v14n',
'xkblayout':'us,ua(winkeys)',
'language':'uk',
},
#United Kingdom/British
'en_GB' : {
'locale':'en_GB.UTF-8',
'keymap':'uk',
'dumpkeys_charset':'',
'consolefont':'LatArCyrHeb-16',
'xkblayout':'us,gb',
'language':'en',
},
#United State/English
'en_US' : {
'locale':'en_US.UTF-8',
'keymap':'us',
'dumpkeys_charset':'',
'consolefont':'LatArCyrHeb-16',
'xkblayout':'us',
'language':'en',
}
}
def getLangs(self):
return self.lang.keys()
def getLanguages(self):
return map(lambda x:self.lang[x]['language'],
self.lang.keys())
def isLangExists(self,lang):
return lang in self.lang.keys()
def isValueInFieldExists(self,field,value):
return value in map(lambda x:self.lang[x][field],self.lang.keys())
def getFields(self,field):
return [ l[1][field] for l in self.lang.items() ]
def getFieldByLang(self,field,lang):
return self.lang.get(lang, self.lang['en_US'])[field]
def getFieldByKeymap(self,field,keymap):
return self.lang.get(self.getLangByField('keymap',keymap),
self.lang['en_US'])[field]
def getLangByField(self,field,value):
langs = [lang[0] for lang in self.lang.items()
if lang[1][field] == value ]
if not langs:
return 'en_US'
else:
return langs[0]
def getDirList(path):
#Получить список директорий по указаному пути
dirs = []
if os.path.exists(path):
dirs = filter(lambda x: os.path.isdir(os.path.join(path,x)),
os.listdir(path))
return dirs
class fillVars(glob_attr):
# Объект данных из LDAP
_ldapUserObject = False
# Данные о пользователе из LDAP
_ldapUserData = {}
class fillVars(varsShare):
"""Auxilary object for creating variables
Contains filling methods"""
def get_cl_env_path(self):
'''Пути к env файлам'''
"""Path to env files"""
envData = self.Get("cl_env_data")
if envData:
return map(lambda x: x[1], envData)
@ -249,7 +41,7 @@ class fillVars(glob_attr):
cl_overriding.exit(1)
def get_cl_env_location(self):
'''Алиасы к env файлам'''
"""Aliases to env files"""
envData = self.Get("cl_env_data")
if envData:
return map(lambda x: x[0], envData)
@ -259,21 +51,21 @@ class fillVars(glob_attr):
cl_overriding.exit(1)
def get_cl_template_clt_path(self):
'''Пути к файлам ,clt'''
"""Path to 'clt' files"""
if "CONFIG_PROTECT" in os.environ:
protectPaths = ["/etc"] + filter(lambda x: x.strip(),
os.environ["CONFIG_PROTECT"].split(" "))
else:
protectPaths = ["/etc", "/usr/share/X11/xkb", "var/lib/hsqldb",
"/usr/share/config"]
return filter(os.path.exists, protectPaths)
return filter(path.exists, protectPaths)
def get_os_net_domain(self):
'''Определим домен'''
"""Get net domain name"""
textLines = self._runos("hostname -d 2>&1")
if textLines is False:
cl_overriding.printERROR(_("Error execute 'hostname -d'"))
cl_overriding.exit(1)
return cl_overriding.exit(1)
domain = ""
if textLines:
domain = textLines[0]
@ -282,134 +74,40 @@ class fillVars(glob_attr):
_("Not found domain name"))
cl_overriding.printERROR(\
_("Command 'hostname -d' returns an empty value"))
cl_overriding.exit(1)
return cl_overriding.exit(1)
elif re.search("^hostname: ",domain):
return "local"
else:
return domain
dictLinuxName = {"CLD":"Calculate Linux Desktop",
"CLDX":"Calculate Linux Desktop",
"CLDG":"Calculate Linux Desktop",
"CDS":"Calculate Directory Server",
"CLS":"Calculate Linx Scratch",
"CSS":"Calculate Scratch Server",
"Gentoo":"Gentoo"}
def get_os_linux_shortname(self):
'''Получить переменную короткого названия системы'''
makeprofile = '/etc/make.profile'
if os.path.exists(makeprofile):
link = os.readlink(makeprofile)
reMakeProfileLink = re.compile('/calculate/(desktop|server)/(%s)/'%
"|".join(self.dictLinuxName.keys()),re.S)
shortnameSearch = reMakeProfileLink.search(link)
if shortnameSearch:
return shortnameSearch.groups()[1]
path = '/etc/calculate/calculate.ini'
if os.path.exists(path):
FD = open(path)
data = FD.readlines()
FD.close()
shortNameList = filter(lambda y:y,
map(lambda x:\
len(x.split("="))==2 and\
x.split("=")[0]=="calculate" and\
x.split("=")[1].strip(), data))
if shortNameList:
return shortNameList[0]
gentooFile = "/etc/gentoo-release"
shortName = "Linux"
if os.path.exists(gentooFile):
shortName = "Gentoo"
return shortName
"""Get short system name"""
systemRoot = "/"
return self.getShortnameByMakeprofile(systemRoot) or \
self.getShortnameByIni(systemRoot) or \
self.detectOtherShortname(systemRoot) or \
"Linux"
def get_os_linux_name(self):
"""полное название системы"""
"""Get full system name"""
linuxShortName = self.Get("os_linux_shortname")
if linuxShortName:
if linuxShortName in self.dictLinuxName.keys():
return self.dictLinuxName[linuxShortName]
else:
return "Linux"
else:
return "Linux"
return self.dictLinuxName.get(linuxShortName,"Linux")
def get_os_linux_subname(self):
"""постфикс к названию системы"""
"""Get posfix name of system"""
linuxShortName = self.Get("os_linux_shortname")
if linuxShortName:
dictLinuxSubName = {"CLD":"KDE", "CLDX":"XFCE", "CLDG":"GNOME"}
if linuxShortName in dictLinuxSubName.keys():
return dictLinuxSubName[linuxShortName]
else:
return ""
else:
return ""
return self.dictLinuxSubName.get(linuxShortName,"")
def get_os_linux_ver(self):
'''Get system version'''
def get_from_metapackage():
"""Get version from meta package"""
shortname = self.Get('os_linux_shortname')
metaPkgs = filter(lambda x:"%s-meta"%shortname.lower() in x,
os.listdir('/var/db/pkg/app-misc/'))
if metaPkgs:
reFindVer = re.compile("(?<=\-)\d+\.?\d*\.?\d*")
findVer = reFindVer.search(metaPkgs[0])
if findVer:
return findVer.group()
return None
def get_from_calculate_ini():
"""Get version from calculate ini"""
path = '/etc/calculate/calculate.ini'
if os.path.exists(path):
FD = open(path)
data = FD.readlines()
FD.close()
verList = filter(lambda y:y,
map(lambda x:\
len(x.split("="))==2 and\
x.split("=")[0]=="linuxver" and\
x.split("=")[1].strip(), data))
if verList:
reVer=re.compile("^(\d+\.)*\d$",re.S)
reRes = filter(reVer.search,verList)
if reRes:
return reRes[0]
def get_from_gentoo_files():
"""Get version from gentoo files"""
gentooFile = "/etc/gentoo-release"
systemVersion = ""
flagGentoo = False
reVer=re.compile("^(\d+\.)*\d$",re.S)
if os.path.exists(gentooFile):
gentooLink = "/etc/make.profile"
if os.path.islink(gentooLink):
vers = filter(reVer.search,
os.readlink(gentooLink).split('/'))
if vers:
return vers[-1]
def get_from_uname():
"""Get version from uname"""
textLines = self._runos("uname -r")
reVer=re.compile("^(\d+\.)*\d",re.S)
kernelVersion = ""
if textLines:
kernelVersion = textLines[0]
if kernelVersion:
reRes = reVer.search(kernelVersion)
if reRes:
return reRes.group()
return get_from_metapackage() or get_from_calculate_ini() or \
get_from_gentoo_files() or get_from_uname() or "0"
"""Get system version"""
linuxShortName = self.Get("os_linux_shortname")
return self.getVersionFromMetapackage('/',linuxShortName) or \
self.getVersionFromCalculateIni('/') or \
self.getVersionFromGentooFiles('/') or \
self.getVersionFromUname() or "0"
def get_os_net_hostname(self):
'''Считать имя компьютера net_host'''
"""Get hostname of computer"""
textLines = self._runos("hostname -s 2>&1")
hostname = ""
if textLines:
@ -428,9 +126,8 @@ class fillVars(glob_attr):
return self.Get('os_linux_shortname')
return hostname
# все ip
def get_os_net_ip(self):
"""все ip компьютера, разделитель запятая"""
"""All computer ip addresses, comma delimeter"""
IPs = []
netInterfaces=self.Get("os_net_interfaces")
for i in netInterfaces:
@ -446,15 +143,14 @@ class fillVars(glob_attr):
return ",".join(IPs)
def get_os_net_interfaces(self):
"""Существующие сетевые интерфейсы"""
return filter(lambda x: x!="lo", getDirList("/sys/class/net"))
"""All net interfaces"""
return filter(lambda x: x!="lo", self.getDirList("/sys/class/net"))
# Разрешенные сети (в данном случае все сети)
def get_os_net_allow(self):
"""Разрешенные сети разделитель запятая"""
"""Allowed networks"""
def getNet(ip, mask):
"""По ip и маске получаем сеть"""
"""By ip and mask get network"""
octetsMult = (0x1, 0x100, 0x10000, 0x1000000)
octetsIp = map(lambda x: int(x), ip.split("."))
octetsMask = map(lambda x: int(x), mask.split("."))
@ -488,7 +184,7 @@ class fillVars(glob_attr):
return ",".join(networks)
def get_os_arch_machine(self):
"""архитектура процессора"""
"""Processor architecture"""
textLines = self._runos("uname -m")
if not textLines:
return ""
@ -496,7 +192,7 @@ class fillVars(glob_attr):
return march
def get_os_root_dev(self):
"""корневой раздел файловой системы"""
"""Root filesystem device"""
for record in open('/proc/cmdline','rb').readlines():
re_res=re.search('(?:^|\s)root=(\S+)(\s|$)',record.strip())
if re_res:
@ -507,11 +203,11 @@ class fillVars(glob_attr):
# check root set by uuid
uuidpath = '/dev/disk/by-uuid'
if os.access(uuidpath,os.R_OK):
uuidDevs = filter(os.path.islink,
map(lambda x: os.path.join(uuidpath,x),
uuidDevs = filter(path.islink,
map(lambda x: path.join(uuidpath,x),
os.listdir(uuidpath)))
mapUuidDev = dict(map(lambda x:(os.path.basename(x),
os.path.normpath(os.path.join(uuidpath,
mapUuidDev = dict(map(lambda x:(path.basename(x),
path.normpath(path.join(uuidpath,
os.readlink(x)))), uuidDevs))
if re.match("^UUID=.*$",rootparam):
uuid = rootparam[5:]
@ -527,7 +223,7 @@ class fillVars(glob_attr):
return ""
def get_os_root_type(self):
"""тип носителя (ram, hdd, livecd)"""
"""Root device type (ram, hdd, livecd)"""
mountLunes = self._runos("mount")
if not mountLunes:
return ""
@ -543,7 +239,7 @@ class fillVars(glob_attr):
flagCD = True
break
if rootType == "ram":
if os.path.exists("/mnt/livecd") or flagCD:
if path.exists("/mnt/livecd") or flagCD:
rootType = "livecd"
return rootType
rootDev = self.Get("os_root_dev")
@ -551,13 +247,17 @@ class fillVars(glob_attr):
slpRootDev = rootDev.split("/dev/")
if len(slpRootDev) == 2:
rDev = slpRootDev[1]
devLines = os.listdir("/dev/disk/by-id")
for name in devLines:
path = os.path.join("/dev/disk/by-id", name)
if os.path.islink(path):
if rDev in os.readlink(path) and "usb-" in name:
rootType = "usb-hdd"
break
if os.path.exists('/dev/disk/by-id'):
devLines = os.listdir("/dev/disk/by-id")
for name in devLines:
pathname = path.join("/dev/disk/by-id", name)
if path.islink(pathname):
if rDev in os.readlink(pathname) and \
"usb-" in name:
rootType = "usb-hdd"
break
else:
devLines = None
if not devLines:
return ""
if rootType == "ram":
@ -567,7 +267,7 @@ class fillVars(glob_attr):
return ""
def get_hr_virtual(self):
"""Название виртуальной машины (virtualbox, vmware, qemu)"""
"""Virtual machine name (virtualbox, vmware, qemu)"""
pciLines = self._runos("/usr/sbin/lspci")
if not pciLines:
return False
@ -582,7 +282,7 @@ class fillVars(glob_attr):
return virtName
def get_hr_board_model(self):
"""motherboard model"""
"""Get motherboard model"""
modelFile = "/sys/class/dmi/id/board_name"
try:
return open(modelFile,"r").read().strip()
@ -590,7 +290,7 @@ class fillVars(glob_attr):
return ""
def get_hr_board_vendor(self):
"""motherboard vendor"""
"""Get motherboard vendor"""
vendorFile = "/sys/class/dmi/id/board_vendor"
try:
return open(vendorFile,"r").read().strip()
@ -598,7 +298,7 @@ class fillVars(glob_attr):
return ""
def get_hr_cpu_num(self):
"""processors count"""
"""Get processors count"""
cpuinfoFile = "/proc/cpuinfo"
try:
return len(["" for line in open(cpuinfoFile,"r").readlines()
@ -645,7 +345,7 @@ class fillVars(glob_attr):
return ""
def get_ur_login(self):
"""Имя пользователя"""
"""User login"""
uid = os.getuid()
try:
userName = pwd.getpwuid(uid).pw_name
@ -654,7 +354,7 @@ class fillVars(glob_attr):
return userName
def get_ur_group(self):
"""Название группы пользователя"""
"""User group"""
userName = self.Get('ur_login')
groupName = ""
if userName:
@ -666,7 +366,7 @@ class fillVars(glob_attr):
return groupName
def get_ur_fullname(self):
"""Полное имя пользователя"""
"""Full user name"""
userName = self.Get('ur_login')
fullName = ""
if userName:
@ -676,28 +376,8 @@ class fillVars(glob_attr):
return ""
return fullName
def getLdapUserObject(self):
"""Объект данных из LDAP"""
if not self._ldapUserObject:
self._ldapUserObject = ldapUser()
return self._ldapUserObject
def getUserInfo(self):
"""Получение информации о пользователе из LDAP"""
userName = self.Get('ur_login')
if userName:
if userName in self._ldapUserData:
return self._ldapUserData[userName]
else:
ldapObj = self.getLdapUserObject()
userInfo = ldapObj.getUserLdapInfo(userName)
if userInfo:
self._ldapUserData[userName] = userInfo
return userInfo
return {}
def get_ur_jid(self):
"""Jabber id пользователя"""
"""Get user Jabber id"""
userInfo = self.getUserInfo()
userJID = ""
if userInfo:
@ -705,7 +385,7 @@ class fillVars(glob_attr):
return userJID
def get_ur_mail(self):
"""Почтовый адрес пользователя"""
"""Get user email"""
userInfo = self.getUserInfo()
userMail = ""
if userInfo:
@ -713,7 +393,7 @@ class fillVars(glob_attr):
return userMail
def get_ur_home_path(self):
"""Домашняя директория пользователя"""
"""Get user home directory"""
userName = self.Get('ur_login')
homeDir = ""
if userName:
@ -725,18 +405,8 @@ class fillVars(glob_attr):
def get_os_linux_system(self):
"""Get linux system (server or desktop)"""
mapNameSystem = {'CDS':'server',
'CLD':'desktop',
'CLDG':'desktop',
'CLDX':'desktop',
'CLS':'desktop',
'CSS':'server'
}
shortName = self.Get('os_linux_shortname')
if shortName in mapNameSystem:
return mapNameSystem[shortName]
else:
return ""
return self.dictNameSystem.get(shortName,"")
def get_os_x11_video_drv(self):
"""Get video driver used by xorg"""
@ -744,7 +414,7 @@ class fillVars(glob_attr):
xorg_conf = '/etc/X11/xorg.conf'
# Try analize Xorg.{DISPLAY}.log
display = os.environ.get('DISPLAY')
if pathexists(xorg_modules_dir):
if path.exists(xorg_modules_dir):
list_avialable_drivers = \
map(lambda x: x[:-7],
filter(lambda x: x.endswith('_drv.so'),
@ -758,7 +428,7 @@ class fillVars(glob_attr):
if display_number:
xorg_log_file = '/var/log/Xorg.%s.log' % \
display_number.group(1)
if os.path.exists(xorg_log_file):
if path.exists(xorg_log_file):
matchStrs = [i for i in open(xorg_log_file)
if "drv" in i and reDriver.search(i)]
if matchStrs:
@ -768,7 +438,7 @@ class fillVars(glob_attr):
return resDriver.group(1)
# analize /etc/X11/xorg.conf
if os.path.exists(xorg_conf):
if path.exists(xorg_conf):
matchSect = re.search(r'Section "Device".*?EndSection',
open('/etc/X11/xorg.conf').read(),re.S)
if matchSect:
@ -790,24 +460,8 @@ class fillVars(glob_attr):
else:
return "vesa"
def getX11Resolution(self):
"""возвращает текущее разрешение экрана (ширина, высота), X запущен"""
lines=self._runos("xdpyinfo")
if not lines:
return ""
reRes = re.compile("dimensions:\s+(\d+)x(\d+)\s+pixels")
searchRes=False
for line in lines:
searchRes = reRes.search(line)
if searchRes:
break
if searchRes:
return (searchRes.group(1), searchRes.group(2))
else:
return ""
def get_os_x11_height(self):
"""Получить высоту экрана в пикселах"""
"""Get screen height in pixeles"""
resolution = self.getX11Resolution()
if resolution:
self.Set('os_x11_width',resolution[0])
@ -815,7 +469,7 @@ class fillVars(glob_attr):
return "768"
def get_os_x11_width(self):
"""Получить ширину экрана в пикселах"""
"""Get screen width in pixeles"""
resolution = self.getX11Resolution()
if resolution:
self.Set('os_x11_height',resolution[1])
@ -880,12 +534,12 @@ class fillVars(glob_attr):
return "%sx%s"%(stWidth,stHeight)
def get_os_x11_composite(self):
"""Включен ли композитный режим видеокарты on/off"""
"""On or off composite mode"""
state = self.get_composite_from_xorgconf()
return state or "off"
def get_hr_laptop(self):
"""Vendor of laptop"""
"""Laptop vendor"""
chassisType = '/sys/class/dmi/id/chassis_type'
boardVendor = '/sys/class/dmi/id/board_vendor'
if os.access(chassisType,os.R_OK) and \
@ -899,7 +553,7 @@ class fillVars(glob_attr):
return ""
def get_hr_video(self):
"""Производитель видеокарты"""
"""Videocard vendor"""
lines=self._runos("lspci")
if not lines:
return ""
@ -925,16 +579,24 @@ class fillVars(glob_attr):
return "vesa"
def get_cl_kernel_uid(self):
"""Get UID of symlink kernel, initramfs and System.map"""
uuidpath = '/dev/disk/by-uuid'
if not os.access(uuidpath,os.R_OK):
return ""
uuidDevs = filter(os.path.islink,map(lambda x: os.path.join(uuidpath,x),
uuidDevs = filter(path.islink,map(lambda x: path.join(uuidpath,x),
os.listdir(uuidpath)))
mapDevUuid = dict(map(lambda x:(os.path.normpath(os.path.join(uuidpath,
mapDevUuid = dict(map(lambda x:(path.normpath(path.join(uuidpath,
os.readlink(x))),
os.path.basename(x)),
path.basename(x)),
uuidDevs))
if self.Get('os_root_dev') in mapDevUuid:
return mapDevUuid[self.Get('os_root_dev')][:8]
else:
return ""
def get_os_scratch(self):
"""Current system is scratch"""
if self.Get('os_root_type') == 'livecd':
return "on" if isMount('/mnt/scratch/workspace') else "off"
else:
return "on" if isMount('/mnt/scratch') else "off"

@ -14,11 +14,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import optparse
import sys
import re
import textwrap
import optparse
from cl_utils import _toUNICODE
from cl_lang import lang
tr = lang()
tr.setLocalDomain('cl_lib')
@ -83,6 +84,55 @@ def make_option(shortOption=None,longOption=None,
class ShareHelpFormatter:
"""Общие методы форматирования help-а"""
def format_option(self, option):
# The help for each option consists of two parts:
# * the opt strings and metavars
# eg. ("-x", or "-fFILENAME, --file=FILENAME")
# * the user-supplied help string
# eg. ("turn on expert mode", "read data from FILENAME")
#
# If possible, we write both of these on the same line:
# -x turn on expert mode
#
# But if the opt string list is too long, we put the help
# string on a second line, indented to the same column it would
# start in if it fit on the first line.
# -fFILENAME, --file=FILENAME
# read data from FILENAME
result = []
opts = self.option_strings[option]
opt_width = self.help_position - self.current_indent - 2
if len(opts) > opt_width:
opts = "%*s%s\n" % (self.current_indent, "", opts)
indent_first = self.help_position
else: # start help on same line as opts
opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
indent_first = 0
result.append(opts)
if option.help:
help_text = self.expand_default(option)
help_lines = map(lambda x : x.encode('UTF-8'),
textwrap.wrap(_toUNICODE(help_text),
self.help_width))
result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
result.extend(["%*s%s\n" % (self.help_position, "", line)
for line in help_lines[1:]])
elif opts[-1] != "\n":
result.append("\n")
return "".join(result)
def _format_text(self, text):
"""
Format a paragraph of free-form text for inclusion in the
help output at the current indentation level.
"""
text_width = self.width - self.current_indent
indent = " "*self.current_indent
return textwrap.fill(_toUNICODE(text),
text_width,
initial_indent=indent,
subsequent_indent=indent).encode('UTF-8')
def format_description(self, description):
if description:
@ -224,11 +274,11 @@ class opt(optparse.OptionParser):
{'longOption':"filter",
'optVal':"FILTER",
'help':_("filtered variables (as a regular expression is used *), \
is used in conjunction with the options '-v - vars'")
is used in conjunction with the options '-v --vars'")
},
{'longOption':"xml",
'help':_("output variables in the form of XML, \
is used in conjunction with the option '-v - vars'")
'help':_("output variables in the format of XML, \
is used in conjunction with the option '-v --vars'")
}]
color_control = \

@ -25,6 +25,7 @@ import types
import random
import string
import time
import glob
# Переопределение exit
@ -100,13 +101,13 @@ class _terms(_error, _shareTermsFunction):
(объект для работы с переменными)
function - функция для для обработки функций в заголовке блока
"""
trm = {"&&":" and ","||":" or "}
trm = {"&&":"@@and@@","||":"@@or@@"}
rule = ["==", "!=", ">=", "<=", ">", "<"]
listEqual = []
for k in trm.keys():
if k in term:
term = term.replace(k,trm[k])
trs = term.split(" ")
trs = term.split("@@")
listSplitOr = []
if "or" in trs:
lst = []
@ -302,7 +303,7 @@ class fileHeader(_terms):
typeAppend = ""
# Возможные типы вставки шаблонов
_fileAppend = "join", "before", "after", "replace", "remove", "skip",\
"patch"
"patch", "clear"
# Интерпретатор (#!/bin/bash) (#!/usr/bin/python)
execStr = ""
# Символ комментария
@ -474,7 +475,7 @@ class dirHeader(_terms):
typeAppend = ""
# Возможные типы вставки шаблонов
_fileAppend = "join", "remove", "skip"
_fileAppend = "join", "remove", "skip", "clear"
# условные операторы
terms = ('>', '<', '==', '!=', '>=', '<=')
@ -2268,7 +2269,6 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
# Текст функции шаблона
functText = ""
def __init__(self, objVar):
# Если не определен словарь функций шаблона
if not self.templateFunction:
@ -2293,8 +2293,10 @@ class templateFunction(_error, _shareTemplate, _shareTermsFunction):
if self._chrootDir != '/':
# Изменение директории к базе пакетов
self.basePkgDir = pathJoin(self._chrootDir, self.basePkgDir)
self.basePkgDir = os.path.normpath(self.basePkgDir)
# Базовая директория переноса шаблонов "/mnt/calculate" или "/" и.т.д
self._baseDir=pathJoin(self._chrootDir,self.objVar.Get("cl_root_path"))
self._baseDir = os.path.normpath(self._baseDir)
self._reFunc = re.compile(("%s%s%s")\
%(self.varStart,self._reFunctionText,self.varEnd),re.M)
# Аттрибуты для функции шаблона ini()
@ -3099,8 +3101,8 @@ or 'lower' or 'capitalize'"))
cl_overriding.exit(1)
if len(valueVar) != len(valueElementVar):
cl_overriding.printERROR(\
_("size %s is not equal to the size of %s")\
%(nameVar, nameElementVar))
_("size %(name)s is not equal to the size of %(nameElement)s")\
%{'name':nameVar, 'nameElement':nameElementVar})
self.printErrTemplate()
cl_overriding.exit(1)
index = None
@ -3250,6 +3252,7 @@ re.M|re.S)
# Базовая директория переноса шаблонов "/mnt/calculate" или "/" и.т.д
self._baseDir = pathJoin(self.objVar.Get("cl_chroot_path"),
self.objVar.Get("cl_root_path"))
self._baseDir = os.path.normpath(self._baseDir)
# Последняя часть директории шаблона (имя сервиса: samba, mail)
self._servDir = servDir
if self._servDir:
@ -3581,8 +3584,8 @@ variable 'cl-name'"))
for skipDir in skipDirs:
setWARNING(" "*6 + skipDir)
setWARNING("")
setWARNING(_("Headers directory and template files first level \
should include a check of the variable 'cl-name'."))
setWARNING(_("Headers directory and template files first level "\
"should include of the 'cl-name' variable."))
setWARNING(_("Example:"))
setWARNING("# Calculate cl_name==calculate-install")
return skipDirs + skipTemplates
@ -3834,10 +3837,14 @@ should include a check of the variable 'cl-name'."))
if optDir.get("path"):
path = optDir["path"]
else:
path = os.path.split(applyDir)[1]
path = pathJoin(self._baseDir, path)
if applyDir == self._baseDir:
path = os.path.dirname(self._baseDir)
else:
path = os.path.split(applyDir)[1]
path = pathJoin(self._baseDir, path)
if not os.path.exists(templateDirFile):
applyDir = os.path.join(path, os.path.split(applyDir)[1])
if applyDir != self._baseDir:
applyDir = os.path.join(path, os.path.split(applyDir)[1])
# Фильтрация шаблонов по названию директории
realPath = os.path.join("/",applyDir.partition(self._baseDir)[2])
if realPath in self.dirsFilter:
@ -3919,6 +3926,25 @@ should include a check of the variable 'cl-name'."))
applyDir)
return ("", False, [])
# Очищаем директорию
if objHead.typeAppend == "clear":
if os.path.isdir(applyDir):
for rmPath in os.listdir(applyDir):
removePath = pathJoin(applyDir, rmPath)
if os.path.isdir(removePath):
# удаляем директорию
try:
removeDir(removePath)
except:
self.setError(_("Can not delete dir: " ) +\
removePath)
else:
try:
os.unlink(removePath)
except:
self.setError(_("Can not delete: " ) + removePath)
return ("", False, [])
# Созданные директории
createdDirs = []
# chmod - изменяем права
@ -4108,6 +4134,16 @@ should include a check of the variable 'cl-name'."))
if realPath in self.filesFilter:
return ([], False)
typeAppendTemplate = objHeadNew.typeAppend
# Очищаем оригинальный файл
if typeAppendTemplate == "clear":
try:
open(pathOldFile, "w").truncate(0)
except:
self.setError(_("Error in template") + ": " +\
nameFileTemplate)
self.setError(_("Can not clear file") + ": " +\
pathOldFile)
return (applyFiles, False)
# Удаляем оригинальный файл
if typeAppendTemplate == "remove":
if os.path.islink(pathOldFile):
@ -4738,6 +4774,7 @@ class templateClt(scanDirectoryClt, template):
# Базовая директория переноса шаблонов "/mnt/calculate" или "/" и.т.д
self._baseDir = pathJoin(self.objVar.Get("cl_chroot_path"),
self.objVar.Get("cl_root_path"))
self._baseDir = os.path.normpath(self._baseDir)
def applyTemplate(self, path):
"""Применение отдельного .clt шаблона"""
@ -4916,8 +4953,8 @@ class iniParser(_error, templateFormat):
classObj = self.getClassObj("plasma")
else:
if nameFomat == "plasma":
self.setError(_("In the file %s (format - 'plasma'), \
write the variable in the format 'samba'")\
self.setError(_("In the file %s (format - 'plasma'), "\
"write the variable in the format 'samba'")\
%self.iniFile)
return False
# формат samba
@ -5018,8 +5055,8 @@ class iniParser(_error, templateFormat):
formatPlasma = True
else:
if nameFomat == "plasma":
self.setError(_("In the file %s (format - 'plasma'), \
get the variable in the format 'samba'")\
self.setError(_("In the file %s (format - 'plasma'), "\
"get the variable in the format 'samba'")\
%self.iniFile)
return False
# формат samba
@ -5082,8 +5119,8 @@ class iniParser(_error, templateFormat):
formatPlasma = True
else:
if nameFomat == "plasma":
self.setError(_("In the file %s (format - 'plasma'), \
get all variables in the format 'samba'")\
self.setError(_("In the file %s (format - 'plasma'), "\
"get all variables in the format 'samba'")\
%self.iniFile)
return False
# формат samba

@ -514,24 +514,33 @@ def removeDir(rmDir):
rmtree(rmDir)
return True
def getRunCommands():
"""List run program"""
if not os.access('/proc',os.R_OK):
return []
return map(lambda x:open('/proc/%s/cmdline'%x).read().strip(),
filter(lambda x:x.isdigit(),
os.listdir('/proc')))
def isMount(path):
"""В случае монтирования директории выдает другой примонтированный путь"""
absPath = os.path.abspath(path)
mtabFile = '/etc/mtab'
if not os.access(mtabFile,os.R_OK):
return ""
return filter(lambda x: x!=absPath,
reduce(lambda x,y: y, filter(lambda x: absPath in x,
map(lambda x: [x[0], x[1]], map(lambda x: x.split(" "),
open("/etc/mtab")))),[""]))[0]
open(mtabFile)))),[""]))[0]
def pathJoin(*paths):
"""Складывает пути, в отличии от os.path.join, складывает абсолютные пути"""
if len(paths)==1:
return paths[0]
return os.path.join(paths[0],
reduce(os.path.join,
filter(lambda x:x and x != "/",
map(lambda x: x.startswith("/") and x[1:] or x,
paths[1:])),''))
return reduce(os.path.join,
filter(lambda x:x and x != "/",
map(lambda x: x.startswith("/") and x[1:] or x,
paths[1:])),paths[0])
def getUserPassword(flag="dialog", pwDialog=False):
"""Получить пароль у пользователя

@ -181,6 +181,9 @@ class Data:
# on/off composite mode
os_x11_composite = {}
# current system is scratch
os_scratch = {}
# programs have templates setup
cl_merges = {}

@ -0,0 +1,507 @@
#-*- coding: utf-8 -*-
# Copyright 2008-2010 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
import sys
from cl_utils import getpathenv, runOsCommand, typeFile
import re
from os import path
from cl_ldap import ldapUser
from operator import itemgetter
class clLocale:
lang = {
#Belarussian
'be_BY' : {
'locale':'be_BY.UTF-8',
'keymap':'by',
'dumpkeys_charset': 'koi8-u',
'consolefont':'Cyr_a8x16',
'xkblayout':'us,by',
'language':'be',
},
#Bulgarian
'bg_BG' : {
'locale':'bg_BG.UTF-8',
'keymap':'bg_bds-utf8',
'dumpkeys_charset': '',
'consolefont':'ter-m14n',
'xkblayout':'us,bg',
'language':'bg',
},
#Belgian
'fr_BE' : {
'locale':'fr_BE.UTF-8',
'keymap':'be-latin1',
'dumpkeys_charset':'',
'consolefont':'lat9w-16',
'xkblayout':'us,be',
'language':'fr',
},
#Brazilian Portuguese
'pt_BR' : {
'locale':'pt_BR.UTF-8',
'keymap':'br-abnt2',
'dumpkeys_charset':'',
'consolefont':'lat9w-16',
'xkblayout':'pt,us',
'language':'pt',
},
#Canadian French
'fr_CA' : {
'locale':'fr_CA.UTF-8',
'keymap':'cf',
'dumpkeys_charset':'',
'consolefont':'default8x16',
'xkblayout':'us,ca_enhanced',
'language':'fr',
},
#Danish
'da_DK' : {
'locale':'da_DK.UTF-8',
'keymap':'dk-latin1',
'dumpkeys_charset':'',
'consolefont':'lat0-16',
'xkblayout':'us,dk',
'language':'da',
},
#French
'fr_FR' : {
'locale':'fr_FR.UTF-8',
'keymap':'fr-latin9',
'dumpkeys_charset':'',
'consolefont':'lat0-16',
'xkblayout':'fr,us',
'language':'fr',
},
#German
'de_DE' : {
'locale':'de_DE.UTF-8',
'keymap':'de-latin1',
'dumpkeys_charset':'',
'consolefont':'lat9w-16',
'xkblayout':'de,us',
'language':'de',
},
#Icelandic
'is_IS' : {
'locale':'is_IS.UTF-8',
'keymap':'is-latin1',
'dumpkeys_charset':'',
'consolefont':'cp850-8x16',
'xkblayout':'us,is',
'language':'is',
},
#Italian
'it_IT' : {
'locale':'it_IT.UTF-8',
'keymap':'it',
'dumpkeys_charset':'',
'consolefont':'default8x16',
'xkblayout':'us,it',
'language':'it',
},
#Norwegian
'nn_NO' : {
'locale':'nn_NO.UTF-8',
'keymap':'no-latin1',
'dumpkeys_charset':'',
'consolefont':'lat9w-16',
'xkblayout':'us,no',
'language':'nn',
},
#Polish
'pl_PL' : {
'locale':'pl_PL.UTF-8',
'keymap':'pl',
'dumpkeys_charset':'',
'consolefont':'lat2-16',
'xkblayout':'us,pl',
'language':'pl',
},
#Russian
'ru_RU' : {
'locale':'ru_RU.UTF-8',
'keymap':'-u ruwin_cplk-UTF-8',
'dumpkeys_charset':'',
'consolefont':'ter-k14n',
'xkblayout':'us,ru(winkeys)',
'language':'ru',
},
#Spanish
'es_ES' : {
'locale':'es_ES.UTF-8',
'keymap':'es euro2',
'dumpkeys_charset':'',
'consolefont':'lat0-16',
'xkblayout':'es,us',
'language':'es',
},
#Swedish
'sv_SE' : {
'locale':'sv_SE.UTF-8',
'keymap':'sv-latin1',
'dumpkeys_charset':'',
'consolefont':'lat0-16',
'xkblayout':'us,se',
'language':'sv',
},
#Ukrainian
'uk_UA' : {
'locale':'uk_UA.UTF-8',
'keymap':'ua-utf',
'dumpkeys_charset':'koi8-u',
'consolefont':'ter-v14n',
'xkblayout':'us,ua(winkeys)',
'language':'uk',
},
#United Kingdom/British
'en_GB' : {
'locale':'en_GB.UTF-8',
'keymap':'uk',
'dumpkeys_charset':'',
'consolefont':'LatArCyrHeb-16',
'xkblayout':'us,gb',
'language':'en',
},
#United State/English
'en_US' : {
'locale':'en_US.UTF-8',
'keymap':'us',
'dumpkeys_charset':'',
'consolefont':'LatArCyrHeb-16',
'xkblayout':'us',
'language':'en',
}
}
def getLangs(self):
return self.lang.keys()
def getLanguages(self):
return map(lambda x:self.lang[x]['language'],
self.lang.keys())
def isLangExists(self,lang):
return lang in self.lang.keys()
def isValueInFieldExists(self,field,value):
return value in map(lambda x:self.lang[x][field],self.lang.keys())
def getFields(self,field):
return [ l[1][field] for l in self.lang.items() ]
def getFieldByLang(self,field,lang):
return self.lang.get(lang, self.lang['en_US'])[field]
def getFieldByKeymap(self,field,keymap):
return self.lang.get(self.getLangByField('keymap',keymap),
self.lang['en_US'])[field]
def getLangByField(self,field,value):
langs = [lang[0] for lang in self.lang.items()
if lang[1][field] == value ]
if not langs:
return 'en_US'
else:
return langs[0]
class varsShare:
"""Share methods and attributs for fill vars methods"""
dictLinuxName = {"CLD":"Calculate Linux Desktop",
"CLDX":"Calculate Linux Desktop",
"CLDG":"Calculate Linux Desktop",
"CDS":"Calculate Directory Server",
"CLS":"Calculate Linux Scratch",
"CSS":"Calculate Scratch Server",
"Gentoo":"Gentoo"}
dictLinuxSubName = {"CLD":"KDE", "CLDX":"XFCE", "CLDG":"GNOME"}
dictNameSystem = {'CDS':'server',
'CLD':'desktop',
'CLDG':'desktop',
'CLDX':'desktop',
'CLS':'desktop',
'CSS':'server'}
# data object from LDAP
_ldapUserObject = False
# user data from LDAP
_ldapUserData = {}
reFindVer = re.compile(
"(?<=version )(\d+\.?\d*\.?\d*\.?\d*)([^\d* ])*(\d*)")
def getFilesByType(self,pathname,descr):
"""Get files from "pathname" has "descr" in descriptions"""
filelist = map(lambda x:path.join(pathname,x),os.listdir(pathname))
ftype = typeFile(magic=0x4).getMType
filesWithType = map(lambda x:(x,ftype(x)), filelist)
return filter(lambda x:descr in x[1],filesWithType)
def getInitrd(self,arch,shortname,chroot,kernel,suffix="",notsuffix=""):
"""Get initrd for kernel"""
reInitrdVer = re.compile("(initrd|initramfs)-(.+?)(-install)?$",re.S)
def initrd_version_by_name(filename):
resInitrdVer = reInitrdVer.search(filename)
if resInitrdVer:
return resInitrdVer.groups()[1]
return ""
ftype = typeFile(magic=0x4).getMType
kernelfile = path.join(chroot,'boot',kernel)
resKernelVer = self.reFindVer.search(ftype(kernelfile))
if resKernelVer:
kernelVersion = "%s-%s-%s"% \
(resKernelVer.group().replace('-calculate',''),
arch, shortname)
origKernelVer = resKernelVer.group()
bootdir = path.join(chroot,'boot')
initramfsFiles = self.getFilesByType(bootdir,"ASCII cpio archive")
initramfsWithVer = \
filter(lambda x: (kernelVersion in x[1] or
origKernelVer in x[1]) and \
x[0].endswith(suffix) and \
(not notsuffix or not x[0].endswith(notsuffix)),
map(lambda x:(x[0],initrd_version_by_name(x[0])),
initramfsFiles))
if initramfsWithVer:
return path.split(min(initramfsWithVer,
key=itemgetter(0))[0])[-1]
return ""
def getDirList(self,pathname):
"""Get directory list by pathname"""
dirs = []
if path.exists(pathname):
dirs = filter(lambda x: path.isdir(path.join(pathname,x)),
os.listdir(pathname))
return dirs
def getUserInfo(self):
"""Get information about user from LDAP in dict format"""
userName = self.Get('ur_login')
if userName:
if userName in self._ldapUserData:
return self._ldapUserData[userName]
else:
ldapObj = self.getLdapUserObject()
userInfo = ldapObj.getUserLdapInfo(userName)
if userInfo:
self._ldapUserData[userName] = userInfo
return userInfo
return {}
def getLdapUserObject(self):
"""Get data obejct from LDAP"""
if not self._ldapUserObject:
self._ldapUserObject = ldapUser()
return self._ldapUserObject
def _runos(self, cmd, env={}):
"""Return result of os command perform"""
if not env:
env.update(os.environ.items() + [("PATH",getpathenv())] +\
env.items())
retCode, programOut = runOsCommand(cmd, None, env_dict=env)
if not retCode:
return programOut
return False
def get_composite_from_xorgconf(self,chroot="/"):
"""Get composite value from xorg.conf"""
xorgConfig = path.join(chroot,
"etc/X11/xorg.conf")
try:
confLines = open(xorgConfig,"r").readlines()
except:
return None
flagStartExtensions = False
lineCompositeTmp = ""
lineComposite = ""
for line in confLines:
if flagStartExtensions:
if 'EndSection' in line:
lineComposite = lineCompositeTmp
break
elif 'Section' in line:
break
if 'Option' in line and '"Composite"' in line:
lineCompositeTmp = line
else:
if '"Extensions"' in line and 'Section' in line:
flagStartExtensions = True
if lineComposite:
listOpt = filter(lambda x: x.strip(), lineComposite.split('"'))
if len(listOpt) == 3:
ret = listOpt[2].lower()
if ret in ("on","true","yes","1"):
return "on"
elif ret in ("off","false","no","0"):
return "off"
return None
def getValueFromCmdLine(self,option,num):
"""Get value of parameter from boot params
Parameters:
option param name
num number part of value parameter (, split)
"""
cmdLine = "/proc/cmdline"
calculateParam = "calculate"
# try get timezone from kernel calculate param
try:
for param in open(cmdLine,"r").read().split(" "):
parname,op,value = param.partition("=")
if parname == calculateParam and op == "=":
values = value.split(",")
if len(values) > num and values[num].strip():
return values[num].strip()
except IOError,e:
return ""
def getValueFromConfig(self,config,name):
"""Get value of parameter from bash type file
Parameters:
config config file name
name param name
"""
reMatch = re.compile("^%s\s*=\s*\"?(.*?)\"?$"%name, re.I)
try:
if path.exists(config):
for line in open(config,"r").readlines():
match = reMatch.match(line)
if match:
return match.groups()[0].strip()
except:
pass
return False
def getX11Resolution(self):
"""Return current screen resolution (width, height), X must be ran"""
lines=self._runos("xdpyinfo")
if not lines:
return ""
reRes = re.compile("dimensions:\s+(\d+)x(\d+)\s+pixels")
searchRes=False
for line in lines:
searchRes = reRes.search(line)
if searchRes:
break
if searchRes:
return (searchRes.group(1), searchRes.group(2))
else:
return ""
def getShortnameByMakeprofile(self,systemroot):
"""Get shortname by symlink of make.profile"""
makeprofile = path.join(systemroot,'etc/make.profile')
if path.exists(makeprofile):
link = os.readlink(makeprofile)
reMakeProfileLink = re.compile('/calculate/(desktop|server)/(%s)/'%
"|".join(self.dictLinuxName.keys()),re.S)
shortnameSearch = reMakeProfileLink.search(link)
if shortnameSearch:
return shortnameSearch.groups()[1]
return None
def getShortnameByIni(self,systemroot):
"""Get shortname by calculate.ini file"""
inifile = path.join(systemroot,'etc/calculate/calculate.ini')
if path.exists(inifile):
FD = open(inifile)
data = FD.readlines()
FD.close()
shortNameList = filter(lambda y:y,
map(lambda x:\
len(x.split("="))==2 and\
x.split("=")[0]=="calculate" and\
x.split("=")[1].strip(), data))
if shortNameList:
return shortNameList[0]
def detectOtherShortname(self,systemroot):
"""Detect other system. Now only Gentoo."""
gentooFile = path.join(systemroot,"etc/gentoo-release")
if path.exists(gentooFile):
return "Gentoo"
return None
def getVersionFromMetapackage(self,systemroot,shortname):
"""Get version from meta package"""
pkgInfoDir = path.join(systemroot,'var/db/pkg/app-misc/')
if not os.access(pkgInfoDir,os.R_OK):
return None
metaPkgs = filter(lambda x:"%s-meta"%shortname.lower() in x,
os.listdir(pkgInfoDir))
if metaPkgs:
reFindVer = re.compile("(?<=\-)\d+\.?\d*\.?\d*")
findVer = reFindVer.search(metaPkgs[0])
if findVer:
return findVer.group()
return None
def getVersionFromCalculateIni(self,systemroot):
"""Get version from calculate ini"""
pathname = path.join(systemroot,
'etc/calculate/calculate.ini')
if path.exists(pathname):
FD = open(pathname)
data = FD.readlines()
FD.close()
verList = filter(lambda y:y,
map(lambda x:\
len(x.split("="))==2 and\
x.split("=")[0]=="linuxver" and\
x.split("=")[1].strip(), data))
if verList:
reVer=re.compile("^(\d+\.)*\d$",re.S)
reRes = filter(reVer.search,verList)
if reRes:
return reRes[0]
def getVersionFromGentooFiles(self,systemroot):
"""Get version from gentoo files"""
gentooFile = path.join(systemroot,"etc/gentoo-release")
systemVersion = ""
flagGentoo = False
reVer=re.compile("^(\d+\.)*\d$",re.S)
if path.exists(gentooFile):
gentooLink = path.join(systemroot,"etc/make.profile")
if path.islink(gentooLink):
vers = filter(reVer.search,
os.readlink(gentooLink).split('/'))
if vers:
return vers[-1]
def getVersionFromUname(self):
"""Get version from uname"""
textLines = self._runos("uname -r")
reVer=re.compile("^(\d+\.)*\d",re.S)
kernelVersion = ""
if textLines:
kernelVersion = textLines[0]
if kernelVersion:
reRes = reVer.search(kernelVersion)
if reRes:
return reRes.group()

@ -119,7 +119,7 @@ class xml_gconf(xml_xfce):
else:
if not tagName == "entry":
self.setError(_("The text is not a valid gconf-XML format \
(found '<gconf><%s>..</%s></gconf>'")%(tagName,tagName))
(found '<gconf><%(tag)s>..</%(tag)s></gconf>'")%{'tag':tagName})
return False
if not n.hasAttribute("name"):
self.setError(_('Not found arrtibute "name" in tag entry'))

@ -132,10 +132,16 @@ class updateUserConfigs(shareUpdateConfigs):
xUsers = []
if retCode==0:
if resWho:
xUsers = map(lambda x: x[0],
filter(lambda x: x[1].startswith(":"),
map(lambda x: filter(lambda y: y,
x.split(" "))[:2] ,resWho)))
listProcessing = lambda x: (x[0], x[1], x[4])\
if len(x)==5 else []
xUsers = list(set(filter(lambda x: x!="root",
map(lambda x: x[0],
filter(lambda x: x and\
(x[2].startswith("(:") or \
x[1].startswith(":")),
map(lambda x: listProcessing(\
filter(lambda y: y, x.split(" "))),
resWho))))))
else:
self.printERROR(_("Can not execute 'who'"))
return False
@ -238,6 +244,7 @@ class updateSystemConfigs(shareUpdateConfigs):
if os.path.exists(realPath):
scanObj.scanningDirectory(realPath)
configFiles = map(lambda x: x.partition(configPath)[2], configFiles)
configFiles = map(lambda x: pathJoin('/',x), configFiles)
return configFiles
def createDir(self, configPath, dstDir):

@ -70,7 +70,8 @@ setup(
'calculate-lib.pym.client',
'calculate-lib.pym.update_config'],
data_files = [("/usr/share/calculate/i18n",['i18n/cl_lib_ru.mo']),
("/var/calculate/remote",[])],
("/var/calculate/remote", []),
("/var/log/calculate", [])],
scripts=["./scripts/cl-update-config"],
cmdclass={'build_scripts':cl_build_scripts,
'install_scripts':cl_install_scripts},

Loading…
Cancel
Save