#-*- coding: utf-8 -*- # Copyright 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 os import re import cl_overriding from cl_datavars import glob_attr from os.path import join as pathjoin, exists as pathexists from os import readlink,listdir,access,R_OK from cl_utils import isMount class fillVars(object, glob_attr): def get_os_net_interfaces_info(self): """Информация о существующих сетевых интерфейсах""" netInterfaces=self.Get("os_net_interfaces") listInterfacesInfo = [] # Получена ли сеть по DHCP если нет to ip или off for interfaces in netInterfaces: fdhcpLeases = "/var/lib/dhcp/dhclient.leases" if access(fdhcpLeases, R_OK) and\ interfaces in open(fdhcpLeases).read(): listInterfacesInfo.append((interfaces, "DHCP")) continue fdhcpInfo = "/var/lib/dhcpcd/dhcpcd-%s.info"%interfaces fdhcpLease = "/var/lib/dhcpcd/dhcpcd-%s.lease"%interfaces if pathexists(fdhcpInfo) or pathexists(fdhcpLease): listInterfacesInfo.append((interfaces, "DHCP")) # Если интерфейс без DHCP if not (interfaces, "DHCP") in listInterfacesInfo: # Находим ip res = self._runos("/sbin/ifconfig %s"%interfaces) ip = "" for j in res: sIP=re.search('addr:([0-9\.]+).+',j) if sIP: ip = sIP.group(1) listInterfacesInfo.append((interfaces, ip)) break if not ip: listInterfacesInfo.append((interfaces, "Off")) return ", ".join(map(lambda x:"%s (%s)"%(x[0],x[1]),listInterfacesInfo)) def get_os_device_hash(self): diskIdPath = '/dev/disk/by-id' usbdevices = \ map(lambda x: readlink(pathjoin(diskIdPath,x)).rpartition('/')[2], filter(lambda x: x.startswith('usb-'),listdir(diskIdPath))) reWrongDevice = re.compile("|".join(['sr','fd','ram','loop'])) devices = filter( lambda x: not reWrongDevice.search(x), listdir('/sys/block')) device_hash = {} for mapnum,device in enumerate(sorted(devices)): device_hash[device] = {} device_hash[device]['map'] = mapnum if device in usbdevices: removablePath = '/sys/block/%s/removable'%device if os.access(removablePath,R_OK) and \ open(removablePath,'r').read().strip() == "1": devtype = "flash" else: devtype = "usb-hdd" else: devtype = "hdd" device_hash[device]['type'] = devtype return device_hash def get_os_disk_hash(self): reSdaPart = re.compile("^/dev/sd([a-z])(\d+)$") devices = self.Get('os_device_hash').keys() disks = reduce( lambda x,y: x + map( lambda x: "/dev/%s"%x, filter(lambda x: y in x,listdir('/sys/block/%s'%y))), devices, [] ) disk_hash = {} # fill grub info for dev in disks: disk_hash[dev] = {} match = reSdaPart.match(dev) if match: disk_hash[dev]['grub'] = "%d,%d" % \ (ord(match.groups()[0])-ord('a'), int(match.groups()[1])-1) curDevice = None # parse all parted lines started with Disk and started with number res = self._runos('LANG=C /usr/sbin/parted -l',ret_list=True) if res is False: cl_overriding.printERROR("Cann't execute /usr/sbin/parted") cl_overriding.exit(1) partedLines = filter(lambda x: x.startswith("Disk") or x.strip()[:1].isdigit(), res ) for line in partedLines: # split data parts = filter(lambda x: x, line.strip().split(' ')) # if start device description if parts[0] == "Disk": curDevice = parts[1][:-1] continue # if first part is number then it is partition description if parts[0].isdigit(): # part name it is devicename + partition number partition = curDevice + parts[0] # create entry if hash hasn't it if not partition in disk_hash: disk_hash[partition] = {} disk_hash[partition]['part'] = parts[4] disk_hash[partition]['size'] = parts[3] # fill format, name and uuid res = self._runos('/sbin/blkid',ret_list=True) if res is False: cl_overriding.printERROR("Cann't execute /sbin/blkid") cl_overriding.exit(1) # map attribute name of blkid to disk_hash blkid_hash = {'LABEL':'name', 'UUID':'uuid', 'TYPE':'format'} for line in res: # split line and discard empty elements parts = filter(lambda x: x, line.strip().split(' ')) if len(parts)>1 and parts[0][:-1] in disks: dev = parts[0][:-1] for i in parts[1:]: key,op,value = i.partition('=') if key in blkid_hash: key = blkid_hash[key] disk_hash[dev][key] = value[1:-1] return disk_hash def get_os_disk_dev(self): """List of available partition devices""" return sorted(self.Get('os_disk_hash').keys()) def getAttributeFromHash(self,var,attr): hash = self.Get(var) return map(lambda x: hash[x][attr] if attr in hash[x] else "", sorted(hash.keys())) def get_os_disk_uuid(self): """List uudi for partition devices""" return self.getAttributeFromHash('os_disk_hash','uuid') def get_os_disk_install(self): """List mounted points for installed system""" rootdev = self.Get('os_root_dev') disk_hash = self.Get('os_disk_hash') def getMountPoint(disk): if disk == rootdev: return "/" elif "format" in disk_hash[disk] and \ "swap" in disk_hash[disk]['format']: return "swap" else: mount_point = isMount(disk) if mount_point == "/": return "" else: return mount_point return map(lambda x: getMountPoint(x), sorted(self.Get('os_disk_hash').keys())) def get_os_disk_load(self): """List mounted points for current operation system""" disk_hash = self.Get('os_disk_hash') def isSwap(disk): if "format" in disk_hash[disk] and \ "swap" in disk_hash[disk]['format']: return "swap" else: return "" return map(lambda x: isMount(x) or isSwap(x) or "", sorted(self.Get('os_disk_hash').keys())) def get_os_disk_format(self): """List filesystem for partition devices""" return self.getAttributeFromHash('os_disk_hash','format') def get_os_disk_grub(self): """List grub id for partition devices""" return self.getAttributeFromHash('os_disk_hash','grub') def get_os_disk_part(self): """Type of partition devices (primary, extended or logical)""" return self.getAttributeFromHash('os_disk_hash','part') def get_os_disk_size(self): """Partition size""" return self.getAttributeFromHash('os_disk_hash','size') def get_os_disk_name(self): """Label of partitions""" return self.getAttributeFromHash('os_disk_hash','name') def get_os_device_dev(self): """Devices""" return sorted(self.Get('os_device_hash').keys()) def get_os_device_type(self): """Device type (hdd,cdrom,usb-flash)""" return self.getAttributeFromHash('os_device_hash','type') def get_os_device_map(self): """Map number for grub""" return self.getAttributeFromHash('os_device_hash','map') def get_os_grub_info(self): """Part of current grub.conf""" pass def get_os_grub_devicemap_info(self): """Content of device.map file for grub""" pass def get_os_fstab_mount_info(self): """Information about mount points for fstab""" pass def get_os_fstab_swap_info(self): """Information about swap for fstab""" pass