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.
calculate-utils-2.2-lib/pym/cl_fill.py

807 lines
28 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#-*- coding: utf-8 -*-
# Copyright 2008-2010 Mir Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import os
import types
import filecmp
import pwd, grp
import cl_overriding
from cl_ldap import ldapUser
from cl_datavars import glob_attr
class clLocale:
lang = {
#Belarussian
'be_BY' : {
'locale':'be_BY.UTF-8',
'keymap':'by',
'dumpkeys_charset': 'koi8-u',
'consolefont':'Cyr_a8x16',
'xkblayout':'us,by',
'language':'ru',
},
#Belgian
'fr_BE' : {
'locale':'fr_BE.UTF-8',
'keymap':'be-latin1',
'dumpkeys_charset':'',
'consolefont':'lat9w-16',
'xkblayout':'us,be',
'language':'en_US',
},
#Brazilian Portuguese
'pt_BR' : {
'locale':'pt_BR.UTF-8',
'keymap':'br-abnt2',
'dumpkeys_charset':'',
'consolefont':'lat9w-16',
'xkblayout':'pt,us',
'language':'pt_BR',
},
#Canadian French
'fr_CA' : {
'locale':'fr_CA.UTF-8',
'keymap':'cf',
'dumpkeys_charset':'',
'consolefont':'default8x16',
'xkblayout':'us,ca_enhanced',
'language':'en_US',
},
#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':'en_US',
},
#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':'en_US',
},
#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_US',
},
#United State/English
'en_US' : {
'locale':'en_US.UTF-8',
'keymap':'us',
'dumpkeys_charset':'',
'consolefont':'LatArCyrHeb-16',
'xkblayout':'us',
'language':'en_US',
}
}
def getLangs(self):
return self.lang.keys()
def isLangExists(self,lang):
return lang in 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 = {}
def get_cl_env_path(self):
'''Пути к env файлам'''
envData = self.Get("cl_env_data")
if envData:
return map(lambda x: x[1], envData)
else:
cl_overriding.printERROR(_("Error:") + " " +\
_("Template variable cl_env_data is empty"))
cl_overriding.exit(1)
def get_cl_env_location(self):
'''Алиасы к env файлам'''
envData = self.Get("cl_env_data")
if envData:
return map(lambda x: x[0], envData)
else:
cl_overriding.printERROR(_("Error:") + " " +\
_("Template variable cl_env_data is empty"))
cl_overriding.exit(1)
def get_cl_template_clt_path(self):
'''Пути к файлам ,clt'''
if "CONFIG_PROTECT" in os.environ:
protectPaths = ["/etc"] + map(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)
def get_os_net_domain(self):
'''Определим домен'''
domain=self._runos("hostname -d 2>&1")
if not domain:
cl_overriding.printERROR(_("Error:") + " " +\
_("Not found domain name"))
cl_overriding.printERROR(\
_("Command 'hostname -d' returns an empty value"))
cl_overriding.exit(1)
elif re.search("^hostname: ",domain):
return "local"
else:
return domain
def get_os_linux_shortname(self):
'''Получить переменную короткого названия системы'''
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
def get_os_linux_name(self):
"""полное название системы"""
linuxShortName = self.Get("os_linux_shortname")
if linuxShortName:
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"}
if linuxShortName in dictLinuxName.keys():
return dictLinuxName[linuxShortName]
else:
return "Linux"
else:
return "Linux"
def get_os_linux_subname(self):
"""постфикс к названию системы"""
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 ""
def get_os_linux_ver(self):
'''Получить версию системы'''
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]=="linuxver" and\
x.split("=")[1].strip(), data))
if shortNameList:
return shortNameList[0]
gentooFile = "/etc/gentoo-release"
systemVersion = ""
flagGentoo = False
if os.path.exists(gentooFile):
gentooLink = "/etc/make.profile"
if os.path.islink(gentooLink):
systemVersion = os.readlink(gentooLink).rpartition("/")[2]
flagGentoo = True
if not flagGentoo:
kernelVersion=self._runos("uname -r")
if kernelVersion:
systemVersion = kernelVersion.partition("-")[0]
return systemVersion
def get_os_net_hostname(self):
'''Считать имя компьютера net_host'''
hostname=self._runos("hostname -s 2>&1")
if not hostname:
return ""
if re.search("^hostname: ",hostname):
hostname=self._runos("hostname 2>&1")
if not hostname:
return ""
if re.search("^hostname: ",hostname):
return self.Get('os_linux_shortname')
else:
if hostname=='livecd':
return self.Get('os_linux_shortname')
return hostname
# все ip
def get_os_net_ip(self):
"""все ip компьютера, разделитель запятая"""
IPs = []
netInterfaces=self.Get("os_net_interfaces")
for i in netInterfaces:
res = self._runos("/sbin/ifconfig %s"%i)
if not res:
break
for line in res:
searchIP = re.search('addr:([0-9\.]+).+Bcast:', line)
if searchIP:
# ip адрес
ip = searchIP.groups()[0]
IPs.append(ip)
return ",".join(IPs)
def get_os_net_interfaces(self):
"""Существующие сетевые интерфейсы"""
return filter(lambda x: x!="lo", getDirList("/sys/class/net"))
# Разрешенные сети (в данном случае все сети)
def get_os_net_allow(self):
"""Разрешенные сети разделитель запятая"""
def getNet(ip, mask):
"""По ip и маске получаем сеть"""
octetsMult = (0x1, 0x100, 0x10000, 0x1000000)
octetsIp = map(lambda x: int(x), ip.split("."))
octetsMask = map(lambda x: int(x), mask.split("."))
ipNumb = 0
for i in octetsMult:
ipNumb += octetsIp.pop()*i
maskNumb = 0
for i in octetsMult:
maskNumb += octetsMask.pop()*i
startIpNumber = maskNumb&ipNumb
x = startIpNumber
nMask = lambda y: len(filter(lambda x: y >> x &1 ,range(32)))
return "%s.%s.%s.%s/%s"\
%(x>>24, x>>16&255, x>>8&255, x&255, nMask(maskNumb))
networks=[]
netInterfaces=self.Get("os_net_interfaces")
flagError = False
for i in netInterfaces:
res = self._runos("/sbin/ifconfig %s"%i)
if not res:
flagError = True
break
for j in res:
s_ip=re.search('addr:([0-9\.]+).+Bcast:.+Mask:([0-9\.]+)' ,j)
if s_ip:
ip, mask = s_ip.groups()
networks.append(getNet(ip, mask))
if flagError:
return ""
return ",".join(networks)
def get_os_locale_xkbname(self):
"""названия используемых раскладок клавиатуры для X"""
localeXkb = self.Get("os_locale_xkb")
if localeXkb:
return localeXkb.split("(")[0]
return ""
def get_os_arch_machine(self):
"""архитектура процессора"""
march = self._runos("uname -m")
if not march:
return ""
return march
def get_os_root_dev(self):
"""корневой раздел файловой системы"""
for record in open('/proc/cmdline','rb').readlines():
re_res=re.search('^root=(\/dev\/[a-z]+[0-9]).*',record.strip())
if re_res:
return re_res.group(1)
else:
mountLunes = self._runos("mount")
if not mountLunes:
return ""
if type(mountLunes) == types.ListType:
root_dev = mountLunes[0].split("on / type")[0].strip()
if root_dev:
return root_dev
return ""
def get_os_root_type(self):
"""тип носителя (ram, hdd, livecd)"""
mountLunes = self._runos("mount")
if not mountLunes:
return ""
rootType = "hdd"
if type(mountLunes) == types.ListType:
flagCD = False
for line in mountLunes:
if "/dev/loop0 on / type" in line:
rootType = "ram"
break
elif "/dev/loop0 on /newroot/mnt/livecd type" in line:
rootType = "ram"
flagCD = True
break
if rootType == "ram":
if os.path.exists("/mnt/livecd") or flagCD:
rootType = "livecd"
return rootType
rootDev = self.Get("os_root_dev")
if rootType != "ram" and rootDev:
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 not devLines:
return ""
if rootType == "ram":
rootType = "hdd"
return rootType
else:
return ""
def get_hr_virtual(self):
"""Название виртуальной машины (virtualbox, vmware, qemu)"""
pciLines = self._runos("/usr/sbin/lspci")
if not pciLines:
return False
virtSysDict = {'VirtualBox':'virtualbox',
'VMware':'vmware',
'Qumranet':'qemu'}
virtName = ''
for vName in virtSysDict.keys():
if filter(lambda x: vName in x, pciLines):
virtName = virtSysDict[vName]
break
return virtName
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 group().strip()
except:
pass
return False
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 get_hr_board_model(self):
"""motherboard model"""
modelFile = "/sys/class/dmi/id/board_name"
try:
return open(modelFile,"r").read().strip()
except:
return ""
def get_hr_board_vendor(self):
"""motherboard vendor"""
vendorFile = "/sys/class/dmi/id/board_vendor"
try:
return open(vendorFile,"r").read().strip()
except:
return ""
def get_hr_cpu_num(self):
"""processors count"""
cpuinfoFile = "/proc/cpuinfo"
try:
return len(["" for line in open(cpuinfoFile,"r").readlines()
if "processor" in line])
except:
return 1
def get_os_locale_locale(self):
"""locale (example: ru_RU.UTF-8)"""
locale = clLocale()
# get locale from boot calculate param
localeVal = self.getValueFromCmdLine("calculate",0)
if locale.isLangExists(localeVal):
return locale.getFieldByLang('locale',localeVal)
elif os.environ.has_key("LANG"):
return os.environ["LANG"]
else:
return locale.getFieldByLang("locale","default")
def get_os_locale_lang(self):
"""lang (example: ru_RU)"""
locale = clLocale()
return locale.getLangByField("locale",self.Get('os_locale_locale'))
def get_os_locale_language(self):
"""language (example: ru)"""
locale = clLocale()
return locale.getFieldByLang("language",self.Get('os_locale_lang'))
def get_os_locale_xkb(self):
"""xkb layouts (example: en,ru)"""
locale = clLocale()
# is specified keymap support by locale hash
if self.Get('os_locale_keymap') in locale.getFields('keymap'):
return locale.getFieldByKeymap("xkblayout",
self.Get('os_locale_keymap'))
else:
return locale.getFieldByLang("xkblayout",
self.Get('os_locale_lang'))
def get_os_locale_keymap(self):
"""keymap of locale (used for /etc/conf.d/keymaps)"""
locale = clLocale()
# get keymap from boot calculate param (keymap specified
# by lang)
keymapConfd = '/etc/conf.d/keymaps'
keymap = self.getValueFromCmdLine("calculate",1)
if locale.isLangExists(keymap):
return locale.getFieldByLang('keymap',keymap)
# get keymap by os_locale_lang
keymap = self.getValueFromConfig(keymapConfd,'KEYMAP')
if keymap:
return keymap
return locale.getFieldByLang("keymap",self.Get("os_locale_lang"))
def get_os_locale_dumpkeys(self):
"""dumpkeys charset for keymap"""
locale = clLocale()
# is specified keymap support by locale hash
if self.Get('os_locale_keymap') in locale.getFields('keymap'):
return locale.getFieldByKeymap("dumpkeys_charset",
self.Get('os_locale_keymap'))
else:
return locale.getFieldByLang("dumpkeys_charset",
self.Get('os_locale_lang'))
def get_os_clock_timezone(self):
"""timezone for clock"""
zoneinfodir = "/usr/share/zoneinfo/"
localtimefile = "/etc/localtime"
# try get timezone from kernel calculate param
timezone = self.getValueFromCmdLine("calculate",2)
if timezone and \
os.path.exists(os.path.join(zoneinfodir,timezone)):
return timezone
# get timezone from localtime symlink
if os.path.lexists(localtimefile):
return os.readlink(localtimefile).replace(zoneinfodir,"")
return "UTC"
def get_os_clock_type(self):
"""type of clock (UTC or local)"""
clockTypeFile = ['/etc/conf.d/clock','/etc/conf.d/hwclock']
for f in clockTypeFile:
clock = self.getValueFromConfig(f,"clock")
if clock:
if clock.upper() == 'UTC':
return clock.upper()
elif clock.lower() == 'local':
return clock.lower()
return "local"
def get_ur_login(self):
"""Имя пользователя"""
uid = os.getuid()
try:
userName = pwd.getpwuid(uid).pw_name
except:
return ""
return userName
def get_ur_group(self):
"""Название группы пользователя"""
userName = self.Get('ur_login')
groupName = ""
if userName:
try:
gid = pwd.getpwnam(userName).pw_gid
groupName = grp.getgrgid(gid).gr_name
except:
return ""
return groupName
def get_ur_fullname(self):
"""Полное имя пользователя"""
userName = self.Get('ur_login')
fullName = ""
if userName:
try:
fullName = pwd.getpwnam(userName).pw_gecos
except:
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 пользователя"""
userInfo = self.getUserInfo()
userJID = ""
if userInfo:
userJID = userInfo["jid"]
return userJID
def get_ur_mail(self):
"""Почтовый адрес пользователя"""
userInfo = self.getUserInfo()
userMail = ""
if userInfo:
userMail = userInfo["mail"]
return userMail
def get_ur_home_path(self):
"""Домашняя директория пользователя"""
userName = self.Get('ur_login')
homeDir = ""
if userName:
try:
homeDir = pwd.getpwnam(userName).pw_dir
except:
return ""
return homeDir
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 ""
def get_hr_x11_video_drv(self):
"""Get video driver used by xorg"""
xorg_modules_dir = '/usr/lib/xorg/modules/drivers'
xorg_conf = '/etc/X11/xorg.conf'
# Try analize Xorg.{DISPLAY}.log
display = os.environ.get('DISPLAY')
if display and os.path.exists(xorg_modules_dir):
list_avialable_drivers = os.listdir(xorg_modules_dir)
if list_avialable_drivers:
reDriver = re.compile('|'.join(list_avialable_drivers))
display_number = re.search(r':(\d+)\..*', display)
if display_number:
xorg_log_file = '/var/log/Xorg.%s.log' % \
display_number.group(1)
if os.path.exists(xorg_log_file):
matchStrs = [i for i in open(xorg_log_file)
if "drv" in i and reDriver.search(i)]
if matchStrs:
resDriver = re.search(r'([^/]+)_drv.so',
matchStrs[-1])
if resDriver:
return resDriver.group(1)
# analize /etc/X11/xorg.conf
if os.path.exists(xorg_conf):
matchSect = re.search(r'Section "Device".*?EndSection',
open('/etc/X11/xorg.conf').read(),re.S)
if matchSect:
resDriver = re.search(r'Driver\s*"([^"]+)"',
matchSect.group(0),re.S)
if resDriver:
return resDriver.group(1)
return "vesa"
def get_hr_video(self):
"""Производитель видеокарты"""
lines=self._runos("lspci")
if not lines:
return ""
reVGA = re.compile("vga",re.I)
foundVGA = False
for line in lines:
if reVGA.search(line):
foundVGA = True
break
if not foundVGA:
return "vesa"
if "nVidia" in line or "GeForce" in line:
return "nvidia"
elif "ATI" in line:
return "ati"
elif "Intel" in line:
return "intel"
elif "VIA" in line:
return "via"
elif "VMware" in line:
return "vmware"
else:
return "vesa"