Compare commits

...

53 Commits

Author SHA1 Message Date
Mike Hiretsky e30b350f50 Restore full info about MBR disk.
13 years ago
Mike Hiretsky 9d81a083d6 Fix for bind mount points.
13 years ago
Mike Hiretsky 9b1a2c8051 Remove /usr/calculate/share/linux from distro path.
13 years ago
Mike Hiretsky 4708568240 Add detect by calculate OS on raid and lvm.
13 years ago
Mike Hiretsky fc2ee711e7 Check ability install on RAID.
13 years ago
Mike Hiretsky 257fa2624f Fix detect LVM on RAID.
13 years ago
Mike Hiretsky 2c8f640e2b Update display information in install disk table.
13 years ago
Mike Hiretsky cea3da200b Fix for LVM.
13 years ago
Mike Hiretsky d2085307aa Fix refresh lvm.
13 years ago
Mike Hiretsky 4717969eab Add check using raid lvm member.
13 years ago
Mike Hiretsky 881f9d22fb Refactoring disk_content
13 years ago
Mike Hiretsky b4c4e69ec3 Update lvm raid member display.
13 years ago
Mike Hiretsky 83b3b17167 Add detect active lvm and raid members.
13 years ago
Mike Hiretsky 73647850d1 Refresh lvm data.
13 years ago
Mike Hiretsky f43afc90db Fix print scheme in show-partition.
13 years ago
Mike Hiretsky e1e44e4657 Hide "-" in os without build.
13 years ago
Mike Hiretsky 0a82ec7845 Enable show-partition without -d.
13 years ago
Mike Hiretsky 942bb7dc60 Add detect current os.
13 years ago
Mike Hiretsky 536fca44b3 Fix counting Partition. Add installation from flash and cdrom.
13 years ago
Mike Hiretsky 5eaedb26fe Add --iso option.
13 years ago
Mike Hiretsky b129e397bc Os detect update.
13 years ago
Mike Hiretsky 71ae46b885 Add print partitions.
13 years ago
Mike Hiretsky 21bd3595b1 Fix dolvm and domdadm kernel attrs.
13 years ago
Mike Hiretsky 21e251bac2 Fix check legecy grub install.
13 years ago
Mike Hiretsky 43a7c12d8a Fix detect usb devices.
13 years ago
Mike Hiretsky dffd6ad001 Fix kernel attr variable.
13 years ago
Mike Hiretsky 3ec5ff5ec9 Fix change part id.
13 years ago
Mike Hiretsky 4d6f99f0d4 Fix uuid.
13 years ago
Mike Hiretsky 43b2beb7d1 Fix uuid.
13 years ago
Mike Hiretsky 2b0bbc4750 Fix work with uuid.
13 years ago
Mike Hiretsky 52880b957f Fix grub partnumber.
13 years ago
Mike Hiretsky c6fc50e0e0 Add detect type of partition (primary,logical and etc)
13 years ago
Mike Hiretsky ae58a01e8a Syntax bugfix.
13 years ago
Mike Hiretsky 06bb8060de Add variable for detect os using lvm and mdadm.
13 years ago
Mike Hiretsky da2c15f909 Add cmdline domdadm and dolvm for boot.
13 years ago
Mike Hiretsky f1a1b077b1 Fix check boot record device.
13 years ago
Mike Hiretsky ec86249e99 Add condition for grub install.
13 years ago
Mike Hiretsky 50e35f622a Fix get part table.
13 years ago
Mike Hiretsky 1dc58d534f Add device type info.
13 years ago
Mike Hiretsky d68c86a6e0 Add determine symlink on device.
13 years ago
Mike Hiretsky de8725d962 Merge branch 'master' into lvmraid
13 years ago
Mike Hiretsky a33b762293 Fix grub2 installation.
13 years ago
Mike Hiretsky 3b42713364 Fix detect install root type.
13 years ago
Mike Hiretsky d8d30f0346 Fix mountDirectory function.
13 years ago
Mike Hiretsky cc02c7d930 Fix get partition table.
13 years ago
Mike Hiretsky 9ddfc64129 Add variable about partition table.
13 years ago
Mike Hiretsky 7cbc013850 Fix change ID.
13 years ago
Mike Hiretsky 14fdb67439 Fix missed conflict.
13 years ago
Mike Hiretsky ca7ea2df67 Merge branch 'master' into lvmraid
13 years ago
Mike Hiretsky 068c4c5077 Update change systemID.
13 years ago
Mike Hiretsky 39c58a20a1 Merge branch 'netsetup' into lvmraid
13 years ago
Mike Hiretsky 8dec130d7c Two day realization of netsetup.
13 years ago
Mike Hiretsky 5b724f8c4b Rewrite fill method of device and disk hash variables.
13 years ago

@ -25,7 +25,8 @@ import sys
import operator
from cl_utils import runOsCommand,isMount,removeDir,typeFile,pathJoin, \
process,getRunCommands,getTupleVersion,cmpVersion, \
detectDeviceForPartition, getProgPath,listDirectory
detectDeviceForPartition, getProgPath,listDirectory, \
checkUtils,STDOUT,getUdevDeviceInfo, countPartitions
from cl_vars_share import varsShare
from shutil import copyfile,copytree
from cl_template import _terms
@ -103,6 +104,8 @@ class DistributiveError(Exception):
class DistributiveRepository:
varsShare = varsShare()
contentCache = {}
marches = ['i686','x86_64']
extensiton = ['iso','tar.bz2','tar.gz','tar.7z','tar.lzma']
@ -129,17 +132,21 @@ class DistributiveRepository:
else:
return {}
def _getfromcontent(self,filename):
def _getfromcontent(self,filename,addFunc=None):
"""Get info from content"""
origfilename = filename
if filename in DistributiveRepository.contentCache:
return DistributiveRepository.contentCache[filename]
varsShare = self.varsShare
distr = None
# may be directory is isodir (directory which contains iso image)
extname = "isodir"
try:
if filename.startswith('/dev'):
distr = IsoDistributive(filename)
if not distr.probe() and filename.startswith('/dev'):
distr.close()
distr = None
distr = PartitionDistributive(filename)
else:
distr = IsoDistributive(filename)
filename = distr.convertToDirectory().directory
except Exception,e:
extname = "dir"
@ -172,15 +179,18 @@ class DistributiveRepository:
d['build'] = os_linux_build[-1]
else:
d['build'] = ""
if addFunc:
d = addFunc(filename,d)
if distr:
distr.close()
DistributiveRepository.contentCache[origfilename] = d
return d
def _getdistrinfo(self,filename):
"""Get information by distributive"""
varsShare = self.varsShare
# if filename is directory
if path.isdir(filename):
if not path.isfile(filename):
return self._getfromcontent(filename)
else:
match = self.reDistName.match(filename)
@ -229,6 +239,8 @@ class DistributiveRepository:
return [pathname]
elif path.exists(path.join(pathname,'livecd')):
return [pathname]
elif pathname.startswith('/dev/'):
return [pathname]
else:
# discard inner directories
return filter(lambda x:not path.isdir( path.join(pathname,x)),
@ -248,8 +260,10 @@ class DistributiveRepository:
def getDistributiveByFile(self,filename):
"""Get Distributive object by filename"""
# MAGIC_COMPRESS 0x000004 Check inside compressed files
tf = typeFile(magic=0x4)
tf = typeFile(magic=0x6)
ftype = tf.getMType(filename)
if "block special" in ftype:
return IsoDistributive(filename)
if "ISO 9660 CD-ROM" in ftype:
return IsoDistributive(filename)
elif "7-zip" in ftype or \
@ -512,18 +526,18 @@ class Distributive(object, SignalInterrupt):
" '%s' " %fromdir + _("to") +\
" '%s':\n%s" %(todir,errmes))
def _mountToBind(self,srcDirectory,destDirectory,mountopts="-o bind"):
def _mountToBind(self,srcDirectory,destDirectory):
"""Mount srcDirectory to destDirectory"""
res,errmes = self.runOsCommand("/bin/mount %s %s %s"%
(mountopts,srcDirectory,destDirectory))
if res == 0:
mount = process('/bin/mount',"-o","bind",srcDirectory,destDirectory,
stderr=STDOUT)
if mount.success():
return True
else:
try:
os.rmdir(destDirectory)
except:
pass
raise DistributiveError(self.mountError%(srcDirectory,errmes))
raise DistributiveError(self.mountError%(srcDirectory,mount.read()))
def performFormat(self):
pass
@ -557,27 +571,29 @@ class Distributive(object, SignalInterrupt):
if isMount(directory):
raise DistributiveError(_("Cann't mount to directory: %s\n")\
%directory+ _("Directory already mounted"))
res,errmes = self.runOsCommand("/bin/mount %s %s %s"%
(mountopts,file,directory))
if res == 0:
mountopts = filter(lambda x:x,
mountopts.split(" "))
mountProcess = process('/bin/mount',file,directory,*mountopts,
stderr=STDOUT)
if mountProcess.success():
return True
else:
try:
self._removeDirectory(directory)
except:
pass
raise DistributiveError(self.mountError%(file,errmes))
raise DistributiveError(self.mountError%(file,mountProcess.read()))
def _umountDirectory(self,directory):
"""Umount directory"""
if isMount(directory):
for wait in [0,0.5,2,5]:
sleep(wait)
res,errmes = self.runOsCommand("/bin/umount %s"%directory)
if res == 0:
processUmount = process('/bin/umount',directory,stderr=STDOUT)
if processUmount.success():
return True
raise DistributiveError(_("Cann't umount") + " %s:\n%s"%
(directory,errmes))
(directory,processUmount.read()))
else:
return True
@ -680,7 +696,7 @@ class MultiPartitions:
return map(lambda x: x.systemId, self.listPartitions)
def getPartitionTable(self):
"""Get systemID for change [msdos,gpt,...]"""
"""Get systemID for change [dos,gpt,...]"""
return map(lambda x: x.partitionTable, self.listPartitions)
def getIsFormat(self):
@ -771,7 +787,7 @@ class PartitionDistributive(Distributive):
if "ntfs" in opts:
source_dir = isMount(partition)
if source_dir:
self._mountToDirectory(source_dir,directory,"-o bind")
self._mountToBind(source_dir,directory)
return
self._mountToDirectory(partition,directory,opts)
@ -850,6 +866,8 @@ class PartitionDistributive(Distributive):
def formatAllPartitions(self):
"""Format all partitions"""
FS,DEV,NEEDFORMAT,NEWID,PARTTABLE = 0,1,2,3,4
# get all information to matrix
dataPartitions = zip(self.multipartition.getFileSystems() +\
[self.fileSystem],
self.multipartition.getPartitions() + \
@ -860,21 +878,24 @@ class PartitionDistributive(Distributive):
[self.systemId],
self.multipartition.getPartitionTable() + \
[self.partitionTable])
formatPartitions = map(lambda x: (x[0],x[1]),
filter(lambda x: x[2] and x[0]!="bind",
dataPartitions))
# get partition which need format
formatPartitions = map(lambda x: (x[FS],x[DEV]),
filter(lambda x: x[NEEDFORMAT] and x[FS]!="bind",
dataPartitions))
# format all get partition
for fileSystem, dev in formatPartitions:
if fileSystem=="swap":
self.formatSwapPartition(dev)
else:
if dev == self.partition:
self.formatPartition(dev, format=fileSystem,
label=self.rootLabel)
label=self.rootLabel)
else:
self.formatPartition(dev, format=fileSystem)
changeidPartitions = map(lambda x: (x[3],x[1],x[4]),
filter(lambda x: x[3],
dataPartitions))
# change system id for partitions
changeidPartitions = map(lambda x: (x[NEWID],x[DEV],x[PARTTABLE]),
filter(lambda x: x[NEWID],
dataPartitions))
for systemid, dev, partTable in changeidPartitions:
self.changeSystemID(dev,systemid,partTable)
return True
@ -919,53 +940,42 @@ class PartitionDistributive(Distributive):
label=self.rootLabel)
def changeSystemID(self,dev,systemid,parttable):
parentDir = path.split(dev)[0]
reDeviceSplit = re.compile("^(.*/)?(.*?)(\d+)$")
"""Change partition id, specified by systemid"""
deviceName = detectDeviceForPartition(dev)
if deviceName is None:
raise DistributiveError(_("Can not determine parent device for %s")%dev)
fdiskProg = getProgPath("/sbin/fdisk")
gdiskProg = getProgPath("/usr/sbin/gdisk")
for prog,name in [(fdiskProg,"fdisk"),(gdiskProg,"gdisk")]:
if not prog:
raise DistributiveError(_("Can not find '%s'")%name)
if parttable == "msdos":
pipe = Popen([fdiskProg,
path.join('/dev',deviceName)],
raise DistributiveError(
_("Can not determine parent device for %s")%dev)
# device hasn't any partition
elif deviceName == "":
return True
fdiskProg, gdiskProg = checkUtils('/sbin/fdisk','/usr/sbin/gdisk')
partitionNumber = getUdevDeviceInfo(name=dev).get('ID_PART_ENTRY_NUMBER','')
devicePartitionCount = countPartitions(deviceName)
if deviceName and not partitionNumber:
raise DistributiveError(
_("Can not determine partition number for %s")%dev)
if parttable == "dos":
fdisk = process(fdiskProg,deviceName,stderr=STDOUT)
pipe = Popen([fdiskProg,deviceName],
stdin=PIPE, stdout=PIPE,stderr=PIPE)
if len(filter(lambda x: deviceName in x and deviceName != x,
listDirectory('/dev'))) > 1:
numPart = reDeviceSplit.search(dev)
if numPart:
numPart = numPart.groups()[-1]
else:
pipe.stdin.close()
raise DistributiveError(
_("Can not determine partition number for %s")%dev)
pipe.stdin.write("t\n%s\n%s\nw\n"%(numPart,systemid))
if devicePartitionCount > 1:
pipe.stdin.write("t\n%s\n%s\nw\n"%(partitionNumber,
systemid))
else:
pipe.stdin.write("t\n%s\nw\n"%systemid)
pipe.stdin.close()
pipe.wait()
if parttable == "gpt":
pipe = Popen([gdiskProg,
path.join('/dev',deviceName)],
elif parttable == "gpt":
pipe = Popen([gdiskProg,deviceName],
stdin=PIPE, stdout=PIPE,stderr=PIPE)
if len(filter(lambda x: deviceName in x and deviceName != x,
listDirectory('/dev'))) > 1:
numPart = reDeviceSplit.search(dev)
if numPart:
numPart = numPart.groups()[-1]
else:
pipe.stdin.close()
raise DistributiveError(
_("Can not determine partition number for %s")%dev)
pipe.stdin.write("t\n%s\n%s\nw\ny\n"%(numPart,systemid))
if devicePartitionCount > 1:
pipe.stdin.write("t\n%s\n%s\nw\ny\n"%(devicePartitionCount,
systemid))
else:
pipe.stdin.write("t\n%s\nw\n\y"%systemid)
pipe.stdin.write("t\n%s\nw\ny\n"%systemid)
pipe.stdin.close()
pipe.wait()
return True
def formatSwapPartition(self, dev):
"""Format swap partition"""
@ -1159,6 +1169,15 @@ class IsoDistributive(Distributive):
self.exclude = [] if not exclude else exclude
self.compress = compress
def probe(self):
"""Check directory for iso content"""
try:
pathname = self.getIsoContentDirectory()
except:
return False
return path.exists(path.join(pathname,"syslinux")) and \
path.exists(path.join(pathname,"isolinux"))
def _mountIso(self,file,directory):
if self.file != self.mdirectory:
self._makeDirectory(directory)

@ -24,8 +24,11 @@ from os import path
from os import readlink,access,R_OK
from cl_utils import isMount,typeFile,getTupleVersion,pathJoin,isFstabMount,\
listDirectory, getAvailableVideo, getUUIDDict, \
getUdevDeviceInfo, getPartitionDevice, getPartitionSize, \
isPkgInstalled, process, checkUtils, readLinesFile, \
lspci, getPartitionSize, getInstalledVideo
FStab, lspci, getInstalledVideo,getDeviceType, \
getPartitionType, getOsProberHash, getProgPath, \
getRaidPartitions, getLvmPartitions, getLvmGroups
from cl_distr import DistributiveRepository,PartitionDistributive
from cl_fill import clLocale
from operator import itemgetter
@ -45,6 +48,8 @@ class fillVars(object, glob_attr):
"/opt", "/proc", "/sbin",
"/sys", "/usr", "/var"]
reWrongDevice = re.compile("|".join(['^fd','^ram','^loop']))
def removeFloppy(self):
"""Remove floopy device and return floppyData"""
floppyPath = '/dev/fd1'
@ -225,6 +230,10 @@ class fillVars(object, glob_attr):
listInterfacesInfo))
def get_os_device_hash(self):
def onlyDisk(devpath):
prop = getUdevDeviceInfo(devpath)
return prop.get("ID_TYPE","")=="disk" and \
prop.get("DEVTYPE","")=="disk"
diskIdPath = '/dev/disk/by-id'
if path.exists(diskIdPath):
usbdevices = \
@ -232,34 +241,23 @@ class fillVars(object, glob_attr):
filter(lambda x: x.startswith('usb-'),listDirectory(diskIdPath)))
else:
usbdevices = []
reWrongDevice = re.compile("|".join(['sr','fd','ram','loop']))
devices = filter( lambda x: not reWrongDevice.search(x),
listDirectory('/sys/block'))
sysBlockPath = '/sys/block'
devices = map(lambda x:path.join(sysBlockPath,x),
filter(lambda x: onlyDisk(path.join(sysBlockPath,x)),
filter(lambda x: not self.reWrongDevice.search(x),
listDirectory(sysBlockPath))))
device_hash = {}
execParted = self.getProgPath("/usr/sbin/parted")
if not execParted:
cl_overriding.printERROR(_("Command not found '%s'")%"parted")
cl_overriding.exit(1)
for mapnum,device in enumerate(sorted(devices,key=self.separateDevice)):
if device.startswith('cciss'):
device = device.replace('!','/')
props = getUdevDeviceInfo(device)
if not "DEVNAME" in props:
continue
device = props['DEVNAME']
device_hash[device] = {}
device_hash[device]['table'] = props.get('ID_PART_TABLE_TYPE','')
device_hash[device]['map'] = mapnum
device_hash[device]['table'] = None
execStr = '%(prog)s %(device)s print'% \
{'prog':execParted,
'device':"/dev/%s"%device}
floppyData = self.removeFloppy()
res = self._runos(execStr,env={"LANG":"C"})
self.restoreFloppy(floppyData)
if res:
res = map(lambda x:x.rpartition("Partition Table:")[2],
filter(lambda x:x.startswith("Partition Table:"),
res))
if res:
device_hash[device]['table'] = res[-1].strip()
if device in usbdevices:
removablePath = '/sys/block/%s/removable'%device
if path.basename(device) in usbdevices:
removablePath = '/sys/block/%s/removable'%path.basename(device)
if os.access(removablePath,R_OK) and \
open(removablePath,'r').read().strip() == "1":
devtype = "flash"
@ -271,170 +269,80 @@ class fillVars(object, glob_attr):
return device_hash
def get_os_disk_hash(self):
# check command existing
for util in ("/sbin/fdisk","/usr/sbin/gdisk","/sbin/blkid",
"/usr/sbin/parted"):
utilPath = self.getProgPath(util)
if not utilPath:
cl_overriding.printERROR(_("Command not found '%s'")%
path.basename(util))
cl_overriding.exit(1)
reSdaPart = \
re.compile("^/dev/(sd[a-z])(\d+)|/dev/(cciss/c\dd\d+)p(\d+)$")
"""Get information about disk, which use for installation"""
def selfOrPartition(devpath):
"""Return self device or partitions if it has them"""
# search partition in device
partitions = \
filter(lambda x:x.startswith(path.basename(devpath)),
listDirectory(devpath))
if partitions:
return filter(lambda x:x,
map(lambda x:selfOrPartition(path.join(devpath,x)),
partitions))
else:
return devpath
# refresh LVM
vgscan = getProgPath('/sbin/vgscan')
vgchange = getProgPath('/sbin/vgchange')
lvchange = getProgPath('/sbin/lvchange')
if vgscan and vgchange and lvchange:
process(vgscan).success()
process(vgchange,'-ay','--refresh').success()
for group in getLvmGroups():
process(lvchange,'-ay','--refresh',group).success()
devicesHash = self.Get('os_device_hash')
devices = devicesHash.keys()
disksDevs = reduce( lambda x,y: x +
map( lambda x: ["/dev/%s"%x.replace('!','/'),y],
filter(lambda x: y in x.replace('!','/'),
listDirectory('/sys/block/%s'%y.replace('/','!')))),
devices, [] )
disks = map(lambda x:x[0],disksDevs)
disksDevs = dict(disksDevs)
sysBlockPath = '/sys/block'
new_disks = reduce(lambda x,y:x+ ([y] if type(y) == str else y),
map(lambda x:selfOrPartition(path.join(sysBlockPath,x)),
filter(lambda x: not self.reWrongDevice.search(x),
listDirectory(sysBlockPath))),[])
disk_hash = {}
# fill grub info
for dev in sorted(disks):
disk_hash[dev] = {}
match = reSdaPart.match(dev)
if match:
if match.groups()[0] and match.groups()[0] in devicesHash:
disk_hash[dev]['grub'] = "%d,%d" % \
(int(devicesHash[match.groups()[0]]['map']),
int(match.groups()[1])-1)
elif match.groups()[2] in devicesHash:
disk_hash[dev]['grub'] = "%d,%d" % \
(int(devicesHash[match.groups()[2]]['map']),
int(match.groups()[3])-1)
curDevice = None
execFdisk = self.getProgPath("/sbin/fdisk")
execGdisk = self.getProgPath("/usr/sbin/gdisk")
# getting id
for device in devices:
if devicesHash[device]['table'] == 'msdos':
execStr = '%s -l %s'%(execFdisk,"/dev/%s"%device)
res = self._runos(execStr,env={"LANG":"C"})
if res is False:
cl_overriding.printERROR(_("Cann't execute '%s'")%execStr)
cl_overriding.exit(1)
partedLines = filter(lambda x: x.startswith('/dev/'),res or [] )
partedMatrix = map(lambda x: filter(lambda y: y and y!="*",
x.split())[:6],
partedLines)
for part,nm,nm,nm,sysid,nm in \
filter(lambda x:len(x)>5,partedMatrix):
if not part in disk_hash:
disk_hash[part] = {}
disk_hash[part]['id'] = sysid
disk_hash[part]['table'] = 'msdos'
elif devicesHash[device]['table'] == 'gpt':
execStr = '%s -l %s'%(execGdisk,"/dev/%s"%device)
res = self._runos(execStr,env={"LANG":"C"})
if res is False:
cl_overriding.printERROR(_("Cann't execute '%s'")%execStr)
cl_overriding.exit(1)
partTemplate = "/dev/%sp%s" if "cciss" in device else "/dev/%s%s"
for dev,partid in filter(lambda x:x[0] in disk_hash,
map(lambda x:[partTemplate%(device,x[0]),x[1]],
map(lambda x:x.split()[0:6:5],
reduce(lambda x,y:x+[y] \
if x or y.startswith("Number") else x,
res,[])[1:]))):
disk_hash[dev]['id'] = partid
disk_hash[dev]['table'] = 'gpt'
# parse all parted lines started with Disk and started with number
floppyData = self.removeFloppy()
execProg = self.getProgPath("/usr/sbin/parted")
execStr = '%s -l'%execProg
res = self._runos(execStr,env={"LANG":"C"})
self.restoreFloppy(floppyData)
if res is False:
cl_overriding.printERROR(_("Cann't execute '%s'")%execStr)
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]
fstab = FStab('/etc/fstab')
raidUsedDisks = []
lvmUsedDisks = []
for disk in new_disks:
props = getUdevDeviceInfo(disk)
if not "DEVNAME" in props:
continue
# if first part is number then it is partition description
if parts[0].isdigit():
# part name it is devicename + partition number
if "cciss" in curDevice:
partition = "%sp%s"%(curDevice,parts[0])
else:
partition = curDevice + parts[0]
# create entry if hash hasn't it
if not partition in disk_hash:
disk_hash[partition] = {}
if disk_hash[partition].get('table',None) == "gpt":
disk_hash[partition]['part'] = "gpt"
if len(parts)>4 and "swap" in parts[4]:
disk_hash[partition]['format'] = 'swap'
else:
disk_hash[partition]['part'] = parts[4]
if len(parts)>5 and "swap" in parts[5]:
disk_hash[partition]['format'] = 'swap'
disk_hash[partition]['size'] = getPartitionSize(partition)
# fill format, name and uuid
execStr = self.getProgPath('/sbin/blkid')
res = self._runos(execStr)
if res is False:
cl_overriding.printERROR(_("Cann't execute '%s'")%execStr)
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]
mapUuidDev = getUUIDDict()
mapDevUuid = dict(zip(mapUuidDev.values(),mapUuidDev.keys()))
mountOptionsList = \
filter(lambda x: x.strip() and not x.strip().startswith('#'),
open("/etc/fstab").readlines())
# split all string by columns and discard string which has less that 4
# columns
mountOptionsList = \
map(lambda x:[mapUuidDev.get(x[0],x[0])]+x[1:4],
filter(lambda x: len(x)>=4,
map(lambda x: filter(lambda x: x ,
x.replace('\t',' ').split(' ')),
mountOptionsList)))
# get dev which has ntfs filesystem
mountFormatList = \
filter(lambda x: x[0] in disk_hash.keys() \
and x[1] in ("ntfs","ntfs-3g"),
map(lambda y: (y[0],y[2]), mountOptionsList))
# split options and discard rw opt
mountOptionsList = \
filter(lambda x: x[0] in disk_hash.keys(),
map(lambda y: (y[0],filter(lambda z: z!="rw",
y[3].split(','))),
mountOptionsList))
dictOptionList = dict(mountOptionsList)
dictFormatList = dict(mountFormatList)
for dev in disk_hash.keys():
if dev in dictOptionList:
disk_hash[dev]['options'] = ",".join(dictOptionList[dev])
if dev in dictFormatList and "format" in disk_hash[dev] and \
disk_hash[dev]['format'] in ("ntfs","ntfs-3g"):
disk_hash[dev]['format'] = dictFormatList[dev]
devName = props['DEVNAME']
dev_hash = {}
dev_hash['uuid'] = props.get('ID_FS_UUID','')
dev_hash['format'] = props.get('FSTAB_TYPE') or \
fstab.getBy(what=fstab.TYPE,eq=devName) or \
props.get('ID_FS_TYPE','')
dev_hash['name'] = props.get('ID_FS_LABEL','')
dev_hash['table'] = props.get('ID_PART_ENTRY_SCHEME','')
dev_hash['type'] = getDeviceType(disk)
dev_hash['id'] =props.get('ID_PART_ENTRY_TYPE','').partition("x")[2]
devParent = getPartitionDevice(disk)
dev_hash['parent'] = devParent
dev_hash['part'] = getPartitionType(props)
dev_hash['options'] = fstab.getBy(what=fstab.OPTS,eq=devName) or ""
dev_hash['size'] = getPartitionSize(disk)
if devParent in devicesHash and 'ID_PART_ENTRY_NUMBER' in props:
dev_hash['grub'] = "%s,%d"%(devicesHash[devParent]['map'],
int(props['ID_PART_ENTRY_NUMBER'])-1)
else:
dev_hash['grub'] = ""
disk_hash[devName] = dev_hash
if "raid" in dev_hash['type']:
raidUsedDisks.extend(map(lambda x:(devName,x),getRaidPartitions(disk)))
if dev_hash['type'].endswith("lvm"):
prop = getUdevDeviceInfo(path=disk)
lvmUsedDisks.extend(map(lambda x:(devName,x),
getLvmPartitions(prop.get('DM_VG_NAME',''),
prop.get('DM_LV_NAME',''))))
for disk,part in raidUsedDisks:
if part in disk_hash:
disk_hash[part]['type'] = "%s-raidmember(%s)"%(
disk_hash[part]['type'],disk)
for disk,part in lvmUsedDisks:
if part in disk_hash:
disk_hash[part]['type'] = "%s-lvmmember(%s)"%(
disk_hash[part]['type'],disk)
return disk_hash
def separateDevice(self,device):
@ -456,7 +364,7 @@ class fillVars(object, glob_attr):
"""List id for partition after installation"""
diskHash = self.Get('os_disk_hash')
def getIdByFS(fs,parttable,oldid):
if parttable == "msdos":
if parttable == "dos":
return PartitionDistributive.formatId.get(fs,oldid)
elif parttable == "gpt":
return PartitionDistributive.formatIdGpt.get(fs,oldid)
@ -489,18 +397,10 @@ class fillVars(object, glob_attr):
return self.Get('os_disk_dev')
def get_os_install_disk_uuid(self):
"""List uudi for partition devices"""
devuuid = '/dev/disk/by-uuid'
"""List uuid for partition devices"""
diskDev = self.Get('os_disk_dev')
if path.exists(devuuid):
hashUUID = dict(
map(lambda x:(path.normpath(path.join(devuuid,os.readlink(x))),
path.basename(x)),
filter(path.islink,
map(lambda x:path.join(devuuid,x),
listDirectory(devuuid)))))
return map(lambda x:hashUUID.get(x,""),diskDev)
return [""]*len(diskDev)
hashUUID = getUUIDDict(revers=True)
return map(lambda x:hashUUID.get(x,"")[5:],diskDev)
def get_os_install_disk_options(self):
"""List mount options for partition devices of installed os"""
@ -510,27 +410,32 @@ class fillVars(object, glob_attr):
"""List mounted points for installed system"""
rootdev = self.Get('os_install_root_dev')
disk_hash = self.Get('os_disk_hash')
fstabHasSwap = isFstabMount('swap')
fstab = FStab('/etc/fstab')
fstabHasSwap = bool(fstab.isExists(what=FStab.TYPE,eq="swap"))
def getMountPoint(disk):
"""Get mount point for disk. If fstab not contains swap then
for swap use all swap formated partition"""
if disk == rootdev:
return "/"
elif not fstabHasSwap and "format" in disk_hash[disk] and \
"swap" in disk_hash[disk]['format']:
return "swap"
else:
mount_point = isFstabMount(disk)
mount_point = fstab.getBy(eq=disk)
if mount_point in self.nonTransferedDirs:
return ""
else:
return mount_point
return map(lambda x: getMountPoint(x),
sorted(self.Get('os_disk_hash').keys(),
key=self.separateDevice))
sorted(
self.Get('os_disk_hash').keys(),key=self.separateDevice))
def get_os_disk_mount(self):
"""List mounted points for current operation system"""
disk_hash = self.Get('os_disk_hash')
return map(lambda x: isFstabMount(x) or "",
fstab = FStab('/etc/fstab')
rootdev = self.Get('os_root_dev')
return map(lambda x: '/' if x == rootdev else fstab.getBy(eq=x) or "",
sorted(self.Get('os_disk_hash').keys(),
key=self.separateDevice))
@ -577,6 +482,10 @@ class fillVars(object, glob_attr):
"""Type of partition devices (primary, extended or logical)"""
return self.getAttributeFromHash('os_disk_hash','part')
def get_os_disk_table(self):
"""Partition table for this partition"""
return self.getAttributeFromHash('os_disk_hash','table')
def get_os_install_disk_perform_format(self):
"""Needformat partitions"""
return self.getAttributeFromHash('os_disk_hash','needformat')
@ -585,6 +494,46 @@ class fillVars(object, glob_attr):
"""Partition size"""
return self.getAttributeFromHash('os_disk_hash','size')
def get_os_disk_type(self):
"""Partition type"""
return self.getAttributeFromHash('os_disk_hash','type')
def get_os_disk_content(self):
"""Partition content"""
distrRep = DistributiveRepository()
osProberHash = getOsProberHash(getContentFunc=distrRep._getfromcontent)
devicesHash = self.Get('os_device_hash')
def detectContent(devName,devType,devParent,mountPoint):
if mountPoint == '/':
return "{short}-{march}{build}".format(
short=self.Get('os_linux_shortname'),
march=self.Get('os_arch_machine'),
build="-%s"%(self.Get('os_linux_build') if
self.Get('os_linux_build') else
self.Get('os_linux_ver')))
content = osProberHash.get(devName,'')
if not content and ((devParent in devicesHash and \
devicesHash[devParent]['type'] == "flash") or
"cdrom" in devType or devType.endswith('raid') or
devType.endswith('lvm')):
dataInfo = distrRep._getfromcontent(devName)
if "build" in dataInfo and dataInfo['build']:
if "cdrom" in devType:
dataInfo['livetype'] = " livecd"
elif devType.endswith('raid') or devType.endswith('lvm'):
dataInfo['livetype'] = ""
else:
dataInfo['livetype'] = " liveusb"
content = \
"{name}-{march}-{build}{livetype}".format(
**dataInfo)
return content
return map(lambda x:detectContent(x[0],x[1],x[2],x[3]),
zip(self.Get('os_disk_dev'),
self.Get('os_disk_type'),
self.getAttributeFromHash('os_disk_hash','parent'),
self.Get('os_disk_mount')))
def get_os_disk_name(self):
"""Label of partitions"""
return self.getAttributeFromHash('os_disk_hash','name')
@ -602,10 +551,14 @@ class fillVars(object, glob_attr):
"""Map number for grub"""
return self.getAttributeFromHash('os_device_hash','map')
def get_os_device_table(self):
"""Table on device"""
return self.getAttributeFromHash('os_device_hash','table')
def get_os_install_grub_devicemap_conf(self):
"""Content of device.map file for grub"""
rootType = self.Get('os_install_root_type')
return "\n".join(map(lambda x: "(hd%s) /dev/%s" % (x[0],x[1]),
return "\n".join(map(lambda x: "(hd%s) %s" % (x[0],x[1]),
filter(lambda x:x[2] == rootType,
zip(self.Get('os_device_map'),
self.Get('os_device_dev'),
@ -735,13 +688,31 @@ class fillVars(object, glob_attr):
return res.groups()[0]
return "cfq"
def get_os_install_lvm_set(self):
"""Using lvm"""
typeRoot = \
self.selectVar("os_disk_type",where="os_install_disk_mount",
eq="/")
return "on" if "lvm" in typeRoot else "off"
def get_os_install_mdadm_set(self):
"""Using mdadm"""
typeRoot = \
self.selectVar("os_disk_type",where="os_install_disk_mount",
eq="/")
return "on" if "raid" in typeRoot else "off"
def get_os_install_kernel_attr(self):
"""Kernel attributes"""
# on usb-hdd install must be "delay=5"
attr = ""
if self.Get('os_install_root_type') == 'usb-hdd':
return " scandelay=5"
else:
return ""
attr = " scandelay=5"
if self.Get('os_install_mdadm_set') == 'on':
attr += " domdadm"
if self.Get('os_install_lvm_set') == 'on':
attr += " dolvm"
return attr
def get_os_install_kernel_resume(self):
"""install kernel resume parameter"""
@ -765,8 +736,13 @@ class fillVars(object, glob_attr):
livedistr = ['/mnt/cdrom']
else:
livedistr = []
return ['/var/calculate/remote/linux', '/var/calculate/linux',
'/usr/calculate/share/linux'] + livedistr
livedistr += \
map(lambda x:x[0],
filter(lambda x:" live" in x[1],
zip(self.Get('os_disk_dev'),
self.Get('os_disk_content'))))
return ['/var/calculate/remote/linux',
'/var/calculate/linux'] + livedistr
def getImage(self,scratch,rootType,imagePath,archMachine,
shortName,linuxVer=None):
@ -775,7 +751,9 @@ class fillVars(object, glob_attr):
discardType = ["dir"]
else:
discardType = []
distRep = DistributiveRepository(self.Get('cl_image_path'))
if type(imagePath) == str:
imagePath = [imagePath]
distRep = DistributiveRepository(imagePath)
return distRep.getBestDistributive(march=archMachine,
shortname=shortName.lower(),
discardType=discardType,
@ -1153,10 +1131,12 @@ class fillVars(object, glob_attr):
def get_os_install_root_type(self):
"""Type of device for install"""
rootdev = self.Get('os_install_root_dev')
devicetype = getPartitionDevice(
getUdevDeviceInfo(name=rootdev).get('DEVPATH',''))
devicetype = map(lambda x: x[1],
filter(lambda x:x[0] in rootdev,
zip(self.Get('os_device_dev'),
self.Get('os_device_type'))))
filter(lambda x:x[0] == devicetype,
zip(self.Get('os_device_dev'),
self.Get('os_device_type'))))
if devicetype:
return devicetype[0]
else:
@ -1391,8 +1371,7 @@ class fillVars(object, glob_attr):
return self.Get('cl_autoupdate_set')
def get_cl_install_kernel_uid(self):
mapDevUuid = getUUIDDict(revers=True)
return mapDevUuid.get(self.Get('os_install_root_dev'),"")[5:13]
return self.getKernelUid(self.Get('os_install_root_dev'))
def get_os_nvidia_mask(self):
nvidiaeclass = pathJoin(self.Get('cl_chroot_path'),
@ -1448,10 +1427,6 @@ class fillVars(object, glob_attr):
return build
return ""
def get_os_device_partition(self):
"""Get partition table list"""
return self.getAttributeFromHash('os_device_hash','table')
def get_os_install_fb_resolution(self):
"""Get current framebuffer resolution"""
textLines = self._runos("/sbin/fbres 2>&1")

@ -26,7 +26,8 @@ from cl_utils import runOsCommand,appendProgramToEnvFile, \
removeProgramToEnvFile,pathJoin, \
scanDirectory,process,getTupleVersion, \
detectDeviceForPartition,listDirectory, \
cmpVersion,STDOUT
cmpVersion,STDOUT,getUdevDeviceInfo, \
getLvmPartitions
from cl_vars_share import varsShare
from cl_kernel_utils import KernelConfig,InitRamFs
@ -598,10 +599,18 @@ class convertDictOpt:
# bind options
if "srcMountPoint" in optProperties:
# bind options
optProperties["srcMountPoint"] = \
path.normpath(optProperties["srcMountPoint"])
if "destMountPoint" in optProperties:
optProperties["destMountPoint"] = \
path.normpath(optProperties["destMountPoint"])
dictOptions = self.getDefaultOptBind().copy()
dictOptions.update(optProperties)
return dictOptions
optDevice = optProperties["dev"]
optProperties["dev"] = \
getUdevDeviceInfo(name=optDevice).get('DEVNAME',optDevice)
optDevice = optProperties["dev"]
dataPart = filter(lambda x: x[0]==optDevice, self.varDiskData)
if not dataPart:
dataPart = [["",False,"","","",""]]
@ -815,6 +824,12 @@ class cl_install(color_print, SignalInterrupt):
return instnextres
return curnextres
def printAllPartitonsTable(self):
"""Print install report"""
title, headerList, dataList = self.generateTableAllPartitionData()
tableObj = tableReport("", headerList, dataList)
tableObj.printReport(False)
def printLocationTables(self):
"""Print install report"""
title, headerList, dataList = self.generateTableMountData()
@ -843,15 +858,18 @@ class cl_install(color_print, SignalInterrupt):
clGet('os_linux_ver'))
mbrDevice = self.clVars.Get('os_install_mbr')
if not mbrDevice in ("","off"):
pathVendor = "/sys/block/%s/device/vendor"%mbrDevice
pathModel = "/sys/block/%s/device/model"%mbrDevice
syspath = getUdevDeviceInfo(name=mbrDevice).get('DEVPATH','')
if not syspath.startswith('/sys'):
syspath = pathJoin('/sys',syspath)
pathVendor = "%s/device/vendor"%syspath
pathModel = "%s/device/model"%syspath
if path.exists(pathVendor) and path.exists(pathModel):
addonMbrInfo = " (%s %s)"% \
(open(pathVendor,'r').read().strip(),
open(pathModel,'r').read().strip())
else:
addonMbrInfo = ""
mbrdisk = "/dev/%s%s"%(clGet('os_install_mbr'),addonMbrInfo)
mbrdisk = "%s%s"%(clGet('os_install_mbr'),addonMbrInfo)
else:
mbrdisk = _("not changed")
@ -939,8 +957,21 @@ class cl_install(color_print, SignalInterrupt):
if update:
cmpres = self.cmpInstallVersion()
if self.clVars.Get('cl_image') and ( not update or cmpres > 0):
self.printSUCCESS(_("Found update")+": %s %s%s%s\n"%
image = self.clVars.Get('cl_image')
if image and ( not update or cmpres > 0):
deviceName = ""
if image.startswith('/dev'):
deviceImage = \
map(lambda x:x[1].rpartition(" ")[2],
filter(lambda x:x[0]==image,
self.clVars.zipVars("os_disk_dev","os_disk_content")))
if deviceImage:
if deviceImage[0] == "livecd":
deviceName = " " + _("on")+" CDROM (%s)"%image
else:
deviceName = " " + _("on")+" USB Flash (%s)"%image
self.printSUCCESS(_("Found update")+deviceName+": %s %s%s%s\n"%
(self.clVars.Get('os_install_linux_name'),
self.clVars.Get('os_install_linux_ver'),
subname,build))
@ -973,11 +1004,7 @@ class cl_install(color_print, SignalInterrupt):
"""Get target distributive by params"""
rootLabelName = "%s-%s"%(self.clVars.Get('os_install_linux_shortname'),
self.clVars.Get('os_install_linux_ver'))
mapDevice = self.clVars.Get('os_device_hash')
mapPartPT = dict(
map(lambda x:[x,mapDevice.get(detectDeviceForPartition(x),
{'table':None})['table']],
self.clVars.Get('os_disk_dev')))
mapPartPT = dict(self.clVars.zipVars("os_disk_dev","os_disk_table"))
if buildermode:
return ScratchPartitionDistributive(disk,mdirectory="/mnt/install",
check=True, fileSystem=fileSystem,
@ -1298,10 +1325,65 @@ class cl_install(color_print, SignalInterrupt):
self.clVars.Get('os_disk_dev'))))
usingExtPart = list(set(usedDevices)&set(extendedPartitions))
if usingExtPart:
self.printERROR(_("Can not use extended partition %s")%
self.printERROR(
_("Imposible to use extended partition %s for installation")%
usingExtPart[0])
return False
# detect using CDROM disks
cdromPartitions = map(lambda x: x[1],
filter(lambda x: "cdrom" in x[0],
zip(self.clVars.Get('os_disk_type'),
self.clVars.Get('os_disk_dev'))))
usingCdromPart = list(set(usedDevices)&set(cdromPartitions))
if usingCdromPart:
self.printERROR(_("Imposible to use CDROM %s for installation")%
usingCdromPart[0])
return False
# detect using RAID member disks
raidMemberData = filter(lambda x: "raidmember" in x[0],
zip(self.clVars.Get('os_disk_type'),
self.clVars.Get('os_disk_dev')))
raidMemberPartitions = map(lambda x:x[1],raidMemberData)
usingRaidMemberPart = list(set(usedDevices)&set(raidMemberPartitions))
if usingRaidMemberPart:
raidMemberData = filter(lambda x:x[1] in usingRaidMemberPart,
raidMemberData)[0][0]
raidMemberData = raidMemberData.rpartition("raidmember(")[2]
raidMemberData = raidMemberData.partition(")")[0]
self.printERROR(_("Imposible to use active {typepart} member"
" {part} for installation").format(
typepart="RAID",part=usingRaidMemberPart[0]))
self.printERROR(
_("For using this partition need to stop RAID %s")%
raidMemberData)
self.printERROR(" mdadm -S %s"%raidMemberData)
return False
# detect using LVM member disks
lvmMemberData = filter(lambda x: "lvmmember" in x[0],
zip(self.clVars.Get('os_disk_type'),
self.clVars.Get('os_disk_dev')))
lvmMemberPartitions = map(lambda x:x[1],lvmMemberData)
usingLvmMemberPart = list(set(usedDevices)&set(lvmMemberPartitions))
if usingLvmMemberPart:
lvmMemberData = filter(lambda x:x[1] in usingLvmMemberPart[0],
lvmMemberData)[0][0]
lvmMemberData = lvmMemberData.rpartition("lvmmember(")[2]
lvmMemberData = lvmMemberData.partition(")")[0]
prop = getUdevDeviceInfo(name=lvmMemberData)
vgName = prop.get('DM_VG_NAME','')
self.printERROR(_("Imposible to use active {typepart} member"
" {part} for installation").format(
typepart="LVM",part=usingLvmMemberPart[0]))
self.printERROR(
_("For using this partition need to remove LVM %s")%
lvmMemberData)
self.printERROR(" vgremove %s"%vgName)
self.printERROR(" pvremove %s"%usingLvmMemberPart[0])
return False
srcMountPoints = map(lambda x:x['srcMountPoint'],listBinds)
destMountPoints = map(lambda x:x['destMountPoint'],listBinds)
wrongBind = filter(lambda x:x in destMountPoints,srcMountPoints)
@ -1372,10 +1454,11 @@ class cl_install(color_print, SignalInterrupt):
builderMode = self.clVars.Get('os_install_scratch') == "on"
clearBuilder = lambda data,isswap: "" if builderMode and isswap != "swap" else data
# get hash from current variables
devMount = dict(map(lambda x:(x[0],
{'mountPoint':clearParam(x[1],x[1]),
'fileSystem':x[2],
'options':clearParam(x[3],x[1]),
DEV,MOUNT,FS,OPTS = 0,1,2,3
devMount = dict(map(lambda x:(x[DEV],
{'mountPoint':clearParam(x[MOUNT],x[MOUNT]),
'fileSystem':x[FS],
'options':clearParam(x[OPTS],x[MOUNT]),
'isFormat':""}),
zip(self.clVars.Get('os_disk_dev'),
self.clVars.Get('os_install_disk_mount'),
@ -1493,6 +1576,49 @@ class cl_install(color_print, SignalInterrupt):
('os_install_disk_options',new_options),
('os_install_bind_path',new_bind_src),
('os_install_bind_mountpoint',new_bind_dest)))
if not self.clVars.Get('os_grub2_path'):
if not self.checkForLegacyGrub():
return False
else:
if not self.checkForGrub2():
return False
return True
def checkForGrub2(self):
"""Check current disk configuration for installation for install
GRUB2"""
bootDiskType = self.varSelect("os_disk_type",
where="os_install_disk_mount", eq="/boot")
rootDiskType = self.varSelect("os_disk_type",
where="os_install_disk_mount", eq="/")
grubDiskType = bootDiskType or rootDiskType
if "lvm-raid" in grubDiskType:
self.printERROR(
_("Grub not support boot from RAID assembled from LVM.")
+ " " +
_("Try use separate /boot partition"))
return False
if grubDiskType.count("raid")>1:
self.printERROR(
_("Grub not support boot from RAID assembled from another RAID.")
+ " " +
_("Try use separate /boot partition"))
return False
return True
def checkForLegacyGrub(self):
"""Check current disk configuration for installation for install
legacy grub"""
bootDiskType = self.varSelect("os_disk_type",
where="os_install_disk_mount", eq="/boot")
rootDiskType = self.varSelect("os_disk_type",
where="os_install_disk_mount", eq="/")
bootDiskType = bootDiskType or rootDiskType
if "lvm" in bootDiskType or "raid" in bootDiskType:
self.printERROR(
_("Legacy grub not support boot from raid or lvm without"
" separate /boot partition"))
return False
return True
def setUsers(self,listUsers):
@ -1504,19 +1630,16 @@ class cl_install(color_print, SignalInterrupt):
self.clVars.Set('cl_migrate_user', migrateUsers, force=True)
return True
def setMBR(self, mbrDisk):
"""Set mbr by param or get from variables"""
def setBR(self, mbrDisk):
"""Set boot record on disk by param or get from variables"""
bootDiskGrub = ""
if mbrDisk == "off":
self.clVars.Set('os_install_mbr',"",force=True)
return True
elif mbrDisk:
listbootDiskGrub = map(lambda x: x[0],
filter(lambda x: "/dev/"+x[0]==mbrDisk,
zip(self.clVars.Get('os_device_dev'),
self.clVars.Get('os_device_map'))))
if filter(lambda x: "/dev/%s"%x == mbrDisk,
if filter(lambda x: x == mbrDisk,
self.clVars.Get('os_device_dev')):
self.clVars.Set('os_install_mbr',mbrDisk[5:], force=True)
self.clVars.Set('os_install_mbr', mbrDisk, force=True)
else:
self.printERROR(_("Cann't found disk '%s'")%mbrDisk)
return False
@ -1566,12 +1689,12 @@ class cl_install(color_print, SignalInterrupt):
return True
def setInstallOptions(self, listDisks, listBinds, listSwaps, listUsers,
mbrDisk):
"""Set install options (set users, disks and mbr"""
brDisk):
"""Set install options (set users, disks and boot record"""
try:
if self.setUsers(listUsers) and \
self.setDisks(listDisks,listBinds,listSwaps) and \
self.setMBR(mbrDisk):
self.setBR(brDisk):
return self.createListOptions()
else:
return False
@ -1601,7 +1724,7 @@ class cl_install(color_print, SignalInterrupt):
return ""
def setActivePartition(self,partition):
"""TODO: don't work with GPT"""
"""TODO: don't work with GPT. Don't work must be rewrite!!!!!"""
reActive = re.compile('^%s\s*[*]'%partition)
device = filter(lambda x:x in partition,
self.clVars.Get('os_device_dev'))
@ -1609,7 +1732,7 @@ class cl_install(color_print, SignalInterrupt):
raise DistributiveError(_("Cann't get parent device"))
device = device[0]
fdiskProcess = process("/sbin/fdisk","-l","/dev/%s"%device)
fdiskProcess = process("/sbin/fdisk","-l",device)
if fdiskProcess.failed():
raise DistributiveError(_("Cann't get device information\n%s")%
fdiskProcess.read())
@ -1617,13 +1740,13 @@ class cl_install(color_print, SignalInterrupt):
grubDisk = self.getFieldByField("grub","mount","/",
secondPrefix="os_install_disk")
if grubDisk and grubDisk.rpartition(',')[2].isdigit():
fdiskProcess = process("/sbin/fdisk", "/dev/%s"%device)
fdiskProcess = process("/sbin/fdisk", device)
fdiskProcess.write("a\n%d\nw\n"%
(int(grubDisk.rpartition(',')[2])+1))
if fdiskProcess.success():
return True
if filter(reActive.search,process("/sbin/fdisk",
"-l","/dev/%s"%device)):
"-l",device)):
return True
raise DistributiveError(_("Cann't set active partition"))
else:
@ -1635,7 +1758,7 @@ class cl_install(color_print, SignalInterrupt):
Perform syslinux installation to flash.
"""
ddProcess = process("/bin/dd","if=/usr/share/syslinux/mbr.bin",
"of=/dev/%s"%self.clVars.Get('os_install_mbr'),
"of=%s"%self.clVars.Get('os_install_mbr'),
stderr=STDOUT)
if ddProcess.failed():
raise DistributiveError(_("Cann't write master boot record\n%s")%
@ -1674,7 +1797,7 @@ class cl_install(color_print, SignalInterrupt):
deviceName = self.varSelect("os_device_dev",where="os_device_map",
eq=int(deviceNumber))
if deviceName:
return ("/dev/%s"%deviceName,partitionNumber)
return (deviceName,partitionNumber)
return (False,False)
def setBiosGrubForBootPartition(self):
@ -1711,7 +1834,7 @@ class cl_install(color_print, SignalInterrupt):
process("sync").success()
grubProcess = process(cmdGrubInstall,
"--boot-directory=%s"%target.getBootDirectory(),
"/dev/%s"%mbrDisk, "-f", stderr=STDOUT)
mbrDisk, "-f", stderr=STDOUT,envdict=os.environ)
if grubProcess.failed():
raise DistributiveError(_("Cann't install bootloader"))
@ -1744,6 +1867,65 @@ class cl_install(color_print, SignalInterrupt):
if grubProcess.failed():
raise DistributiveError(_("Cann't install bootloader"))
def convertTypeToScheme(self,data):
"""Convert os_disk_type to human readable names"""
if type(data) == tuple:
diskScheme, driveType = data
else:
diskScheme, driveType = data,""
res = ""
if diskScheme.endswith("raid-lvm"):
return _("LVM on RAID")
elif "disk-partition" == diskScheme and driveType == "flash":
return _("Partition on flash")
elif "disk-partition" == diskScheme and driveType == "usb-hdd":
return _("Partition on USB-HDD")
elif "disk-partition" == diskScheme:
return _("Partition on disk")
elif "raid-partition" == diskScheme:
return _("Partition on RAID")
elif "raidmember" in diskScheme:
diskScheme = diskScheme.rpartition("raidmember(")[2]
diskScheme = diskScheme.partition(")")[0]
return _("RAID %s member")%diskScheme
elif "lvmmember" in diskScheme:
lvms = []
while "lvmmember" in diskScheme:
diskScheme,op,data = diskScheme.rpartition("lvmmember(")
lvms.append(data.partition(")")[0])
return _("LVM %s member")%",".join(lvms)
elif "disk" == diskScheme:
return _("Disk without partitions")
elif "lvm" in diskScheme:
return _("LVM")
elif "raid" in diskScheme:
return _("RAID")
elif "cdrom" in diskScheme:
return _("CDROM")
else:
return _("Partition")
def generateTableAllPartitionData(self):
"""Generate table for all partitions"""
title = _("Available partitions")
headerList = [_("Size"),_("Device"),_("Label"),_("Mount point"),
_("File system"), _("Type"),_("OS")]
deviceHash = self.clVars.Get('os_device_hash')
diskHash = self.clVars.Get('os_disk_hash')
getTypeByDevice = lambda x: \
deviceHash.get(diskHash[x].get('parent',{}),{}).get('type','')
return title, headerList, zip(self.clVars.Get('os_disk_size'),
self.clVars.Get('os_disk_dev'),
self.clVars.Get('os_disk_name'),
self.clVars.Get('os_disk_mount'),
self.clVars.Get('os_disk_format'),
map(self.convertTypeToScheme,
zip(self.clVars.Get('os_disk_type'),
map(getTypeByDevice,self.clVars.Get('os_disk_dev')))),
self.clVars.Get('os_disk_content'))
def generateTableMountData(self):
"""Get data from print table"""
title = _("Location")
@ -1791,7 +1973,10 @@ class cl_install(color_print, SignalInterrupt):
listMountPoint,
listFileSystem,
listIsFormat,
self.clVars.Get('os_disk_part'),
map(lambda x:x[0] or x[1],
zip(self.clVars.Get('os_disk_part'),
map(self.convertTypeToScheme,
self.clVars.Get('os_disk_type')))),
self.clVars.Get('os_install_disk_mount'))))
return title, headerList, dataList
@ -2171,6 +2356,17 @@ class cl_install(color_print, SignalInterrupt):
raise InstallError(_("Can not migrate users to new system"))
self.printByResult(True)
def checkCorrectBootRecordDisk(self):
"""Check boot record disk"""
mbr = self.clVars.Get('os_install_mbr')
tableOnBootDisk = self.varSelect('os_device_table',
where="os_device_dev",eq=mbr)
if not tableOnBootDisk:
self.printERROR(_("Disk '%s' without partition table cann't "
"contains boot record")%mbr)
return False
return True
def installSystem(self, force=False, bootDisk=None, stdinReadPwd=False,
builder=False, flagSpinner=True, update=False):
"""install System by current variable enviroment"""
@ -2178,6 +2374,8 @@ class cl_install(color_print, SignalInterrupt):
targetDistr = None
error = None
distrCopy = False
if not self.checkCorrectBootRecordDisk():
return False
try:
rootPartdev = self.clVars.Get('os_install_root_dev')
rootPartCmdList = filter(lambda x: x['dev']==rootPartdev,
@ -2407,3 +2605,17 @@ the system") + " (yes/no)"
self.printERROR(_("Package uninstallation failed"))
return False
return True
def setIso(self,isoimage):
"""Set iso image for installation"""
imageData = DistributiveRepository()._getfromcontent(isoimage)
if "name" in imageData and imageData.get('build','') and \
"march" in imageData:
self.clVars.Set('os_install_arch_machine',
imageData['march'],True)
self.setLinuxName(imageData['name'].upper())
self.clVars.Set('cl_image',True)
return True
else:
self.printERROR(_("Wrong image file"))
return False

@ -36,14 +36,9 @@ CMD_OPTIONS = [{'shortOption':"d",
'optVal':"DISK[:[DIR:FILESYSTEM:OPTIONS]]",
'action':'append',
'help':_("the DISK for installation, which mounted to DIR") +
". "
+_("DIR with value 'none' will cancels the mount point transfer")
},
{'shortOption':"b",
'longOption':"bind",
'optVal':"SRC_DIR:DEST_DIR",
'action':'append',
'help':_("bind mount point for instalation")
". " +
_("DIR with value 'none' will cancels the mount point transfer")
+ ". " +_("For creating bind mount point need specify source directory as DISK")
},
{'shortOption':"w",
'longOption':"swap",
@ -62,6 +57,9 @@ CMD_OPTIONS = [{'shortOption':"d",
'choices':['flash','hdd','usb-hdd'],
'help':_("device type for installed system")
},
{'longOption':'iso',
'optVal':"ISO",
'help':_("ISO image for installation")},
{'shortOption':"s",
'longOption':"os",
'optVal':"SYSTEM",
@ -152,7 +150,11 @@ CMD_OPTIONS = [{'shortOption':"d",
{'shortOption':"P",
'help':_("use passwords for the users accounts \
(from standard input)")
}]
},
{'shortOption':'p',
'longOption':"show-partitions",
'help':_("display all partitions")}
]
class OptException(Exception):
pass
@ -197,6 +199,14 @@ class install_cmd(share_cmd):
self.optobj.error(_("incompatible options")+":"+" %s"\
%self.getStringIncompatibleOptions(incompatible+["live"]))
def checkIncompatibleDhcp(self):
"""Check incompatible options for option --dchp"""
incompatible = list(set(self._getNamesAllSetOptions()) &
set(self.optionsDhcpIncompatible))
if incompatible:
self.optobj.error(_("incompatible options")+":"+" %s"\
%self.getStringIncompatibleOptions(incompatible+["dhcp"]))
def checkIncompatibleInstallUninstall(self):
"""Check incompatible options for options --install and --uninstall"""
opts = self._getNamesAllSetOptions()
@ -212,6 +222,8 @@ class install_cmd(share_cmd):
self.checkIncompatibleInstallUninstall()
if values.live:
self.checkIncompatibleLive()
if values.dhcp:
self.checkIncompatibleDhcp()
if not values.v:
if values.filter:
errMsg = _("incorrect option") + ":" + " %s" %"--filter" +\
@ -245,6 +257,7 @@ class install_cmd(share_cmd):
example="default:192.168.1.1"))
if not (values.install or values.uninstall or values.live):
if values.v is False and \
not values.p and \
values.d is None and \
not self.logicObj.clVars.Get('os_install_dev_from'):
self.optobj.error(_("need specify disk by '-d' option"))
@ -256,15 +269,6 @@ class install_cmd(share_cmd):
self.optobj.error(_("option %s:") %"d" +\
" " + _("disk specifing error: '%s'")\
%", ".join(wrongValue))
# check syntax SRC_DIR:DEST_DIR
if values.b:
reTrueBind = re.compile("^[^:]+:[^:]+$")
wrongValue = filter(lambda x: not reTrueBind.match(x),values.b)
if wrongValue:
self.optobj.error(_("option %s:") %"b" +\
" " + _("mount bind specifing error: '%s'")\
%", ".join(wrongValue))
# check syntax SWAP_DISK
if values.w:
reTrueBind = re.compile("^[^:]+$")
@ -354,7 +358,7 @@ class install_cmd(share_cmd):
self.logicObj.clVars.Set('cl_action',
"merge" if live else "system",True)
def checkAndSetInstallOptions(self,diskOptions, swapOptions, bindOptions,
def checkAndSetInstallOptions(self,diskOptions, swapOptions,
usersOptions):
"""Check and set disk, swap and bind cmd options"""
if self.optobj.values.s:
@ -372,6 +376,10 @@ class install_cmd(share_cmd):
self.logicObj.clVars.Set('os_install_root_type',
self.optobj.values.type, True)
if self.optobj.values.iso:
if not self.logicObj.setIso(self.optobj.values.iso):
return False
listDiskOptions = []
listBindOptions = []
listSwapOptions = []
@ -379,8 +387,7 @@ class install_cmd(share_cmd):
listDiskOptions = self._parseOptDisk(diskOptions)
if listDiskOptions is False:
return False
if bindOptions:
listBindOptions = self._parseOptBind(bindOptions)
listBindOptions = self._parseOptBind(diskOptions)
if listBindOptions is False:
return False
if swapOptions:
@ -413,6 +420,7 @@ class install_cmd(share_cmd):
def _parseOptBind(self, listOpt):
"""Parse value cmd option --bind"""
listOpt = filter(lambda x:not x.startswith('/dev/'),listOpt)
listNameOptions = ["srcMountPoint", "destMountPoint"]
lenOptions = len(listNameOptions)
itemOptions = map(lambda x: (x,''), listNameOptions)
@ -435,6 +443,7 @@ class install_cmd(share_cmd):
def _parseOptDisk(self, listOpt):
"""Parse value cmd option --disk"""
listOpt = filter(lambda x:x.startswith('/dev/'),listOpt)
listNameOptions = ["dev","mountPoint","fileSystem","options"]
lenOptions = len(listNameOptions)
itemOptions = map(lambda x: (x,''), listNameOptions)
@ -468,12 +477,17 @@ class install_cmd(share_cmd):
if self.logicObj.installSystem(force=force, bootDisk=bootDisk,
stdinReadPwd=stdinReadPwd, builder=builder,
flagSpinner=flagSpinner,update=update):
self.defaultPrint("\n")
self.defaultPrint(_("To apply changes you have to reboot")+".\n")
if self.logicObj.clVars.Get('os_install_root_type') != "flash":
self.defaultPrint("\n")
self.defaultPrint(_("To apply changes you have to reboot")+
".\n")
return True
else:
return False
def showPartitions(self):
self.logicObj.printAllPartitonsTable()
def configureSystem(self):
"""Run configure system"""
if self.logicObj.configureSystem():

@ -61,9 +61,15 @@ class Data:
# list mounted points for current operation system
os_disk_mount = {}
# partition content
os_disk_content = {}
# list filesystem for partition devices
os_disk_format = {}
# list type (lvm,raid,partition,disk)
os_disk_type = {}
# install list filesystem for partition devices
os_install_disk_format = {}
@ -99,6 +105,9 @@ class Data:
# type of partition devices (primary, extended or logical)
os_disk_part = {}
# partition table on parent device
os_disk_table = {}
# partition size
os_disk_size = {}
@ -114,12 +123,12 @@ class Data:
# device type (hdd,cdrom,usb-flash)
os_device_type = {}
# device partition table
os_device_partition = {}
# map number for grub
os_device_map = {}
# table for device
os_device_table = {}
# content of device.map file for grub
os_install_grub_devicemap_conf = {}
@ -315,6 +324,12 @@ class Data:
# type of device for install
os_install_root_type = {'mode':'w'}
# using lvm
os_install_lvm_set = {}
# using mdadm
os_install_mdadm_set = {}
# proxy server for system
os_install_proxy = {'mode':'w',
'value':''}

@ -52,13 +52,16 @@ if __name__ == "__main__":
# check and set installed options
install.setAction(options.live)
if not (options.live or options.install or options.uninstall):
if not install.checkAndSetInstallOptions(options.d,options.w,options.b,
if not install.checkAndSetInstallOptions(options.d,options.w,
options.u):
sys.exit(1)
# print variables
if options.v or options.filter or options.xml:
install.printVars(options)
sys.exit(0)
if options.p:
install.showPartitions()
sys.exit(0)
# check root
if not install.isRoot():
sys.exit(1)

Loading…
Cancel
Save