Add basic install api.

master3.3
Mike Hiretsky 13 years ago
parent eafaf6db3f
commit e0a057778b

@ -22,7 +22,7 @@ from calculate.lib.cl_vars_share import varsShare
from os import path
from os import readlink,access,R_OK
from calculate.lib.utils.files import (listDirectory, pathJoin,process,
checkUtils, readLinesFile, FStab, getProgPath)
checkUtils, readFile, readLinesFile, FStab, getProgPath)
from calculate.lib.utils.common import (getTupleVersion, getAvailableVideo,
getInstalledVideo, getPasswdUsers)
from calculate.lib.utils.portage import isPkgInstalled
@ -305,6 +305,19 @@ class fillVars(object, varsShare):
devtype = "hdd"
# set detect device type (hdd,flash or usb-hdd)
device_hash[device]['type'] = devtype
devicepath = props.get("DEVPATH","")
if devicepath:
if not devicepath.startswith("/sys"):
devicepath = pathJoin("/sys",devicepath)
pathVendor = "%s/device/vendor"%devicepath
pathModel = "%s/device/model"%devicepath
deviceName = ("%s %s"% \
(readFile(pathVendor).strip(),
readFile(pathModel).strip())).strip()
else:
deviceName = ""
device_hash[device]['name'] = deviceName
return device_hash
def get_os_disk_hash(self):
@ -602,6 +615,10 @@ class fillVars(object, varsShare):
"""Map number for grub"""
return self.getAttributeFromHash('os_device_hash','map')
def get_os_device_name(self):
"""Names of devices"""
return self.getAttributeFromHash('os_device_hash','name')
def get_os_device_table(self):
"""Table on device"""
return self.getAttributeFromHash('os_device_hash','table')

@ -786,7 +786,7 @@ class otherfilesCopy(scanDirectory):
{'src':pathname,'dst':pathJoin(self.target,pathname)})
return True
class cl_install(color_print, SignalInterrupt):
class Install(color_print, SignalInterrupt):
"""Primary class for templates appling and system installation"""
def __init__(self):
@ -1293,27 +1293,25 @@ class cl_install(color_print, SignalInterrupt):
return False
return True
def setDisks(self,listDisks,listBinds,listSwaps):
def setDisks(self,listDisks):
"""Set data for installation partitions"""
convObj = convertDictOpt(self.clVars)
try:
listDisks = map(convObj, listDisks)
# detect previous system if not specified root partition
if not filter(lambda x: x['mountPoint'] == '/',listDisks):
prevRootDev = self.clVars.Get('os_install_dev_from')
if prevRootDev:
listDisks += map(convObj, [{'mountPoint': '',
'options': ['noatime'],
'dev': prevRootDev,
'fileSystem': ''}])
listBinds = map(convObj, listBinds)
listSwaps = map(convObj, listSwaps)
except InstallError,e:
self.printERROR(str(e))
if convObj.listFileSystemCorrupted:
self.printWARNING(_("See 'man mount' for file system") + " "+\
", ".join(convObj.listFileSystemCorrupted))
return False
listSwaps = filter(lambda x:x[0].startswith('/dev') and
x[1] == "swap",listDisks)
listBinds = filter(lambda x:not x[0].startswith('/dev'),listDisks)
listDisks = filter(lambda x:x[0].startswith('/dev') and
x[1] != "swap",listDisks)
listDisks = map(convObj, listDisks)
# detect previous system if not specified root partition
if not filter(lambda x: x['mountPoint'] == '/',listDisks):
prevRootDev = self.clVars.Get('os_install_dev_from')
if prevRootDev:
listDisks += map(convObj, [{'mountPoint': '',
'options': ['noatime'],
'dev': prevRootDev,
'fileSystem': ''}])
listBinds = map(convObj, listBinds)
listSwaps = map(convObj, listSwaps)
# break perform if disk params empty and os_install_dev_from empty
if not (listDisks or listSwaps or listBinds):
return True
@ -1326,18 +1324,16 @@ class cl_install(color_print, SignalInterrupt):
# check mount options for scratch and flash
if filter(lambda x: x != '/', usedMP):
if self.clVars.Get('os_install_scratch') == "on":
self.printERROR(
raise InstallError(
_("Builder mode does not support multipartition install"))
return False
# check specified devices
wrongDevices = list(set(usedDevicesOnlyDisks) - \
set(self.clVars.Get('os_disk_dev')))
wrongDevices = wrongDevices + list(set(usedDevicesOnlySwap) - \
set(self.clVars.Get('os_disk_dev')+["none"]))
if wrongDevices:
self.printERROR(_("Incorrect device '%s'")%wrongDevices[0])
return False
raise InstallError(
_("Incorrect device '%s'")%wrongDevices[0])
# detect using extended partition
extendedPartitions = map(lambda x: x[1],
@ -1346,10 +1342,9 @@ class cl_install(color_print, SignalInterrupt):
self.clVars.Get('os_disk_dev'))))
usingExtPart = list(set(usedDevices)&set(extendedPartitions))
if usingExtPart:
self.printERROR(
raise InstallError(
_("Unable to use the extended partition %s for installation")%
usingExtPart[0])
return False
# detect using CDROM disks
cdromPartitions = map(lambda x: x[1],
@ -1358,9 +1353,9 @@ class cl_install(color_print, SignalInterrupt):
self.clVars.Get('os_disk_dev'))))
usingCdromPart = list(set(usedDevices)&set(cdromPartitions))
if usingCdromPart:
self.printERROR(_("Unable to use CDROM %s for installation")%
raise InstallError(
_("Unable to use CDROM %s for installation")%
usingCdromPart[0])
return False
# detect using RAID member disks
raidMemberData = filter(lambda x: "raidmember" in x[0],
@ -1373,14 +1368,13 @@ class cl_install(color_print, SignalInterrupt):
raidMemberData)[0][0]
raidMemberData = raidMemberData.rpartition("raidmember(")[2]
raidMemberData = raidMemberData.partition(")")[0]
self.printERROR(_("Unable to use active {typepart} member {part} "
raise InstallError([
_("Unable to use active {typepart} member {part} "
"for installation").format(
typepart="RAID",part=usingRaidMemberPart[0]))
self.printERROR(
typepart="RAID",part=usingRaidMemberPart[0]),
_("To use this partition, you have to stop RAID %s")%
raidMemberData)
self.printERROR(" mdadm -S %s"%raidMemberData)
return False
raidMemberData,
(" mdadm -S %s"%raidMemberData)])
# detect using LVM member disks
lvmMemberData = filter(lambda x: "lvmmember" in x[0],
@ -1395,15 +1389,14 @@ class cl_install(color_print, SignalInterrupt):
lvmMemberData = lvmMemberData.partition(")")[0]
prop = getUdevDeviceInfo(name=lvmMemberData)
vgName = prop.get('DM_VG_NAME','')
self.printERROR(_("Unable to use active {typepart} member {part} "
raise InstallError([
_("Unable to use active {typepart} member {part} "
"for installation").format(
typepart="LVM",part=usingLvmMemberPart[0]))
self.printERROR(
typepart="LVM",part=usingLvmMemberPart[0]),
_("To use this partition, you have to remove LVM %s")%
lvmMemberData)
self.printERROR(" vgremove %s"%vgName)
self.printERROR(" pvremove %s"%usingLvmMemberPart[0])
return False
lvmMemberData,
(" vgremove %s"%vgName),
(" pvremove %s"%usingLvmMemberPart[0])])
srcMountPoints = map(lambda x:x['srcMountPoint'],listBinds)
destMountPoints = map(lambda x:x['destMountPoint'],listBinds)
@ -1411,23 +1404,23 @@ class cl_install(color_print, SignalInterrupt):
if wrongBind:
incompBind = filter(lambda x:x[1]==wrongBind[0],
zip(srcMountPoints,destMountPoints))
self.printERROR(_("Source directory %(src)s already used "
raise InstallError(
_("Source directory %(src)s already used "
"for binding '%(bindSrc)s' to '%(bindDst)s'")\
%{'src':wrongBind[0],
'bindSrc':incompBind[0][0],
'bindDst':incompBind[0][1]})
return False
# Check bind params
wrongBind = filter(lambda x:not x[0].startswith("/") or
not x[1].startswith("/") and
x[1] != "none",
zip(srcMountPoints,destMountPoints))
if wrongBind:
self.printERROR(_("Incorrect mount point (bind '%(bindSrc)s' to "\
raise InstallError(
_("Incorrect mount point (bind '%(bindSrc)s' to "\
"'%(bindDst)s')")\
%{'bindSrc':wrongBind[0][0],
'bindDst':wrongBind[0][1]})
return False
# Check '/' in start path
wrongMP = filter(lambda x: not x.startswith("/") and x!="none",
@ -1435,21 +1428,18 @@ class cl_install(color_print, SignalInterrupt):
filter(lambda x: not x.startswith("/"),
map(lambda x:x['srcMountPoint'],listBinds))
if wrongMP:
self.printERROR(_("Incorrect mount point '%s'")%wrongMP[0])
return False
raise InstallError(_("Incorrect mount point '%s'")%wrongMP[0])
# detect duplicate devices
dupDevices = list(set(filter(lambda x:usedDevices.count(x)>1,
usedDevices)))
if dupDevices:
self.printERROR(_("Device '%s' is used twice")%dupDevices[0])
return False
raise InstallError(_("Device '%s' is used twice")%dupDevices[0])
# detect duplicate mount points
dupMP = list(set(filter(lambda x:usedMP.count(x)>1 and x != "none",
usedMP)))
if dupMP:
self.printERROR(_("Mount point '%s' is used twice")%dupMP[0])
return False
raise InstallError(_("Mount point '%s' is used twice")%dupMP[0])
rootdevs = map(lambda x:x['dev'],
filter(lambda x:"mountPoint" in x and \
@ -1502,10 +1492,10 @@ class cl_install(color_print, SignalInterrupt):
mountPoint = ""
curMP = curDevMount[dev]
if curMP and ( curMP != mountPoint and isFormat or curMP == '/' ):
self.printERROR(_("Specified disk '%s' mounted to")\
raise InstallError(
_("Specified disk '%s' mounted to")\
%dev + " " + _("'%s' in the current system")\
%curMP)
return False
else:
if mountPoint and mountPoint in dictMountDev and \
mountPoint != "swap":
@ -1543,7 +1533,7 @@ class cl_install(color_print, SignalInterrupt):
# update install root dev
rootDev = filter(lambda x:x[1]['mountPoint']=='/',devMount.items())
if not rootDev:
self.printERROR(_("The root partition must be specified"))
raise InstallError(_("The root partition must be specified"))
return False
self.clVars.Set('os_install_root_dev',rootDev[0][0],True)
osInstallRootType = self.clVars.Get('os_install_root_type')
@ -1559,20 +1549,17 @@ class cl_install(color_print, SignalInterrupt):
new_bind_dest = []
new_bind_src = []
if filter(lambda x: x != '/', usedMP):
self.printERROR(
raise InstallError(
_("Installation to flash disk is not supported for "
"multipartition install"))
return False
if filter(lambda x:x['dev']!="none",listSwaps):
self.printERROR(
raise InstallError(
_("Installation to flash disk is not "
"supported for swap disks"))
return False
if builderMode:
self.printERROR(
raise InstallError(
_("Installation to flash disk is not supported"
" in builder mode"))
return False
# receive substitution func. Discard all mp, exclude '/' for flash
if osInstallRootType != "flash":
substitution = lambda data,mp: data
@ -1602,11 +1589,9 @@ class cl_install(color_print, SignalInterrupt):
('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
self.checkForLegacyGrub()
else:
if not self.checkForGrub2():
return False
self.checkForGrub2()
return True
def checkForGrub2(self):
@ -1618,18 +1603,16 @@ class cl_install(color_print, SignalInterrupt):
where="os_install_disk_mount", eq="/")
grubDiskType = bootDiskType or rootDiskType
if "lvm-raid" in grubDiskType:
self.printERROR(
raise InstallError(
_("Grub does not support booting from a RAID assembled from LVM.")
+ " " +
_("Try to use a separate /boot partition"))
return False
if grubDiskType.count("raid")>1:
self.printERROR(
raise InstallError(
_("Grub does not support booting from a RAID assembled "
"from another RAID.")
+ " " +
_("Try to use a separate /boot partition"))
return False
return True
def checkForLegacyGrub(self):
@ -2429,7 +2412,21 @@ class cl_install(color_print, SignalInterrupt):
return False
return True
def installSystem(self, force=False, bootDisk=None, stdinReadPwd=False,
def checkInstallParam(self,disks=None,mbr=None,builder=None,typeDisk=None):
errors = []
if disks:
try:
self.setDisks(disks)
except InstallError,e:
errors.append('disks',e)
return errors
def installSystem(self,disks=None,mbr=None,builder=None,
typeDisk=None):
self.checkInstallParam(disks,mbr,builder,typeDisk)
return True
def installSystem2(self, force=False, bootDisk=None, stdinReadPwd=False,
builder=False, flagSpinner=True, update=False):
"""install System by current variable enviroment"""
sourceDistr = None

@ -139,6 +139,9 @@ class Data:
# table for device
os_device_table = {}
# name of device
os_device_name = {}
# content of device.map file for grub
os_install_grub_devicemap_conf = {}

@ -14,76 +14,209 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import soaplib, sys, time
import lxml.etree
from soaplib.serializers.primitive import String, Integer, Any
from soaplib.serializers.clazz import Array
from soaplib.serializers.clazz import ClassSerializer
from soaplib.service import rpc
class NewType (ClassSerializer):
helper = Integer
value = Any
class UserInfo(ClassSerializer):
name = String
surname = String
class GroupInfo(ClassSerializer):
name = String
gid = Integer
class UserInfoValue (ClassSerializer):
table = UserInfo
class GroupInfoValue (ClassSerializer):
table = GroupInfo
# Класс с выполняемым кодом
import soaplib, sys, time, os
from soaplib.serializers.primitive import String, Integer, Any, Boolean
from soaplib.serializers.clazz import Array, ClassSerializer
from soaplib.service import rpc, DefinitionBase
from cl_install import Install
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install',sys.modules[__name__])
##########API########################
class ChoiceValue(ClassSerializer):
values = Array(String)
comments = Array(String)
typefield = String
class Table(ClassSerializer):
head = Array(String)
body = Array(Array(String))
values = Array(ChoiceValue)
class Option(ClassSerializer):
shortopt = String
longopt = String
metavalue = String
help = String
class Field(ClassSerializer):
name = String
label = String
type = String
opt = Option
help = String
element = String
choice = Array(String)
default = String
value = String
tablevalue = Table
class GroupField(ClassSerializer):
name = String
fields = Array(Field)
nextlabel = String
last = Boolean
class ViewInfo(ClassSerializer):
groups = Array(GroupField)
########################################
class InstallInfo(ClassSerializer):
"""Parameters for method install"""
disk = Array(Array(String))
mbr = Array(String)
type = String
nouuid = Boolean
iso = String
system = String
march = String
build = Boolean
lang = String
user = Array(String)
autologin = String
password = Array(String)
hostname = String
netconf = String
dhcp = Array(String)
ip = Array(String)
route = Array(Array(String))
dns = Array(String)
proxy = String
ntp = String
video = String
xorgres = String
fbres = String
timezone = String
default = Array(String)
class FieldError(ClassSerializer):
field = String
error = String
class Wsdl:
def install (self, name, times) :
try:
results = []
self.writeFile()
for i in range( 0, times ) :
results.append('Hello!!!, %s %d'%(name, i))
# Помещение данных в словарь процессов
self.setData (results)
# Учёт процесса выполнения
while self.getPercent() < 100:
time.sleep(2)
# Увеличение процента выполнения процесса
self.addPercent (20)
return True
# Обработка сигнала прерывания работы процесса
except KeyboardInterrupt:
# Необходимо передать Fasle для сохранения данных о процессе
return False
import sys, os
#sys.path.insert(0,os.path.abspath('~/Home/mydir/source/my/soap/temp'))
from baseClass import Basic, check_permissions
@rpc( NewType, UserInfoValue, _returns = Array( String ) )
def func (self, a, b):
return []
@rpc( String, Integer, Array(String), Integer, Integer, String,\
#_inVariableNames = {'_stri':'stri', "a" : "a"},\
_returns = NewType, _outVariableName='return') #Array( String ) )
# проверка прав на вызов функции
@check_permissions()
# кэширование параметров
@Basic.cache
# команда для консоли
@Basic.console('cl-say-hello')
@Basic.gui('Misc')
#def say_hello_view
def say_hello ( self, cert, sid, name, times, a = 5, _stri = "stri_"):
install = type("CommonInstall",(self.Common, Wsdl, object), {})
return self.startprocess(sid, target=install,method="install",
args_proc = (name[0], times))
@rpc(String,Integer,InstallInfo,Boolean,_returns=Array(FieldError))
#@wsdl_server.check_permissions(["install"])
#@Basic.cache
#@Basic.console('cl-install')
#@Basic.gui('System.Install')
def install_system(self,cert,sid,param,onlycheck):
install = Install()
install.initVars()
if onlycheck:
errors = []
for err in install.checkInstallParam(param.disks,
param.mbr,
param.type,
param.build):
errros.append(FieldError(field=err[0],
error=err[1]))
return errors
else:
install.installSystem(param.disks,param.mbr,param.type,param.build)
return []
def getPartitionInfo(self,clVars):
MOUNTPOINT,DEVICE,MAKEFORMAT,FORMAT,LABLE,SIZE = 0,1,2,3,4,5
body = filter(lambda x:x[MOUNTPOINT],
clVars.zipVars('os_install_disk_mount',
'os_disk_dev',
'os_install_disk_perform_format',
'os_install_disk_format',
'os_disk_name',
'os_disk_size'))
table = Table(
head=[_("Mount point"),_("Partition"),
_("Perform format"),_("Filesystem"),
_("Label"),_("Size")],
body=body,
values=[])
table.values.append(ChoiceValue(
type="string"))
table.values.append(ChoiceValue(
values=clVars.Get('os_disk_dev'),
comments = map(lambda x:"%s - %s - %s"%
(x[DEVICE],x[FORMAT],x[SIZE]),
body),
type="choice"))
table.values.append(ChoiceValue(
values=[_("yes"),_("no")],
type="choice"))
table.values.append(ChoiceValue(
values=clVars.Get('os_format_type'),
type="choice"))
return table
def getDeviceChoice(self,clVars):
"""Get choice value for device"""
deviceDevName = map(lambda x:"%s (%s)"%(x[0],x[1]),
clVars.zipVars('os_device_name','os_device_dev'))
return ChoiceValue(
values = clVars.Get('os_device_dev')+["off"],
comments = deviceDevName + [_("off")])
def getDeviceTypesChoice(self):
return ChoiceValue(values = ["hdd","usb-hdd","flash"],
comments = [_("Hard disk"), _("USB Hard disk"),
_("USB Flash")])
@rpc(String,Integer,Integer,_returns=ViewInfo)
def install_system_view(self,cert,sid,page):
#print dir(wsdl_server)
view = ViewInfo(groups=[])
install = Install()
install.initVars()
if not page is None or page == 0:
group = GroupField(name=_("Partitioning"),nextlabel=_("Next"))
group.fields = []
group.fields.append(Field(
name = "disk",
label = _("Mount points"),
type = "table",
opt = Option(shortopt="-d",
longopt="--disk",
metavalue="DISK[:[DIR:FILESYSTEM:OPTIONS]]"),
help = \
_("DISK for installation, will be mounted to DIR. DIR set "
"to 'none' will cancel the mount point transfer. For "
"creating bind mount point you have to specify the "
"source directory as DISK"),
element = "table",
tablevalue = self.getPartitionInfo(install.clVars)))
group.fields.append(Field(
name = "mbr",
label = _("MBR"),
type = "list",
opt = Option(longopt="--mbr",
metavalue="MBR"),
help = \
_("boot disk for the system bound for install (for "
"recording MBR), off - disable MBR writing"),
element = "select",
choice = self.getDeviceChoice(install.clVars)))
group.fields.append(Field(
name = "type",
label = _("Device type"),
type = "string",
opt = Option(longopt="--type",
metavalue="MBR"),
help = \
_("device type for the system bound for install"),
element = "choice",
choice = self.getDeviceTypesChoice()))
view.groups.append(group)
if not page is None or page == 1:
group = GroupField(name=_("System"),last=True,nextlable=_("Install"))
group.fields.append(Field(
name = "build",
label = _("Builder mode"),
type = "boolean",
opt = Option(longopt="--build"),
help = \
_("installation for assemble"),
element = "checkbox"))
view.groups.append(group)
return view

Loading…
Cancel
Save