#-*- 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 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 os.path import exists as pathexists 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_BY', }, #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_BE', }, #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':'fr_CA', }, #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_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_GB', }, #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 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 = {} 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"] + 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) 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 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 def get_os_linux_name(self): """полное название системы""" linuxShortName = self.Get("os_linux_shortname") if linuxShortName: if linuxShortName in self.dictLinuxName.keys(): return self.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): '''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() 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] def get_from_gentoo_files(): """Get version from gentoo files""" gentooFile = "/etc/gentoo-release" systemVersion = "" flagGentoo = False if os.path.exists(gentooFile): gentooLink = "/etc/make.profile" if os.path.islink(gentooLink): return os.readlink(gentooLink).rpartition("/")[2] def get_from_uname(): """Get version from uname""" kernelVersion=self._runos("uname -r") if kernelVersion: return kernelVersion.partition("-")[0] return get_from_metapackage() or get_from_calculate_ini() or \ get_from_gentoo_files() or get_from_uname() or "0" 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_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 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: localeVal = self.getValueFromConfig('/etc/env.d/02locale','LANG') if locale.isValueInFieldExists('locale',localeVal): return localeVal 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() return locale.getFieldByLang("xkblayout", self.Get('os_locale_lang')) def get_os_locale_xkbname(self): """названия используемых раскладок клавиатуры для X""" localeXkb = self.Get("os_locale_xkb") if localeXkb: return localeXkb.split("(")[0] return "" 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_os_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 pathexists(xorg_modules_dir): list_avialable_drivers = \ map(lambda x: x[:-7], filter(lambda x: x.endswith('_drv.so'), os.listdir(xorg_modules_dir))) else: list_avialable_drivers = [] if display and list_avialable_drivers: reDriver = re.compile('|'.join(map(lambda x: "%s_drv.so"%x, 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 and resDriver.group(1) in list_avialable_drivers: return resDriver.group(1) defaultDriver = { 'vesa':'vesa', 'nvidia':'nvidia' if "nvidia" in list_avialable_drivers else "nv", 'ati':'fglrx' if "fglrx" in list_avialable_drivers else "radeon", 'intel':'intel', 'via':'via', 'vmware':'vmware'} hr_video = self.Get('hr_video') if hr_video in defaultDriver and \ defaultDriver[hr_video] in list_avialable_drivers: return defaultDriver[hr_video] 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): """Получить высоту экрана в пикселах""" resolution = self.getX11Resolution() if resolution: self.Set('os_x11_width',resolution[0]) return resolution[1] return "768" def get_os_x11_width(self): """Получить ширину экрана в пикселах""" resolution = self.getX11Resolution() if resolution: self.Set('os_x11_height',resolution[1]) return resolution[0] return "1024" def get_os_x11_standart(self): """Get the nearest standard size of image relative current screen resolution""" #Стандартные разрешения widthVal = self.Get('os_x11_width') heightVal = self.Get('os_x11_height') if not widthVal or not heightVal: return "" width = int(widthVal) height = int(heightVal) res = [(1024,768), (1280,1024), (1280,800), (1440,900), (1600,1200), (1680,1050), (1920,1200)] resolution = [] formats = [] for w, h in res: formats.append(float(w)/float(h)) listFr = list(set(formats)) listFormats = {} for fr in listFr: listFormats[fr] = [] for w, h in res: for fr in listFormats.keys(): if fr == float(w)/float(h): listFormats[fr].append((w,h)) break format = float(width)/float(height) deltaFr = {} for fr in listFormats.keys(): deltaFr[abs(format - fr)] = fr resolution = listFormats[deltaFr[min(deltaFr.keys())]] flagFound = False stResol = [] stHeights = [] stWidths = [] stWidth = False stHeight = False for w, h in resolution: if w >= width and h >= height: stResol.append((w,h)) stHeights.append(h) if stHeights: stHeight = min(stHeights) for w, h in stResol: if stHeight == h: stWidths.append(w) if stWidths: stWidth = min(stWidths) if (not stWidth) or (not stHeight): return "%sx%s"%(resolution[-1][0],resolution[-1][1]) else: return "%sx%s"%(stWidth,stHeight) def get_os_x11_composite(self): """Включен ли композитный режим видеокарты on/off""" state = self.get_composite_from_xorgconf() return state or "off" def get_hr_laptop(self): """Если компьютер ноутбук, то его производитель""" formfactor = self._runos("hal-get-property --udi \ /org/freedesktop/Hal/devices/computer --key system.formfactor") if not formfactor: return "" if formfactor == 'laptop': vendor = self._runos("hal-get-property --udi \ /org/freedesktop/Hal/devices/computer --key system.hardware.vendor") if vendor: vendor = vendor.split(" ")[0] else: vendor = "unknown" return vendor.lower() return "" 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"