Moved not get_ methods from cl_fill to cl_vars_share module.

Fill function refactoring: os_linux_ver,os_linux_shortname and etc.
Moved some fill methods from calculate-install.
Changed regular expression for find initramfs files!!!.
Move os_scratch from install to lib.
develop
Mike Hiretsky 14 years ago
parent 57dc84c57b
commit bbfc691dc4

@ -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,17 +51,17 @@ 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'"))
@ -288,128 +80,34 @@ class fillVars(glob_attr):
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")
@ -553,9 +249,9 @@ class fillVars(glob_attr):
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:
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
if not devLines:
@ -567,7 +263,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 +278,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 +286,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 +294,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 +341,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 +350,7 @@ class fillVars(glob_attr):
return userName
def get_ur_group(self):
"""Название группы пользователя"""
"""User group"""
userName = self.Get('ur_login')
groupName = ""
if userName:
@ -666,7 +362,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 +372,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 +381,7 @@ class fillVars(glob_attr):
return userJID
def get_ur_mail(self):
"""Почтовый адрес пользователя"""
"""Get user email"""
userInfo = self.getUserInfo()
userMail = ""
if userInfo:
@ -713,7 +389,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 +401,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 +410,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 +424,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 +434,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 +456,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 +465,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 +530,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 +549,7 @@ class fillVars(glob_attr):
return ""
def get_hr_video(self):
"""Производитель видеокарты"""
"""Videocard vendor"""
lines=self._runos("lspci")
if not lines:
return ""
@ -925,16 +575,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"

@ -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,506 @@
#-*- 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=""):
"""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),
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()
Loading…
Cancel
Save