diff --git a/install/cl_distr.py b/install/cl_distr.py index d0cd37a..2984ec4 100644 --- a/install/cl_distr.py +++ b/install/cl_distr.py @@ -33,7 +33,6 @@ from calculate.lib.utils.device import (detectDeviceForPartition, getUdevDeviceInfo, countPartitions) from calculate.lib.cl_vars_share import varsShare from calculate.lib.cl_template import _terms -from calculate.lib.cl_fill import fillVars import threading diff --git a/install/cl_fill_install.py b/install/cl_fill_install.py index 88a16ca..5b5e422 100644 --- a/install/cl_fill_install.py +++ b/install/cl_fill_install.py @@ -35,7 +35,7 @@ from calculate.lib.cl_fill import clLocale from calculate.lib.cl_template import _terms from calculate.install.cl_distr import (DistributiveRepository, PartitionDistributive) -from calculate.install.cl_install import convertDictOpt +from calculate.install.cl_install import FileSystemManager from operator import itemgetter from calculate.lib.cl_lang import setLocalTranslate @@ -69,40 +69,6 @@ class fillVars(object, varsShare): except: pass - def get_ac_install_merge(self): - """Need perform templates for install:merge or install:unmerge""" - actionsMap = {'merge':'up', - 'system':'up'} - cl_action = self.Get('cl_action') - if cl_action == 'system' and \ - self.Get('os_install_root_type') == 'flash': - return "" - return actionsMap[cl_action] if cl_action in actionsMap else "" - - def get_ac_install_system(self): - """Need perform templates for install:system""" - if self.Get('cl_action') == 'system' and \ - self.Get('os_install_root_type') != "flash": - return "up" - else: - return "" - - def get_ac_install_flash(self): - """Need perform templates for install:flash""" - clAction = self.Get('cl_action') - if clAction == 'system' and self.Get('os_install_root_type') == 'flash': - return "up" - return "" - - def get_ac_install_live(self): - """Need perform templates for install:live""" - if self.Get('ac_install_merge') == "up" and \ - self.Get('cl_chroot_status') == "off" or \ - self.Get('cl_action') == 'live': - return "up" - else: - return "" - def get_os_install_net_hash(self): """Get net hash""" rePci = re.compile(r"(\d\d:\d\d\.\d)(?:/[^/]+){2}$") @@ -1259,16 +1225,12 @@ class fillVars(object, varsShare): def get_os_format_type(self): """Filesystem format support by calcualte-install""" - return filter(lambda x:not x in ("default","noformat") and - x in convertDictOpt._fileSystemOpt, - filter(lambda x:not x.startswith("_"), - convertDictOpt._fileSystemOpt.keys())+\ - convertDictOpt._propertiesFileSystem.keys()) + return FileSystemManager.supportFS.keys() def get_os_format_use(self): """Avialable format by mkfs utility""" return map(lambda x:"yes" - if path.exists(convertDictOpt._fileSystemOpt[x]["makefs"]) + if path.exists(FileSystemManager.supportFS[x]["format"]) else "no", self.Get('os_format_type')) def get_os_install_lang(self): diff --git a/install/cl_install.py b/install/cl_install.py index 7f6973b..d604002 100644 --- a/install/cl_install.py +++ b/install/cl_install.py @@ -59,9 +59,9 @@ def pop_install_errors(): defaultExit = cl_overriding.exit defaultPrintERROR = cl_overriding.printERROR -from calculate.lib.cl_fill import clLocale +from calculate.lib.variables import Locale from calculate.lib.cl_template import template -from calculate.lib.cl_datavars import DataVars +from calculate.lib.cl_datavars import ClDataVars from calculate.lib.cl_print import color_print from cl_distr import (PartitionDistributive,DistributiveRepository, DistributiveError, ScratchPartitionDistributive, @@ -77,663 +77,121 @@ setLocalTranslate('cl_install',sys.modules[__name__]) class InstallError(Exception): """Installation Error""" - pass + def __init__(self,error,field=None): + self.field = field + Exception.__init__(self,error) class printNoColor: def colorPrint(self,attr,fg,bg,string): sys.stdout.write(string) -class DataVarsInstall(DataVars): +class DataVarsInstall(ClDataVars): """Variable class for installation""" def importInstall(self, **args): - '''Заполнить конфигурацию переменных, для десктопа''' - # Имя секции в calculate.env - envSection = "install" - # заполнить переменные окружения алгоритмом по умолнанию - self.importData(envSection, ('calculate.install.cl_vars_install', - 'calculate.install.cl_fill_install')) + """Import install variables""" + self.importData('calculate.install.cl_vars_install') -class convertDictOpt: +class FileSystemManager: """Convert dict install option""" - _defaultFS = "ext4" - _defaultFlashFS = "vfat" - - _diskDefaultMountPoints = { "default":{"fileSystem":_defaultFS, - "isFormat":False, - "options":["noatime"]}, - "/":{"fileSystem":_defaultFS, - "isFormat":True, - "options":["noatime"]}, - "none":{"fileSystem":"", - "isFormat":False, - "options":[""]},} - #"/boot":{"fileSystem":"ext2", - # "isFormat":True, - # "options":["noatime"]}} - - _bindDefaultMountPoint = {"fileSystem":"none", - "isFormat":False, - "options":["bind"]} - - _swapDefaultMountPoint = {"fileSystem":"swap", - "isFormat":False, - "options":["sw"]} - - _propertiesFileSystem = {"default": {"fileSystem":_defaultFS, - "isFormat":True, - "options":["noatime"]}, - "noformat":{"fileSystem":"", - "isFormat":False, - "options":["noatime"]}, - "defaultflash":{"fileSystem":_defaultFlashFS, - "isFormat":True, - "options":["noatime"]}} - - _ext2Options = {"options":["acl", "noacl", "bsddf", "minixdf", "check", - "debug", "errors", "grpid", "bsdgroups", - "nogrpid", "sysvgroups", "grpquota", "noquota", - "quota", "usrquota","nobh", "nouid32", - "oldalloc", "orlov", "resgid","resuid", "sb", - "user_xattr", "nouser_xattr"], - "pair":{"check":{"options":["none", "nocheck"], - "incompatible":["none", "nocheck"]}, - "errors":{"options":["continue", "remount-ro", - "panic"], - "incompatible":["continue","remount-ro", - "panic"]}, - "resgid":{"options":re.compile("\d+"), - "incompatible":[]}, - "resuid":{"options":re.compile("\d+"), - "incompatible":[]}, - "sb":{"options":re.compile("\d+"), - "incompatible":[]}}, - "incompatible":[["acl","noacl"], - ["bsddf", "minixdf"], - ["grpid","bsdgroups"], - ["grpid","nogrpid"], - ["bsdgroups","sysvgroups"], - ["nogrpid","sysvgroups"], - ["grpquota","noquota","quota", - "usrquota"], - ["oldalloc","orlov"], - ["user_xattr","nouser_xattr"]], - "makefs":"/sbin/mkfs.ext2"} - _ext3Options = _ext2Options.copy() - _ext3Options.update({"makefs":"/sbin/mkfs.ext3"}) - _ext3Options["options"] += ["journal", "noload", "data", "barrier", - "commit", "data_err"] - _ext3Options["pair"].update({"journal":{"options":["update", "inum"], - "incompatible":["update", "inum"]}, - "data":{"options":["journal", "ordered", - "writeback"], - "incompatible":["journal", "ordered", - "writeback"]}, - "data_err":{"options":["abort", "ordered", - "ignore"], - "incompatible":["abort", "ordered", - "ignore"]}, - "barrier":{"options":["0","1"], - "incompatible":["0","1"]}, - "commit":{"options":re.compile("\d+"), - "incompatible":[]}}) - - _fileSystemOpt = {"_all":{"options":["async", "atime", "noatime", "auto", - "noauto", "defaults", "dev", "nodev", - "diratime", "nodiratime", "dirsync", - "exec", "noexec", "group", "iversion", - "noiversion", "mand", "nomand", - "_netdev", "nofail", "relatime", - "norelatime", "strictatime", - "nostrictatime", "suid", "nosuid", - "owner", "remount", "ro", "rw", "sync", - "user", "nouser", "users"], - "pair": {}, - "incompatible":[["sync", "async"], - ["atime", "noatime"], - ["auto", "noauto"], - ["dev", "nodev"], - ["diratime", "nodiratime"], - ["exec", "noexec"], - ["iversion", "noiversion"], - ["mand", "nomand"], - ["relatime", "norelatime"], - ["strictatime", "nostrictatime"], - ["suid", "nosuid"], - ["ro", "rw"], - ["user", "nouser"]]}, - "ext2":_ext2Options, - "ext3":_ext3Options, - "ext4":{"options":["journal_dev", "noload", "data", - "commit", "orlov", "oldalloc", - "user_xattr", "nouser_xattr", "acl", - "noacl", "bsddf", "minixdf", "debug", - "errors", "data_err", "grpid", - "bsdgroups", "nogrpid", "sysvgroups", - "resgid", "resuid", "sb", "quota", - "noquota", "grpquota", "usrquota", - "bh", "nobh", "journal_checksum", - "journal_async_commit", "journal", - "barrier", "nobarrier", - "inode_readahead", "stripe", - "delalloc", "nodelalloc", - "max_batch_time", "journal_ioprio", - "auto_da_alloc", "noauto_da_alloc"], - "pair": {"journal_dev":{\ - "options":re.compile(".+"), - "incompatible":[]}, - "data":{"options":["journal", "ordered", - "writeback"], - "incompatible":["journal", - "ordered", - "writeback"]}, - "commit":{"options":re.compile("\d+"), - "incompatible":[]}, - "errors":{"options":["continue", - "remount-ro", - "panic"], - "incompatible":["continue", - "remount-ro", - "panic"]}, - "data_err":{"options":["abort", - "ordered", - "ignore"], - "incompatible":["abort", - "ordered", - "ignore"]}, - "resgid":{"options":re.compile("\d+"), - "incompatible":[]}, - "resuid":{"options":re.compile("\d+"), - "incompatible":[]}, - "sb":{"options":re.compile("\d+"), - "incompatible":[]}, - "journal":{"options":["update"], - "incompatible":[]}, - "inode_readahead":{"options":\ - re.compile("\d+"), - "incompatible":[]}, - "stripe":{"options":re.compile("\d+"), - "incompatible":[]}, - "max_batch_time":{"options":\ - re.compile("\d+"), - "incompatible":[]}, - "journal_ioprio":{"options":\ - re.compile("[1-7]"), - "incompatible":[]}}, - "incompatible":[["oldalloc", "orlov"], - ["user_xattr","nouser_xattr"], - ["acl", "noacl"], - ["bsddf", "minixdf"], - ["grpid","bsdgroups"], - ["grpid","nogrpid"], - ["bsdgroups","sysvgroups"], - ["nogrpid","sysvgroups"], - ["grpquota","noquota","quota", - "usrquota"], - ["bh","nobh"], - ["delalloc", "nodelalloc"], - ["auto_da_alloc", - "noauto_da_alloc"]], - "makefs":"/sbin/mkfs.ext4"}, - "reiserfs":{"options":["conv","hash","hashed_relocation", - "no_unhashed_relocation", - "noborder", "nolog", "notail", - "replayonly", "resize", - "user_xattr", "acl"], - "pair":{"hash":{"options":["rupasov", "tea", - "r5", "detect"], - "incompatible":["rupasov", - "tea", - "r5", - "detect"]}, - "resize":{"options":re.compile("\d+"), - "incompatible":[]}}, - "incompatible":[], - "makefs":"/sbin/mkfs.reiserfs"}, - "vfat":{"options":["uni_xlate","posix","nonumtail", - "utf8","shortname"], - "pair":{"shortname":{"options": - re.compile("lower|win95|winnt|mixed"), - "incompatible":[]}, - "utf8":{"options": - re.compile("0|1|no|false|true|yes"), - "incompatible":["uni_xlate"]}}, - "incompatible":[], - "makefs":"/usr/sbin/mkfs.vfat"}, - "btrfs":{"options":[], - "pair":{}, - "incompatible":[], - "makefs":"/sbin/mkfs.btrfs"}, - "nilfs2":{"options":[], - "pair":{}, - "incompatible":[], - "makefs":"/sbin/mkfs.nilfs2"}, - "jfs":{"options":[], - "pair":{}, - "incompatible":[], - "makefs":"/sbin/mkfs.jfs"}, - "ntfs":{"options":["uni_xlate","posix","nls", - "utf8","iocharset", - "uid","gid","umask"], - "pair":{"utf8":{"options": - re.compile("0|1|no|false|true|yes"), - "incompatible":["uni_xlate"]}, - "iocharset":{"options":re.compile(".+"), - "incompatible":["nls"]}, - "uni_xlate":{"options": - re.compile("0|1|2"), - "incompatible":[]}, - "posix":{"options": - re.compile("0|1"), - "incompatible":[]}, - "uid":{"options":re.compile(".+"), - "incompatible":[]}, - "gid":{"options":re.compile(".+"), - "incompatible":[]}, - "umask":{"options":re.compile(".+"), - "incompatible":[]}, - }, - "incompatible":[], - "makefs":"/usr/sbin/mkfs.ntfs"}, - "ntfs-3g":{"options":["uid","gid","umask","fmask", - "dmask","usermapping", - "default_permissions", - "inherit","locale", - "force","remove_hiberfile", - "show_sys_files","allow_other", - "max_read","silent","no_def_opts", - "streams_interface","user_xattr", - "efs_raw","debug","no_detach"], - "pair":{"uid":{"options":re.compile(".+"), - "incompatible":[]}, - "gid":{"options":re.compile(".+"), - "incompatible":[]}, - "umask":{"options":re.compile(".+"), - "incompatible":[]}, - "fmask":{"options":re.compile(".+"), - "incompatible":[]}, - "dmask":{"options":re.compile(".+"), - "incompatible":[]}, - "usermapping":{"options":re.compile(".+"), - "incompatible":[]}, - "default_permissions":{ - "options":re.compile(".+"), - "incompatible":[]}, - "locale":{"options":re.compile(".+"), - "incompatible":[]}, - "max_read":{"options":re.compile(".+"), - "incompatible":[]}, - "streams_interface":{ - "options":re.compile(".+"), - "incompatible":[]}}, - "incompatible":[], - "makefs":"/usr/sbin/mkfs.ntfs"}, - "xfs":{"options":["allocsize", "attr2", "noattr2", - "barrier", "dmapi", "grpid", - "bsdgroups", "nogrpid", "sysvgroups", - "ihashsize", "ikeep", "noikeep", - "inode64", "largeio","nolargeio", - "logbufs", "logbsize", "logdev", - "rtdev", "mtpt", "noalign", "noatime", - "norecovery", "nouuid", "osyncisosync", - "uquota", "usrquota", "uqnoenforce", - "quota", "pquota", "prjquota", - "pqnoenforce", "sunit", "swidth", - "swalloc"], - "pair":{"allocsize":{"options":re.compile("\d+"), - "incompatible":[]}, - "ihashsize":{"options":re.compile("\d+"), - "incompatible":[]}, - "logbufs":{"options":re.compile("\d+"), - "incompatible":[]}, - "logbsize":{"options":re.compile("\d+"), - "incompatible":[]}, - "logdev":{"options":re.compile(".+"), - "incompatible":[]}, - "rtdev":{"options":re.compile(".+"), - "incompatible":[]}, - "mtpt":{"options":re.compile(".+"), - "incompatible":[]}, - "sunit":{"options":re.compile("\d+"), - "incompatible":[]}, - "swidth":{"options":re.compile("\d+"), - "incompatible":[]}}, - "incompatible":[["attr2", "noattr2"], - ["grpid", "bsdgroups"], - ["grpid", "nogrpid"], - ["bsdgroups", "sysvgroups"], - ["nogrpid", "sysvgroups"], - ["ikeep", "noikeep"], - ["largeio","nolargeio"], - ["uquota", "usrquota", - "uqnoenforce", "quota"], - ["pquota", "prjquota", - "pqnoenforce"]], - "makefs":"/sbin/mkfs.xfs"}} - listFileSystemCorrupted = [] - - def __init__(self, clVars): - self.clVars = clVars - self.varDiskData = clVars.zipVars('os_disk_dev', 'os_disk_format', - 'os_disk_mount', 'os_disk_options', - 'os_disk_part', 'os_disk_size') - - def addFileSystemCorrupted(self, fileSystem): - """Add file system with error""" - if not fileSystem in self.listFileSystemCorrupted: - self.listFileSystemCorrupted.append(fileSystem) - - def getAllSupportFileSystemOpt(self): - """Get list all file system""" - return filter(lambda x: not x.startswith("_"), - self._fileSystemOpt.keys()) +\ - self._propertiesFileSystem.keys() - - def getAllAvailableFileSystemOpt(self): - return filter(lambda x: x in ("default","noformat","defaultflash") or - (not "makefs" in self._fileSystemOpt[x] or - path.exists(self._fileSystemOpt[x]["makefs"])), - self.getAllSupportFileSystemOpt()) - - def _getFileSystemData(self, realFileSystem): - """Get data in _fileSystemOpt""" - return self._fileSystemOpt.get(realFileSystem) - - def _getFileSystemAllOpt(self, realFileSystem): - """Get all options from file system""" - data = self._getFileSystemData(realFileSystem) - if data: - return list(set(data["options"])|\ - set(self._fileSystemOpt["_all"]["options"])) - else: - return [] - - def _checkExistsOptions(self, realFileSystem, realOptions): - """Check exists options""" - allOptions = self._getFileSystemAllOpt(realFileSystem) - if not allOptions: - raise InstallError(_("Unsupported file system %s")%realFileSystem) - for opt in realOptions: - if opt and not opt in allOptions: - self.addFileSystemCorrupted(realFileSystem) - raise InstallError(_("Incorrect option %s")%opt) - - def _checkFileSystemIncompatibleOpt(self, realFileSystem, realOptions): - """Check incompatible options from realOptions""" - # detect duplicate options - dupOptions = filter(lambda x: realOptions.count(x)>1, set(realOptions)) - if dupOptions: - raise InstallError(_("Duplicated options %s")%", ".join(dupOptions)) - realOptions = map(lambda x: x.split("=")[0], realOptions) - self._checkExistsOptions(realFileSystem, realOptions) - data = self._getFileSystemData(realFileSystem) - if data: - defIncompatibleOpt = self._fileSystemOpt["_all"]["incompatible"] - defIncompatibleOpt = map(lambda x: map(lambda y: y, x), - defIncompatibleOpt) - listDefIncompatibleOpt = reduce(lambda x,y: x+y, - defIncompatibleOpt, []) - incompatibleOpt = data["incompatible"] - for listOpt in incompatibleOpt: - for opt in listOpt: - if opt in listDefIncompatibleOpt: - defIncompatibleOpt = filter(lambda x: not opt in x, - defIncompatibleOpt) - incompatibleOpt = defIncompatibleOpt + incompatibleOpt - listIncompatibleOpt = reduce(lambda x,y: x+y, incompatibleOpt, []) - for option in realOptions: - if option in listIncompatibleOpt: - dataOpt = filter(lambda x: option in x, incompatibleOpt) - if dataOpt: - listOpt = filter(lambda x: x!=option, dataOpt[0]) - twoOptList = list(set(listOpt)&set(realOptions)) - if twoOptList: - self.addFileSystemCorrupted(realFileSystem) - raise InstallError(_("Incompatible options") + ":"+\ - " " + option + " " + _("and") +\ - " " + ",".join(twoOptList)) - - def _checkPairOpt(self, realFileSystem, realOptions): - """Check options from realOptions (option=value)""" - # detect duplicate options - dupOptions = filter(lambda x: realOptions.count(x)>1, set(realOptions)) - if dupOptions: - raise InstallError(_("Duplicated options %s")%", ".join(dupOptions)) - splOptions = map(lambda x: x.split("=")[0], realOptions) - self._checkExistsOptions(realFileSystem, splOptions) - dictOpt = {} - notPairOpt = [] - for opt in realOptions: - dataOpt = opt.split("=") - if len(dataOpt)==2: - nameOpt, valueOpt = dataOpt - if not nameOpt in dictOpt: - dictOpt[nameOpt] = [] - dictOpt[nameOpt].append(valueOpt) - elif len(dataOpt)>2: - self.addFileSystemCorrupted(realFileSystem) - raise InstallError(_("Incorrect option %s")%opt) - else: - notPairOpt.append(opt) - data = self._getFileSystemData(realFileSystem) - if data: - pairData = {} - pairData.update(self._fileSystemOpt["_all"]["pair"]) - pairData.update(data["pair"]) - allPairOpt = pairData.keys() - wrongOpt = list(set(allPairOpt)&set(notPairOpt)) - if wrongOpt: - self.addFileSystemCorrupted(realFileSystem) - raise InstallError(_("Incorrect options %s")\ - %", ".join(wrongOpt)) - for nameOpt in dictOpt.keys(): - if not nameOpt in allPairOpt: - self.addFileSystemCorrupted(realFileSystem) - raise InstallError(_("Incorrect option %s")\ - %"%s=%s"%(nameOpt,valueOpt)) - checkValues = pairData[nameOpt] - checkValuesOpt = checkValues["options"] - # check options - listValues = dictOpt[nameOpt] - if type(checkValuesOpt)!=list: - if len(listValues)>1: - wrongOpt = ",".join(map(lambda x: "%s=%s"%(nameOpt,x), - listValues)) - self.addFileSystemCorrupted(realFileSystem) - raise InstallError(_("Incorrect option %s")\ - %wrongOpt) - if not checkValuesOpt.search(listValues[0]): - self.addFileSystemCorrupted(realFileSystem) - raise InstallError(_("Incorrect option %s")\ - %"%s=%s"%(nameOpt,listValues[0])) - else: - wrongValues = list(set(listValues)-set(checkValuesOpt)) - if wrongValues: - wrongOpt = ",".join(map(lambda x: "%s=%s"%(nameOpt,x), - wrongValues)) - self.addFileSystemCorrupted(realFileSystem) - raise InstallError(_("Incorrect option %s")\ - %wrongOpt) - checkValuesIncompOpt = checkValues["incompatible"] - if checkValuesIncompOpt: - incompValues = list(set(listValues)&\ - set(checkValuesIncompOpt)) - if len(incompValues)>1: - wrongOpt = map(lambda x: "%s=%s"%(nameOpt,x), - incompValues) - self.addFileSystemCorrupted(realFileSystem) - raise InstallError(_("Incompatible options") + ":"+\ - " " + wrongOpt[0] + " " + \ - _("and") + " " +\ - ",".join(wrongOpt[1:])) - - def getDefaultOptFileSystem(self, fileSystem, devicetype="hdd"): - """Get default properties for fileSystem""" - if not fileSystem in self._propertiesFileSystem: - fileSystem="default" - if devicetype == "flash" and fileSystem=="default": - fileSystem="defaultflash" - if devicetype != "flash" and fileSystem=="defaultflash": - fileSystem="default" - propertiesFileSystem = self._propertiesFileSystem.copy() - return propertiesFileSystem[fileSystem] - - def getDefaultOptMountPoint(self, mountPoint): - """Get default properties for mount point disk""" - if not mountPoint in self._diskDefaultMountPoints: - if mountPoint.startswith('/'): - mountPoint = "default" - else: - raise InstallError(_("Incorrect mount point %s")%mountPoint) - propertiesMountPoints = self._diskDefaultMountPoints.copy() - return propertiesMountPoints[mountPoint] - - def getDefaultOptSwap(self): - """Get default properties for swap""" - return self._swapDefaultMountPoint - - def getDefaultOptBind(self): - """Get default properties for swap""" - return self._bindDefaultMountPoint - - def _getDeviceType(self,dev): - """Get device type, considing given by user param""" - oldRootDev = self.clVars.Get('os_install_root_dev') - self.clVars.Set('os_install_root_dev',dev,True) - rootType = self.clVars.Get('os_install_root_type') - self.clVars.Set('os_install_root_dev',oldRootDev,True) - return rootType - - def __call__(self, optionsDict={}): - """Convert dict options (bind options, swap options or disk options)""" - optProperties = optionsDict.copy() - # 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,"","","",""]] - dev, format, mount, options, part, size = dataPart[0] - dictUpdateProperty = {} - if "mountPoint" in optProperties: - # Disk options - dictOptions = {} - optFileSystem = optProperties["fileSystem"] - if optProperties["mountPoint"]: - optMountPoint = path.normpath(optProperties["mountPoint"]) - else: - optMountPoint = optProperties["mountPoint"] - # if specified mount point empty of default - it is / - if not optMountPoint or optMountPoint=="default": - optMountPoint = "/" - dictUpdateProperty["mountPoint"] = optMountPoint - supportedFS = self.getAllSupportFileSystemOpt() - reRootDirectories = re.compile("^/[^/]*/?$",re.S) - if reRootDirectories.match(path.normpath(optMountPoint)): - # check install type (flash or hdd) - if self._getDeviceType(dev) != "flash": - excludeFS = set(["vfat","ntfs","ntfs-3g"]) - else: - excludeFS = set(supportedFS) - \ - set(["vfat","noformat","default"]) - else: - excludeFS = set([]) - availableFS = self.getAllAvailableFileSystemOpt() - # if fs not specified and current fs not supported - if not optFileSystem: - if not (format and format in \ - set(availableFS)&set(supportedFS)-excludeFS) \ - and optMountPoint == '/': - optFileSystem = "default" - else: - dictUpdateProperty["fileSystem"] = format - - # if specified fs - if optFileSystem: - # if specified wrong fs - if not optFileSystem in supportedFS: - raise InstallError(_("Wrong file system option '%s'")\ - %optFileSystem) - if not optFileSystem in availableFS: - raise InstallError(_("File system '%s' is not available")\ - %optFileSystem) - if optFileSystem in excludeFS: - mp = optMountPoint - if reRootDirectories.match(path.normpath(mp)) \ - and self._getDeviceType(dev) == "flash": - mp = "flash" - raise InstallError( - _("File system for '%(mp)s' should not be '%(opt)s'") - %{'mp':mp, 'opt':optFileSystem}) - if not "fileSystem" in dictOptions or \ - optFileSystem == "default": - dictOptions.update( - self.getDefaultOptFileSystem(optFileSystem, - self._getDeviceType(dev))) - if optFileSystem == "noformat": - if not format: - raise InstallError(\ - _("Partition %s is not formatted")%dev) - elif format in excludeFS: - mp = optMountPoint - if reRootDirectories.match(path.normpath(mp)) \ - and self._getDeviceType(dev) == "flash": - mp = "flash" - raise InstallError(\ - _("File system for '%(mp)s' should not be '%(format)s'")\ - %{'mp':mp,'format':format}) - if not options: - options = ["noatime"] - dictOptions["fileSystem"] = format - dictOptions["options"] = [] - if optFileSystem in self._propertiesFileSystem: - dictUpdateProperty["fileSystem"] = dictOptions["fileSystem"] - optOptions = optProperties["options"] - flagCheckOptOptions = True - if optOptions: - if optMountPoint != "/": - dictUpdateProperty["options"] = optOptions - else: - flagCheckOptOptions = True - - optProperties = dict(filter(lambda x: x[1], optProperties.items())) - optProperties.update(dictUpdateProperty) - if dictOptions: - dictDefault = dictOptions.copy() - else: - dictDefault = self.getDefaultOptMountPoint(optMountPoint).copy() - dictDefault.update(optProperties) - if flagCheckOptOptions: - # Check mount options - self._checkFileSystemIncompatibleOpt(dictDefault["fileSystem"], - dictDefault["options"]) - self._checkPairOpt(dictDefault["fileSystem"], - dictDefault["options"]) - return dictDefault - else: - # Swap options - dictOptions = {} - optFileSystem = "swap" - if optFileSystem != format: - dictUpdateProperty["isFormat"] = True - dictOptions = self.getDefaultOptSwap().copy() - dictOptions.update(optProperties) - dictOptions.update(dictUpdateProperty) - return dictOptions + defaultFS = {'hdd':"ext4", + 'flash':"vfat", + 'usb-hdd':"ext4"} + defaultOpt = 'noatime' + defaultBindOpts = ['bind'] + supportFS = { + 'ext2': {'defaultopt': defaultOpt, + 'format': '/sbin/mkfs.ext2', + 'formatparam': '{labelparam} {device}', + 'gpt': '0700', + 'label': '-L {labelname}', + 'msdos': '83', + 'type':['hdd','usb-hdd']}, + 'ext3': {'defaultopt': defaultOpt, + 'format': '/sbin/mkfs.ext3', + 'formatparam': '{labelparam} {device}', + 'gpt': '0700', + 'label': '-L {labelname}', + 'msdos': '83', + 'type':['hdd','usb-hdd']}, + 'ext4': {'defaultopt': defaultOpt, + 'format': '/sbin/mkfs.ext4', + 'formatparam': '{labelparam} {device}', + 'gpt': '0700', + 'label': '-L {labelname}', + 'msdos': '83', + 'type':['hdd','usb-hdd']}, + 'reiserfs': {'defaultopt': defaultOpt, + 'format': '/sbin/mkfs.reiserfs', + 'formatparam': '{labelparam} -f {device}', + 'gpt': '0700', + 'label': '-l {labelname}', + 'msdos': '83', + 'type':['hdd','usb-hdd']}, + 'btrfs': {'defaultopt': defaultOpt, + 'format': '/sbin/mkfs.btrfs', + 'formatparam': '{labelparam} {device}', + 'gpt': '0700', + 'label': '-L {labelname}', + 'msdos': '83', + 'type':['hdd','usb-hdd']}, + 'jfs': {'defaultopt': defaultOpt, + 'format': '/sbin/mkfs.jfs', + 'formatparam': '{labelparam} -f {device}', + 'gpt': '0700', + 'label': '-L {labelname}', + 'msdos': '83', + 'type':['hdd','usb-hdd']}, + 'xfs': {'defaultopt': defaultOpt, + 'format': '/sbin/mkfs.xfs', + 'formatparam': '{labelparam} -f {device}', + 'gpt': '0700', + 'label': '-L {labelname}', + 'msdos': '83', + 'type':['hdd','usb-hdd']}, + 'nilfs2': {'defaultopt': defaultOpt, + 'format': '/sbin/mkfs.nilfs2', + 'formatparam': '{labelparam} {device}', + 'gpt': '0700', + 'label': '-L {labelname}', + 'msdos': '83', + 'type':['hdd','usb-hdd']}, + 'swap': {'defaultopt': 'sw', + 'format': '/sbin/mkswap', + 'formatparam': '{device}', + 'gpt': '8200', + 'label': '', + 'msdos': '82'}, + 'vfat': {'defaultopt': defaultOpt, + 'format': '/usr/sbin/mkfs.vfat', + 'formatparam': '{labelparam} -F 32 {device}', + 'gpt': '0700', + 'label': '-n {labelname}', + 'msdos': '0b', + 'type':['flash']}, + 'ntfs': {'defaultopt': defaultOpt, + 'format': '/sbin/mkfs.ntfs', + 'formatparam': '{labelparam} -FQ {device}', + 'gpt': '0700', + 'label': '-L {labelname}', + 'msdos': '7', + 'compatible':['ntfs-3g']}, + 'ntfs-3g': {'defaultopt': defaultOpt, + 'format': '/sbin/mkfs.ntfs', + 'formatparam': '{labelparam} -FQ {device}', + 'gpt': '0700', + 'label': '-L {labelname}', + 'msdos': '7', + 'compatible':['ntfs']}} + @classmethod + def getDefaultOpt(cls,fs): + return cls.supportFS.get(fs,{'defaultopt':''})['defaultopt'] + + @classmethod + def checkFSForType(cls,fs,roottype): + return roottype in cls.supportFS.get(fs,{}).get('type',[]) class cltCopy(scanDirectory): """Copy clt files @@ -1295,56 +753,61 @@ class Install(color_print, SignalInterrupt): def setDisks(self,listDisks): """Set data for installation partitions""" - convObj = convertDictOpt(self.clVars) - 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) + lSwaps = [] + lBinds = [] + lDisks = [] + DEVICE,MP,FS,FORMAT = 0,1,2,3 + print "LD",listDisks + listDisks = map(lambda x:x + ['']*(4-len(x)), + listDisks) + for entry in listDisks: + if entry[DEVICE].startswith('/dev'): + if entry[MP] != "swap": + lDisks.append(entry) + else: + lSwaps.append(entry) + else: + lBinds.append(entry[:2]) + + error = lambda *args,**kw: self.errlist.append(InstallError(*args,**kw)) + # break perform if disk params empty and os_install_dev_from empty - if not (listDisks or listSwaps or listBinds): - return True + if not (lDisks or lSwaps or lBinds): + error(_("For installation need specify root device"), + field="disk") + return False - usedDevicesOnlyDisks = map(lambda x:x['dev'],listDisks) - usedDevicesOnlySwap = map(lambda x:x['dev'],listSwaps) - usedDevices = map(lambda x:x['dev'],listSwaps)+usedDevicesOnlyDisks - usedMP = map(lambda x:x['mountPoint'],listDisks) + \ - map(lambda x:x['destMountPoint'],listBinds) - # check mount options for scratch and flash + # check for Incorrect device + wrongDevices = [] + if lDisks + lSwaps: + usedDevices = zip(*(lDisks+lSwaps))[0] + else: + usedDevices = [] + wrongDevices = list(set(usedDevices) - \ + set(self.clVars.Get('os_disk_dev'))) + if wrongDevices: + error(_("Incorrect device '%s'")%wrongDevices[0], + field="disk") + return False + + usedMP = list(zip(*(map(lambda x:x+[""],lDisks+lBinds)))[1]) + # check mount options for scratch if filter(lambda x: x != '/', usedMP): if self.clVars.Get('os_install_scratch') == "on": - raise InstallError( + error( _("Builder mode does not support multipartition install")) - # 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: - raise InstallError( - _("Incorrect device '%s'")%wrongDevices[0]) # detect using extended partition extendedPartitions = map(lambda x: x[1], filter(lambda x: x[0]=="extended", zip(self.clVars.Get('os_disk_part'), self.clVars.Get('os_disk_dev')))) + extendedPartitions = ['/dev/sda4'] usingExtPart = list(set(usedDevices)&set(extendedPartitions)) if usingExtPart: - raise InstallError( + error( _("Unable to use the extended partition %s for installation")% - usingExtPart[0]) + usingExtPart[0],field="disk") # detect using CDROM disks cdromPartitions = map(lambda x: x[1], @@ -1353,9 +816,8 @@ class Install(color_print, SignalInterrupt): self.clVars.Get('os_disk_dev')))) usingCdromPart = list(set(usedDevices)&set(cdromPartitions)) if usingCdromPart: - raise InstallError( - _("Unable to use CDROM %s for installation")% - usingCdromPart[0]) + error(_("Unable to use CDROM %s for installation")% + usingCdromPart[0],field="disk") # detect using RAID member disks raidMemberData = filter(lambda x: "raidmember" in x[0], @@ -1368,13 +830,15 @@ class Install(color_print, SignalInterrupt): raidMemberData)[0][0] raidMemberData = raidMemberData.rpartition("raidmember(")[2] raidMemberData = raidMemberData.partition(")")[0] - raise InstallError([ + error( _("Unable to use active {typepart} member {part} " "for installation").format( - typepart="RAID",part=usingRaidMemberPart[0]), + typepart="RAID",part=usingRaidMemberPart[0]) + +"\n"+ _("To use this partition, you have to stop RAID %s")% - raidMemberData, - (" mdadm -S %s"%raidMemberData)]) + raidMemberData + +"\n"+ + (" mdadm -S %s"%raidMemberData),field="disk") # detect using LVM member disks lvmMemberData = filter(lambda x: "lvmmember" in x[0], @@ -1389,197 +853,177 @@ class Install(color_print, SignalInterrupt): lvmMemberData = lvmMemberData.partition(")")[0] prop = getUdevDeviceInfo(name=lvmMemberData) vgName = prop.get('DM_VG_NAME','') - raise InstallError([ + error( _("Unable to use active {typepart} member {part} " "for installation").format( - typepart="LVM",part=usingLvmMemberPart[0]), + typepart="LVM",part=usingLvmMemberPart[0]) + +"\n"+ _("To use this partition, you have to remove LVM %s")% - lvmMemberData, - (" vgremove %s"%vgName), - (" pvremove %s"%usingLvmMemberPart[0])]) - - srcMountPoints = map(lambda x:x['srcMountPoint'],listBinds) - destMountPoints = map(lambda x:x['destMountPoint'],listBinds) + lvmMemberData + +"\n"+ + (" vgremove %s"%vgName) + +"\n"+ + (" pvremove %s"%usingLvmMemberPart[0]),field="disk") + + # check bind mount points + srcMountPoints = map(lambda x:x[DEVICE],lBinds) + destMountPoints = map(lambda x:x[MP],lBinds) wrongBind = filter(lambda x:x in destMountPoints,srcMountPoints) if wrongBind: incompBind = filter(lambda x:x[1]==wrongBind[0], zip(srcMountPoints,destMountPoints)) - raise InstallError( + error( _("Source directory %(src)s already used " "for binding '%(bindSrc)s' to '%(bindDst)s'")\ %{'src':wrongBind[0], 'bindSrc':incompBind[0][0], - 'bindDst':incompBind[0][1]}) - # Check bind params + 'bindDst':incompBind[0][1]},field="disk") + wrongBind = filter(lambda x:not x[0].startswith("/") or not x[1].startswith("/") and x[1] != "none", zip(srcMountPoints,destMountPoints)) if wrongBind: - raise InstallError( + error( _("Incorrect mount point (bind '%(bindSrc)s' to "\ "'%(bindDst)s')")\ %{'bindSrc':wrongBind[0][0], - 'bindDst':wrongBind[0][1]}) + 'bindDst':wrongBind[0][1]},field="disk") # Check '/' in start path wrongMP = filter(lambda x: not x.startswith("/") and x!="none", usedMP) + \ filter(lambda x: not x.startswith("/"), - map(lambda x:x['srcMountPoint'],listBinds)) + map(lambda x:x[DEVICE],lBinds)) if wrongMP: - raise InstallError(_("Incorrect mount point '%s'")%wrongMP[0]) + error(_("Incorrect mount point '%s'")%wrongMP[0], + field="disk") + # detect duplicate devices dupDevices = list(set(filter(lambda x:usedDevices.count(x)>1, usedDevices))) if dupDevices: - raise InstallError(_("Device '%s' is used twice")%dupDevices[0]) + error(_("Device '%s' is used twice")%dupDevices[0], + field="disk") # detect duplicate mount points dupMP = list(set(filter(lambda x:usedMP.count(x)>1 and x != "none", usedMP))) if dupMP: - raise InstallError(_("Mount point '%s' is used twice")%dupMP[0]) - - rootdevs = map(lambda x:x['dev'], - filter(lambda x:"mountPoint" in x and \ - "dev" in x and \ - x['mountPoint']=='/', - listDisks)) + error(_("Mount point '%s' is used twice")%dupMP[0], + field="disk") + # set root device + rootdevs = map(lambda x:x[DEVICE], + filter(lambda x:x[MP] == '/', + lDisks)) if rootdevs: self.clVars.Set('os_install_root_dev',rootdevs[0],True) - rootType = self.clVars.Get('os_install_root_type') - curRootType = self.clVars.Get('os_root_type') - def clearParam(data,isswap): - if rootType == 'usb-hdd' and curRootType != "usb-hdd": - return "" - if builderMode: - if len(listSwaps) == 0 and isswap == "swap": - return data - else: - if len(listSwaps) == 0 or isswap != "swap": - return data - return "" - - builderMode = self.clVars.Get('os_install_scratch') == "on" - clearBuilder = lambda data,isswap: \ - "" if builderMode and isswap != "swap" else data - # get hash from current variables - 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'), - self.clVars.Get('os_install_disk_format'), - self.clVars.Get('os_install_disk_options')))) - curDevMount = dict(zip(self.clVars.Get('os_disk_dev'), - self.clVars.Get('os_disk_mount'))) - dictMountDev = dict(zip(self.clVars.Get('os_install_disk_mount'), - self.clVars.Get('os_disk_dev'))) - # update current variable by cmd params - for diskData in listDisks+listSwaps: - dev = diskData['dev'] - # skip none swap device - if dev == "none": - continue - mountPoint = diskData.get('mountPoint','swap') - isFormat = diskData['isFormat'] - if mountPoint == "none": - mountPoint = "" - curMP = curDevMount[dev] - if curMP and ( curMP != mountPoint and isFormat or curMP == '/' ): - raise InstallError( - _("Specified disk '%s' mounted to")\ - %dev + " " + _("'%s' in the current system")\ - %curMP) - else: - if mountPoint and mountPoint in dictMountDev and \ - mountPoint != "swap": - devMount[dictMountDev[mountPoint]]['mountPoint'] = '' - devMount[dev]['mountPoint'] = mountPoint - devMount[dev]['options'] = ",".join(diskData['options']) - devMount[dev]['fileSystem'] = diskData['fileSystem'] - if isFormat: - devMount[dev]['isFormat'] = "yes" - - if builderMode: - bindDestSrc = {} - bindSrcDest = {} else: - bindDestSrc =dict(zip(self.clVars.Get('os_install_bind_mountpoint'), - self.clVars.Get('os_install_bind_path'))) - bindSrcDest = dict(zip(self.clVars.Get('os_install_bind_path'), - self.clVars.Get('os_install_bind_mountpoint'))) - - for bindData in listBinds: - srcMountPoint = bindData['srcMountPoint'] - destMountPoint = bindData['destMountPoint'] - if destMountPoint in dictMountDev: - devMount[dictMountDev[destMountPoint]]['mountPoint'] = '' - if destMountPoint == "none" and srcMountPoint in bindSrcDest and \ - bindSrcDest[srcMountPoint] in bindDestSrc: - bindDestSrc.pop(bindSrcDest[srcMountPoint]) - bindSrcDest.pop(srcMountPoint) - else: - bindDestSrc[destMountPoint] = srcMountPoint - if destMountPoint in bindSrcDest: - bindDestSrc.pop(bindSrcDest[destMountPoint]) - bindSrcDest[srcMountPoint] = destMountPoint + error(_("The root partition must be specified"), + field="disk") # update install root dev - rootDev = filter(lambda x:x[1]['mountPoint']=='/',devMount.items()) - if not rootDev: - 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') + mapCurrent = dict(map(lambda x:(x[DEVICE],(x[MP],x[FS])), + self.clVars.zipVars('os_disk_dev', + 'os_disk_mount', + 'os_disk_format'))) + lDisks = lDisks + lSwaps + for diskData in lDisks: + # if fs not specified + curMP = mapCurrent[diskData[DEVICE]][0] + if curMP == '/': + error( + _("The current root partition %s can not be " + "used for installation")% + diskData[DEVICE], field="disk") + curFS = mapCurrent[diskData[DEVICE]][1] + print diskData + if diskData[FS] == '': + # if current deivce has fs + if curFS: + # install filesystem is current + diskData[FS] = curFS + if diskData[MP] == '/': + diskData[FORMAT] = 'yes' + else: + # install filesystem is default + diskData[FS] = FileSystemManager.defaultFS[osInstallRootType] + if diskData[FORMAT] == 'no': + error( + _("Disk %s without filesystem should be formatted"% + diskData[DEVICE], field="disk")) + diskData[FORMAT] = 'yes' + else: + compatibleFS = \ + FileSystemManager.supportFS.get(diskData[FS],{}) + compatibleFS = compatibleFS.get('compatible',[]) + [curFS] + # if fs specified but format no specified + if diskData[FORMAT] == '': + # if fs equal current fs or + # current fs compatible with specified fs + if diskData[FS] in compatibleFS and diskData[MP] != '/': + diskData[FORMAT] = 'no' + else: + diskData[FORMAT] = 'yes' + print diskData + if not diskData[FS] in self.clVars.Get('os_format_type'): + error(_("Unsupported file system %s")%diskData[FS], + field="disk") + else: + if not diskData[FS] in map(lambda x:x[0], + filter(lambda x:x[1] == 'yes', + self.clVars.zipVars('os_format_type', + 'os_format_use'))): + error(_("File system '%s' is not available")%diskData[FS], + field="disk") + if not FileSystemManager.checkFSForType(diskData[FS], + osInstallRootType): + error( + _("File system for '%(mp)s' should not be '%(opt)s'") + %{'mp':diskData[MP], 'opt':diskData[FS]},field="disk") + if curMP: + if diskData[FORMAT] == 'yes' and curMP != '/': + error(_("Disk {device} should be formatted, but can " + "not be formatted because mounted to " + "{mountpoint} in the current system").format( + device=diskData[DEVICE],mountpoint=curMP), + field="disk") + if diskData[FORMAT] == 'no': + if not diskData[FS] in compatibleFS: + error(_("Disk {device} should be formatted").format( + device=diskData[DEVICE]),field="disk") + # update bind variables by new hash - if osInstallRootType != "flash": - new_bind_dest, new_bind_src = \ - reduce(lambda x,y:[x[0]+[y[0]],x[1]+[y[1]]], - sorted(bindDestSrc.items()) , - [[]]*2) - # discard all bind point for flash installation - else: - new_bind_dest = [] - new_bind_src = [] + if osInstallRootType == "flash": if filter(lambda x: x != '/', usedMP): - raise InstallError( - _("Installation to flash disk is not supported for " - "multipartition install")) - if filter(lambda x:x['dev']!="none",listSwaps): - raise InstallError( - _("Installation to flash disk is not " - "supported for swap disks")) + error(_("Installation to flash disk is not supported for " + "multipartition install"),field="disk") + if lSwaps: + error(_("Installation to flash disk is not " + "supported for swap disks"),field="disk") if builderMode: - raise InstallError( - _("Installation to flash disk is not supported" - " in builder mode")) - # receive substitution func. Discard all mp, exclude '/' for flash - if osInstallRootType != "flash": - substitution = lambda data,mp: data - else: - substitution = lambda data,mp: data if mp == '/' else "" - separateDevice = lambda device: map( - lambda x: int(x) if x.isdigit() else x, - re.findall('\d+|\D+',device)) - # update variables by new hash - new_mount, new_format, new_isformat, new_options= \ - reduce(lambda x,y:[x[0]+[substitution(devMount[y]['mountPoint'], - devMount[y]['mountPoint'])], - x[1]+[substitution(devMount[y]['fileSystem'], - devMount[y]['mountPoint'])], - x[2]+[substitution(devMount[y]['isFormat'], - devMount[y]['mountPoint'])], - x[3]+[substitution(devMount[y]['options'], - devMount[y]['mountPoint'])]], - sorted(devMount.keys(),key=separateDevice),[[]]*4) - + error(_("Installation to flash disk is not supported" + " in builder mode"),field="disk") + diskDev = self.clVars.Get('os_disk_dev') + mapInstallData = dict(map(lambda x:(x[DEVICE],(x[MP],x[FS],x[FORMAT])), + lDisks)) + new_mount = map(lambda x: mapInstallData.get(x,['']*3)[MP-1],diskDev) + new_format = map(lambda x: mapInstallData.get(x,['']*3)[FS-1],diskDev) + new_isformat = \ + map(lambda x: mapInstallData.get(x,['']*3)[FORMAT-1],diskDev) + new_options = map(lambda x:FileSystemManager.getDefaultOpt(x[1]) \ + if x[0] else '', + zip(new_mount,new_format)) + + new_bind_src = map(lambda x:x[0], + filter(lambda x: not x[1] in ("","none"), + lBinds)) + new_bind_dest = map(lambda x:x[1], + filter(lambda x: not x[1] in ("","none"), + lBinds)) map(lambda x:self.clVars.Set(x[0],x[1],True), (('os_install_disk_mount',new_mount), ('os_install_disk_mount',new_mount), @@ -1588,10 +1032,13 @@ class 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'): - self.checkForLegacyGrub() - else: - self.checkForGrub2() + try: + if not self.clVars.Get('os_grub2_path'): + self.checkForLegacyGrub() + else: + self.checkForGrub2() + except InstallError,e: + error.append(e) return True def checkForGrub2(self): @@ -1606,13 +1053,13 @@ class Install(color_print, SignalInterrupt): raise InstallError( _("Grub does not support booting from a RAID assembled from LVM.") + " " + - _("Try to use a separate /boot partition")) + _("Try to use a separate /boot partition"),field="disk") if grubDiskType.count("raid")>1: raise InstallError( _("Grub does not support booting from a RAID assembled " "from another RAID.") + " " + - _("Try to use a separate /boot partition")) + _("Try to use a separate /boot partition"),field="disk") return True def checkForLegacyGrub(self): @@ -1629,15 +1076,15 @@ class Install(color_print, SignalInterrupt): bootDiskType = bootDiskType or rootDiskType bootDiskFormat = bootDiskFormat or rootDiskFormat if "lvm" in bootDiskType or "raid" in bootDiskType: - self.printERROR( + raise InstallError( _("Legacy grub does not support boot from raid or lvm " - "without separate /boot partition")) - return False + "without separate /boot partition"), + field="disk") if bootDiskFormat in ("btrfs","nilfs2"): - self.printERROR( + raise InstallError( _("Legacy grub does not support booting from %s without " - "separate /boot partition")%bootDiskFormat) - return False + "separate /boot partition")%bootDiskFormat, + field="disk") return True def setUsers(self,listUsers,autologinUser): @@ -1657,21 +1104,6 @@ class Install(color_print, SignalInterrupt): self.clVars.Set('cl_migrate_user', migrateUsers, force=True) return True - 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: - if filter(lambda x: x == mbrDisk, - self.clVars.Get('os_device_dev')): - self.clVars.Set('os_install_mbr', mbrDisk, force=True) - else: - self.printERROR(_("Failed to find disk '%s'")%mbrDisk) - return False - return True - def createListOptions(self): """Create listDisksOptions, listSwapsOptions and listBindOptions by variables""" @@ -2262,7 +1694,6 @@ class Install(color_print, SignalInterrupt): objDesktop.createClVars() res = objDesktop.installProg() self.showStdout() - self.printByResult(res) # install client package if linuxShortname in ("CLD","CLDG","CLDX"): @@ -2399,43 +1830,97 @@ class Install(color_print, SignalInterrupt): raise InstallError(_("Failed to migrate users to the new system")) self.printByResult(True) - def checkCorrectBootRecordDisk(self): - """Check boot record disk""" - mbr = self.clVars.Get('os_install_mbr') - if mbr == "off" or mbr == "": - return True - tableOnBootDisk = self.varSelect('os_device_table', - where="os_device_dev",eq=mbr) - if not tableOnBootDisk: - self.printERROR(_("Disk '%s' without partition table " - "contains no boot record")%mbr) - return False + def setBR(self, mbrDisks): + """Set boot record on disk by param or get from variables""" + bootDiskGrub = "" + for mbrDisk in mbrDisks: + if mbrDisk == "off": + self.clVars.Set('os_install_mbr',"",force=True) + return True + elif mbrDisk: + if not filter(lambda x: x == mbrDisk, + self.clVars.Get('os_device_dev')): + self.errlist.append(InstallError( + _("Failed to find disk '%s'")%mbrDisk, + field="mbr")) + return False + tableOnBootDisk = self.varSelect('os_device_table', + where="os_device_dev",eq=mbr) + if not tableOnBootDisk: + self.errlist.append( + _("Disk '%s' without partition table " + "contains no boot record")%mbrDisk,field="mbr") + self.clVars.Set('os_install_mbr', mbrDisks, force=True) return True - def checkInstallParam(self,disks=None,mbr=None,builder=None,typeDisk=None): + def setBuilder(self,builder): + if builder: + self.logicObj.clVars.Set('os_install_scratch',"on",True) + else: + self.logicObj.clVars.Set('os_install_scratch',"off",True) + + def setDiskType(self,disktype): + trueType = FileSystemManager.defaultFS.keys() + if not disktype in trueType: + self.errlist.append( + InstallError( + _("Disk type should be {head} or {tail}").format( + head=trueType[:-1],tail=trueType[-1]), + field="type")) + return False + else: + self.logicObj.clVars.Set('os_install_root_type',disktype,True) + return True + + def _convertErrors(self,errlist): errors = [] - if disks: - try: - self.setDisks(disks) - except InstallError,e: - errors.append('disks',e) + for err in errlist: + if err.field: + errors.append([err.field,str(err)]) + else: + errors.append(["",str(err)]) return errors + def checkInstallParam(self,disks=None,mbr=None,builder=None,typeDisk=None): + self.errlist = [] + try: + if typeDisk: + self.setDiskType(typeDisk) + if not builder is None: + self.setBuilder(builder) + if disks: + self.setDisks(disks) + if mbr: + self.setBR(mbr) + except InstallError,e: + self.errlist.append(e) + return self._convertErrors(self.errlist) + + def getCurrentPartitioning(self): + MOUNTPOINT,DEVICE,MAKEFORMAT,FORMAT,LABLE,SIZE = 0,1,2,3,4,5 + body = filter(lambda x:x[MOUNTPOINT], + self.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 = {'head':[_("Partition"),_("Mount point"), + _("Filesystem"),_("Perform format"), + _("Label"),_("Size")], + 'body':body} + return table + + 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 targetDistr = None error = None distrCopy = False - if not self.checkCorrectBootRecordDisk(): - return False try: + self.createListOptions() rootPartdev = self.clVars.Get('os_install_root_dev') rootPartCmdList = filter(lambda x: x['dev']==rootPartdev, self.listDisksOptions) @@ -2447,6 +1932,7 @@ class Install(color_print, SignalInterrupt): rootPartSystemId=rootPartCmdDict['systemId'] self.printInfo(update=update) + return [] targetDistr = self.getTargetDistributive(rootPartdev, buildermode=builder, @@ -2570,7 +2056,7 @@ the system") + " (yes/no)" def setAllLocaleByLang(self,lang): """Set all locale variable by specified lang""" - locale = clLocale() + locale = Locale() if not lang in self.clVars.Get('os_install_lang'): return False self.clVars.Set('os_install_locale_lang',lang, True) diff --git a/install/cl_vars_install.py b/install/cl_vars_install.py index c573339..fc91167 100644 --- a/install/cl_vars_install.py +++ b/install/cl_vars_install.py @@ -19,422 +19,21 @@ # hide - flag, if it is True, then the variable is not printable # printval - print value of variable from cl_install import __version__, __app__ - -class Data: - # relative path for apply templates on files of system - cl_root_path = {} - +from calculate.lib.cl_vars import Data as LibData +from calculate.lib.cl_datavars import Variables +from calculate.lib.variables import System, Net, Env, X11 +from calculate.install.variables import (InstallAction, InstallLocale, + Distribute,InstallKernel,InstallX11,InstallNet, + InstallSystem,InstallLinux,InstallDisk) + +class Data(InstallAction,InstallLocale,Distribute,InstallKernel, + InstallX11,InstallNet,InstallSystem,InstallLinux, + InstallDisk,LibData): + section = "install" + + vars = ["cl_name","cl_ver"] # program name cl_name = {'value':__app__} # program version cl_ver = {'value':__version__} - - """ - Action variable which has value "up" by default and not flash installation - """ - ac_install_merge = {} - - """ - Action variable which has value "up" for installation on hdd - """ - ac_install_system = {} - - """ - Action variable which has value "up" for USB flash - """ - ac_install_flash = {} - - """ - Action which "up" value describe dinamic templates - """ - ac_install_live = {} - - # install maching architecture - os_install_arch_machine = {'mode':'w'} - - # inforamation about net interfaces - os_net_interfaces_info = {} - - # infomation about disk in hash - os_device_hash = {'hide':True} - - # infomation about disk in hash - os_disk_hash = {'hide':True} - - # list of available partition devices - os_disk_dev = {} - - # list mounted points for installed system - os_install_disk_mount = {} - - # 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 = {} - - # need format - os_install_disk_perform_format = {} - - # uudi for install - os_install_disk_uuid = {} - - # /dev/sd or UUID= list (by cl_uuid_set) - os_install_disk_use = {} - - cl_uuid_set = {'value':'on'} - - # install partition's system id - os_install_disk_id = {} - - # list uudi for partition devices - os_disk_uuid = {} - - # partition's system id - os_disk_id = {} - - # disk for boot mbr - os_install_mbr = {} - - # list grub id for partition devices - os_disk_grub = {} - - # install list grub id for partition devices (depend from mbr) - os_install_disk_grub = {} - - # type of partition devices (primary, extended or logical) - os_disk_part = {} - - # partition table on parent device - os_disk_table = {} - - # partition size - os_disk_size = {} - - # label of partitions - os_disk_name = {} - - # list mount options - os_disk_options = {} - - # devices - os_device_dev = {} - - # device type (hdd,cdrom,usb-flash) - os_device_type = {} - - # map number for grub - os_device_map = {} - - # table for device - os_device_table = {} - - # name of device - os_device_name = {} - - # content of device.map file for grub - os_install_grub_devicemap_conf = {} - - # information about mount points for fstab - os_install_fstab_mount_conf = {} - - # information about swap for fstab - os_install_fstab_swap_conf = {} - - # content of /etc/conf.d/net - #os_net_config_info = {} - - # install scheduler - os_install_kernel_scheduler = {} - - # install kernel attributes - os_install_kernel_attr = {} - - # install kernel resume - os_install_kernel_resume = {} - - # system image for installation - cl_image = {} - - # path which contains images - cl_image_path = {} - - # DISTFILES value - cl_distfiles_path = {'mode':'w', - 'value':'/var/calculate/remote/distfiles'} - # PKGDIR value - cl_pkgdir_path = {'mode':'w'} - - # LINGUAS value - os_install_linguas = {'mode':'w'} - - # linux version of installation os - os_install_linux_ver = {'mode':'r'} - - # linux build of installation os - os_install_linux_build = {'mode':'r'} - - # subname of installation os - os_install_linux_subname = {'mode':'w'} - - # shortname of installation os - os_install_linux_shortname = {'mode':'w'} - - # name of installation os - os_install_linux_name = {'mode':'w'} - - # installation os system: server or desktop - os_install_linux_system = {} - - # root device of installed os - os_install_root_dev = {} - - # root device of previous installed os - os_install_dev_from = {} - - # list mount options of installed os - os_install_disk_options = {} - - # - os_bind_hash = {'hide':True} - - # directories for bind - os_bind_path = {} - - # mountpoint for directories bind - os_bind_mountpoint = {} - - os_install_bind_hash = {'hide':True} - - # install directories for bind - os_install_bind_path = {} - - # mountpoint for install directories bind - os_install_bind_mountpoint = {} - - # busid of video card - hr_video_id = {'value':""} - - # timezone for clock - os_install_clock_timezone = {'mode':'w'} - - # type of clock (UTC or local) - os_install_clock_type = {'mode':'w'} - - # xorg resolution - os_install_x11_resolution = {} - - # fb resolution - os_install_fb_resolution = {'mode':'w'} - - # makeconf makeopts - os_install_makeopts = {'mode':'w'} - - # Video driver used by xorg - os_install_x11_video_drv = {'mode':'w'} - - # on/off composite - os_install_x11_composite = {'mode':'w'} - - # consolefont - os_install_locale_consolefont = {} - - # keymap of locale (used for /etc/conf.d/keymaps) - os_install_locale_keymap = {} - - # dumpkeys_charset for keymap - os_install_locale_dumpkeys = {} - - # locale (at example: ru_RU.UTF-8) - os_install_locale_locale = {} - - # full language (at example: ru_RU) - os_install_locale_lang = {} - - # short language (at example ru) - os_install_locale_language = {} - - # keyboard layout for X server - os_install_locale_xkb = {} - - # keyboard layout name for X server - os_install_locale_xkbname = {} - - # hash for information about net - os_install_net_hash = {} - - # computer hostname - os_install_net_hostname = {'mode':"w"} - - # allowed network - os_install_net_allow ={} - - # net interfaces - os_install_net_interfaces={} - - # net device name - os_install_net_name={} - - # net devices mac - os_install_net_mac={} - - # ip for all network interfaces - os_install_net_ip = {} - - # network for ip - os_install_net_network = {} - - # ip cidr - os_install_net_cidr = {} - - # routing - os_install_net_route_hash = {} - - # net for route - os_install_net_route_network = {} - - # gw for route - os_install_net_route_gw = {} - - # dev for route - os_install_net_route_dev = {} - - # src for route - os_install_net_route_src = {} - - # data by route for conf.d/net - os_install_net_route = {'hide':True} - - # data by route for NetworkManager - os_install_net_nmroute = {'hide':True} - - # dns servers - os_install_net_dns = {} - - # net setup (networkmanager or openrc) - os_install_net_conf = {} - - # net service configured - os_install_net_settings = {'mode':'w', - 'value':''} - - # dhcp or not - os_install_net_dhcp_set = {} - - # dns search - os_install_net_dns_search = {'mode':"w"} - - # domain - os_install_net_domain = {'mode':"w"} - - # 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':''} - - # nt server for system - os_install_ntp = {'mode':'w', - 'value':'ntp0.zenon.net'} - - # kernel filename - os_install_kernel = {} - - # optimized initramfs filename - os_install_initrd = {} - - # install initramfs filename - os_install_initrd_install = {} - - # install config kernel filename - os_install_kernel_config = {} - - # install system map filename - os_install_system_map = {} - - # install kernel uid - cl_install_kernel_uid = {} - - # filesystem format support by calcualte-install - os_format_type = {} - - # avialable format by mkfs utility - os_format_use = {} - - # supported languages - os_install_lang = {} - - # current grub - os_grub_conf = {} - - # grub2 install path - os_grub2_path = {'mode':'w'} - - # grub chroot need for grub-mkconfig - cl_chroot_grub = {} - - # migrate users - cl_migrate_user = {} - - # migrate users who need to change passwords - cl_migrate_user_pwd = {} - - # install system in scratch mode - os_install_scratch = {} - - # nvidia-drivers atom mask - os_nvidia_mask = {} - - # (on or off) autoupdate config from install program - cl_autoupdate_set = {'value': "off"} - - # (on or off) autoupdate config from install program for install - cl_install_autoupdate_set = {'mode':'w','value': "off"} - - # variable for autologin - cl_autologin = {} - - # lib vars - os_locale_xkb = {} - hr_video = {} - hr_video_name = {} - os_linux_name = {} - os_scratch = {} - os_x11_video_drv = {} - hr_cpu_num = {} - os_locale_locale = {} - os_net_interfaces = {} - cl_template_clt_path = {} - os_linux_ver = {} - os_net_allow = {} - cl_kernel_uid = {} - os_arch_machine = {} - cl_template_path = {} - os_net_hostname = {'mode':"w"} - cl_chroot_path = {'mode':"w"} - cl_env_path = {} - os_root_dev = {} - os_linux_shortname = {} - os_net_ip = {} - os_root_type = {} - hr_laptop = {} - hr_laptop_model = {} - os_locale_language = {} - cl_root_path = {'mode':"w"} diff --git a/install/cl_wsdl_install.py b/install/cl_wsdl_install.py index a51ef4f..eab8716 100644 --- a/install/cl_wsdl_install.py +++ b/install/cl_wsdl_install.py @@ -15,13 +15,16 @@ # limitations under the License. import soaplib, sys, time, os +import threading 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 +import cl_install from calculate.lib.cl_lang import setLocalTranslate +from calculate.api.server.decorators import Dec setLocalTranslate('cl_install',sys.modules[__name__]) ##########API######################## @@ -48,10 +51,11 @@ class Field(ClassSerializer): opt = Option help = String element = String - choice = Array(String) + choice = ChoiceValue default = String value = String tablevalue = Table + listvalue = Array(String) class GroupField(ClassSerializer): name = String @@ -91,62 +95,55 @@ class InstallInfo(ClassSerializer): timezone = String default = Array(String) -class FieldError(ClassSerializer): - field = String - error = String +class ReturnedMessage(ClassSerializer): + """type (error,warning,pid)""" + type = String + name = String + message = String class Wsdl: - @rpc(String,Integer,InstallInfo,Boolean,_returns=Array(FieldError)) + @rpc(Integer,InstallInfo,Boolean,_returns=Array(ReturnedMessage)) #@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() + def install_system(self,sid,param,onlycheck): + reload(cl_install) + install = cl_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): + errors = [] + for err in install.checkInstallParam(param.disk, + param.mbr, + param.type, + param.build): + errors.append(ReturnedMessage( + type="error", + name=err[0], + message=err[1])) + if not onlycheck and not errors: + install.installSystem(param.disk,param.mbr,param.type,param.build) + return errors + + def getPartitionInfo(self,install): 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")) + installTable = install.getCurrentPartitioning() + table = Table(head = installTable['head'], + body = installTable['body'], + values = []) table.values.append(ChoiceValue( - values=clVars.Get('os_disk_dev'), + values=install.clVars.Get('os_disk_dev'), comments = map(lambda x:"%s - %s - %s"% (x[DEVICE],x[FORMAT],x[SIZE]), - body), + installTable['body']), type="choice")) table.values.append(ChoiceValue( - values=[_("yes"),_("no")], + type="string")) + table.values.append(ChoiceValue( + values=install.clVars.Get('os_format_type'), type="choice")) table.values.append(ChoiceValue( - values=clVars.Get('os_format_type'), + values=[_("yes"),_("no")], type="choice")) return table @@ -163,13 +160,15 @@ class Wsdl: 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) + @rpc(Integer,Integer,_returns=ViewInfo) + #@check_permissions('cl_install') + def install_system_view(self,sid,page): + threading.currentThread().lang = "ru" view = ViewInfo(groups=[]) install = Install() install.initVars() - if not page is None or page == 0: + + if page is None or page == 0: group = GroupField(name=_("Partitioning"),nextlabel=_("Next")) group.fields = [] group.fields.append(Field( @@ -185,7 +184,7 @@ class Wsdl: "creating bind mount point you have to specify the " "source directory as DISK"), element = "table", - tablevalue = self.getPartitionInfo(install.clVars))) + tablevalue = self.getPartitionInfo(install))) group.fields.append(Field( name = "mbr", label = _("MBR"), @@ -196,6 +195,7 @@ class Wsdl: _("boot disk for the system bound for install (for " "recording MBR), off - disable MBR writing"), element = "select", + listvalue = install.clVars.Get('os_install_mbr'), choice = self.getDeviceChoice(install.clVars))) group.fields.append(Field( name = "type", @@ -206,10 +206,12 @@ class Wsdl: help = \ _("device type for the system bound for install"), element = "choice", + value = install.clVars.Get('os_install_root_type'), choice = self.getDeviceTypesChoice())) view.groups.append(group) - if not page is None or page == 1: + if page is None or page == 1: group = GroupField(name=_("System"),last=True,nextlable=_("Install")) + group.fields = [] group.fields.append(Field( name = "build", label = _("Builder mode"), @@ -217,6 +219,7 @@ class Wsdl: opt = Option(longopt="--build"), help = \ _("installation for assemble"), + value = install.clVars.Get('os_install_scratch'), element = "checkbox")) view.groups.append(group) return view diff --git a/install/variables/X11.py b/install/variables/X11.py new file mode 100644 index 0000000..0eb88d4 --- /dev/null +++ b/install/variables/X11.py @@ -0,0 +1,42 @@ +#-*- coding: utf-8 -*- + +# Copyright 2008-2012 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 sys +from os import path +from calculate.lib.cl_datavars import Variables +from calculate.lib.variables import X11 + +from calculate.lib.cl_lang import setLocalTranslate +setLocalTranslate('cl_install',sys.modules[__name__]) + +class InstallX11(X11): + vars = ["os_install_x11_resolution","os_install_x11_video_drv", + "os_install_x11_composite","os_install_fb_resolution","hr_video_id"] + # xorg resolution + os_install_x11_resolution = {} + + # Video driver used by xorg + os_install_x11_video_drv = {'mode':'w'} + + # on/off composite + os_install_x11_composite = {'mode':'w'} + + # fb resolution + os_install_fb_resolution = {'mode':'w'} + + # busid of video card + hr_video_id = {'value':""} diff --git a/install/variables/__init__.py b/install/variables/__init__.py new file mode 100644 index 0000000..3801d1f --- /dev/null +++ b/install/variables/__init__.py @@ -0,0 +1,9 @@ +from action import InstallAction +from disk import InstallDisk +from distr import Distribute +from kernel import InstallKernel +from linux import InstallLinux +from locale import InstallLocale +from net import InstallNet +from system import InstallSystem +from X11 import InstallX11 diff --git a/install/variables/action.py b/install/variables/action.py new file mode 100644 index 0000000..b7b939a --- /dev/null +++ b/install/variables/action.py @@ -0,0 +1,81 @@ +#-*- coding: utf-8 -*- + +# Copyright 2008-2012 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 sys +from os import path +from calculate.lib.cl_datavars import Variables + +from calculate.lib.cl_lang import setLocalTranslate +setLocalTranslate('cl_install',sys.modules[__name__]) + +class InstallAction(Variables): + vars = ["ac_install_merge","ac_install_system","ac_install_flash", + "ac_install_live"] + """ + Action variable which has value "up" by default and not flash installation + """ + ac_install_merge = {} + + """ + Action variable which has value "up" for installation on hdd + """ + ac_install_system = {} + + """ + Action variable which has value "up" for USB flash + """ + ac_install_flash = {} + + """ + Action which "up" value describe dinamic templates + """ + ac_install_live = {} + + def get_ac_install_merge(self): + """Need perform templates for install:merge or install:unmerge""" + actionsMap = {'merge':'up', + 'system':'up'} + cl_action = self.Get('cl_action') + if cl_action == 'system' and \ + self.Get('os_install_root_type') == 'flash': + return "" + return actionsMap.get(cl_action,'') + + def get_ac_install_system(self): + """Need perform templates for install:system""" + if self.Get('cl_action') == 'system' and \ + self.Get('os_install_root_type') != "flash": + return "up" + else: + return "" + + def get_ac_install_flash(self): + """Need perform templates for install:flash""" + clAction = self.Get('cl_action') + if clAction == 'system' and self.Get('os_install_root_type') == 'flash': + return "up" + return "" + + def get_ac_install_live(self): + """Need perform templates for install:live""" + if self.Get('ac_install_merge') == "up" and \ + self.Get('cl_chroot_status') == "off" or \ + self.Get('cl_action') == 'live': + return "up" + else: + return "" + diff --git a/install/variables/disk.py b/install/variables/disk.py new file mode 100644 index 0000000..90ff45c --- /dev/null +++ b/install/variables/disk.py @@ -0,0 +1,148 @@ +#-*- coding: utf-8 -*- + +# Copyright 2008-2012 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 sys +from os import path +from calculate.lib.cl_datavars import Variables + +from calculate.lib.cl_lang import setLocalTranslate +setLocalTranslate('cl_install',sys.modules[__name__]) + +class InstallDisk(Variables): + vars = ["os_device_hash","os_disk_hash","os_disk_dev", + "os_install_disk_mount","os_disk_mount","os_disk_content", + "os_disk_format","os_disk_type","os_install_disk_format", + "os_install_disk_perform_format","os_install_disk_uuid", + "os_install_disk_use","cl_uuid_set","os_install_disk_id", + "os_disk_uuid","os_disk_id","os_install_mbr","os_disk_grub", + "os_install_disk_grub","os_disk_part","os_disk_table", + "os_disk_size","os_disk_name","os_disk_options","os_device_dev", + "os_device_type","os_device_map","os_device_table","os_device_name", + "os_install_disk_options","os_bind_hash","os_bind_path","os_bind_mountpoint", + "os_install_bind_hash","os_install_bind_path","os_install_bind_mountpoint", + "os_install_fstab_mount_conf","os_install_fstab_swap_conf"] + # infomation about disk in hash + os_device_hash = {'hide':True} + + # infomation about disk in hash + os_disk_hash = {'hide':True} + + # list of available partition devices + os_disk_dev = {} + + # list mounted points for installed system + os_install_disk_mount = {} + + # 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 = {} + + # need format + os_install_disk_perform_format = {} + + # uudi for install + os_install_disk_uuid = {} + + # /dev/sd or UUID= list (by cl_uuid_set) + os_install_disk_use = {} + + cl_uuid_set = {'value':'on'} + + # install partition's system id + os_install_disk_id = {} + + # list uudi for partition devices + os_disk_uuid = {} + + # partition's system id + os_disk_id = {} + + # disk for boot mbr + os_install_mbr = {} + + # list grub id for partition devices + os_disk_grub = {} + + # install list grub id for partition devices (depend from mbr) + os_install_disk_grub = {} + + # type of partition devices (primary, extended or logical) + os_disk_part = {} + + # partition table on parent device + os_disk_table = {} + + # partition size + os_disk_size = {} + + # label of partitions + os_disk_name = {} + + # list mount options + os_disk_options = {} + + # devices + os_device_dev = {} + + # device type (hdd,cdrom,usb-flash) + os_device_type = {} + + # map number for grub + os_device_map = {} + + # table for device + os_device_table = {} + + # name of device + os_device_name = {} + + # list mount options of installed os + os_install_disk_options = {} + + os_bind_hash = {'hide':True} + + # directories for bind + os_bind_path = {} + + # mountpoint for directories bind + os_bind_mountpoint = {} + + os_install_bind_hash = {'hide':True} + + # install directories for bind + os_install_bind_path = {} + + # mountpoint for install directories bind + os_install_bind_mountpoint = {} + + # information about mount points for fstab + os_install_fstab_mount_conf = {} + + # information about swap for fstab + os_install_fstab_swap_conf = {} + diff --git a/install/variables/distr.py b/install/variables/distr.py new file mode 100644 index 0000000..abffc37 --- /dev/null +++ b/install/variables/distr.py @@ -0,0 +1,32 @@ +#-*- coding: utf-8 -*- + +# Copyright 2008-2012 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 sys +from os import path +from calculate.lib.cl_datavars import Variables + +from calculate.lib.cl_lang import setLocalTranslate +setLocalTranslate('cl_install',sys.modules[__name__]) + +class Distribute(Variables): + vars = ["cl_image","cl_image_path"] + # system image for installation + cl_image = {} + + # path which contains images + cl_image_path = {} + diff --git a/install/variables/kernel.py b/install/variables/kernel.py new file mode 100644 index 0000000..560225c --- /dev/null +++ b/install/variables/kernel.py @@ -0,0 +1,56 @@ +#-*- coding: utf-8 -*- + +# Copyright 2008-2012 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 sys +from os import path +from calculate.lib.cl_datavars import Variables + +from calculate.lib.cl_lang import setLocalTranslate +setLocalTranslate('cl_install',sys.modules[__name__]) + +class InstallKernel(Variables): + vars = ["os_install_kernel_scheduler","os_install_kernel_attr", + "os_install_kernel_resume","os_install_kernel","os_install_initrd", + "os_install_initrd_install","os_install_kernel_config", + "os_install_system_map","cl_install_kernel_uid"] + # install scheduler + os_install_kernel_scheduler = {} + + # install kernel attributes + os_install_kernel_attr = {} + + # install kernel resume + os_install_kernel_resume = {} + + # kernel filename + os_install_kernel = {} + + # optimized initramfs filename + os_install_initrd = {} + + # install initramfs filename + os_install_initrd_install = {} + + # install config kernel filename + os_install_kernel_config = {} + + # install system map filename + os_install_system_map = {} + + # install kernel uid + cl_install_kernel_uid = {} + diff --git a/install/variables/linux.py b/install/variables/linux.py new file mode 100644 index 0000000..0df0ed5 --- /dev/null +++ b/install/variables/linux.py @@ -0,0 +1,47 @@ +#-*- coding: utf-8 -*- + +# Copyright 2008-2012 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 sys +from os import path +from calculate.lib.cl_datavars import Variables +from calculate.lib.variables import Linux + +from calculate.lib.cl_lang import setLocalTranslate +setLocalTranslate('cl_install',sys.modules[__name__]) + +class InstallLinux(Linux): + vars = ["os_install_linux_ver","os_install_linux_build", + "os_install_linux_subname","os_install_linux_shortname", + "os_install_linux_name","os_install_linux_system"] + # linux version of installation os + os_install_linux_ver = {'mode':'r'} + + # linux build of installation os + os_install_linux_build = {'mode':'r'} + + # subname of installation os + os_install_linux_subname = {'mode':'w'} + + # shortname of installation os + os_install_linux_shortname = {'mode':'w'} + + # name of installation os + os_install_linux_name = {'mode':'w'} + + # installation os system: server or desktop + os_install_linux_system = {} + diff --git a/install/variables/locale.py b/install/variables/locale.py new file mode 100644 index 0000000..bce7eb1 --- /dev/null +++ b/install/variables/locale.py @@ -0,0 +1,69 @@ +#-*- coding: utf-8 -*- + +# Copyright 2008-2012 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 sys +from os import path +from calculate.lib.cl_datavars import Variables +from calculate.lib.variables import Locale + +from calculate.lib.cl_lang import setLocalTranslate +setLocalTranslate('cl_install',sys.modules[__name__]) + +class InstallLocale(Locale): + vars = ["os_install_linguas", "os_install_locale_consolefont", + "os_install_locale_keymap", "os_install_locale_dumpkeys", + "os_install_locale_locale", "os_install_locale_lang", + "os_install_locale_language", "os_install_locale_xkb", + "os_install_locale_xkbname", "os_install_clock_timezone", + "os_install_clock_type", "os_install_lang"] + + # LINGUAS value + os_install_linguas = {'mode':'w'} + + # consolefont + os_install_locale_consolefont = {} + + # keymap of locale (used for /etc/conf.d/keymaps) + os_install_locale_keymap = {} + + # dumpkeys_charset for keymap + os_install_locale_dumpkeys = {} + + # locale (at example: ru_RU.UTF-8) + os_install_locale_locale = {} + + # full language (at example: ru_RU) + os_install_locale_lang = {} + + # short language (at example ru) + os_install_locale_language = {} + + # keyboard layout for X server + os_install_locale_xkb = {} + + # keyboard layout name for X server + os_install_locale_xkbname = {} + + # timezone for clock + os_install_clock_timezone = {'mode':'w'} + + # type of clock (UTC or local) + os_install_clock_type = {'mode':'w'} + + # supported languages + os_install_lang = {} + diff --git a/install/variables/net.py b/install/variables/net.py new file mode 100644 index 0000000..ade961d --- /dev/null +++ b/install/variables/net.py @@ -0,0 +1,107 @@ +#-*- coding: utf-8 -*- + +# Copyright 2008-2012 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 sys +from os import path +from calculate.lib.cl_datavars import Variables +from calculate.lib.variables import Net + +from calculate.lib.cl_lang import setLocalTranslate +setLocalTranslate('cl_install',sys.modules[__name__]) + +class InstallNet(Net): + vars = ["os_net_interfaces_info","os_install_net_hash", + "os_install_net_hostname","os_install_net_allow", + "os_install_net_interfaces","os_install_net_name", + "os_install_net_mac","os_install_net_ip","os_install_net_network", + "os_install_net_cidr","os_install_net_route_hash", + "os_install_net_route_network","os_install_net_route_gw", + "os_install_net_route_dev","os_install_net_route_src", + "os_install_net_route","os_install_net_nmroute", + "os_install_net_dns","os_install_net_conf", + "os_install_net_settings","os_install_net_dhcp_set", + "os_install_net_dns_search","os_install_net_domain"] + # inforamation about net interfaces + os_net_interfaces_info = {} + + # hash for information about net + os_install_net_hash = {} + + # computer hostname + os_install_net_hostname = {'mode':"w"} + + # allowed network + os_install_net_allow ={} + + # net interfaces + os_install_net_interfaces={} + + # net device name + os_install_net_name={} + + # net devices mac + os_install_net_mac={} + + # ip for all network interfaces + os_install_net_ip = {} + + # network for ip + os_install_net_network = {} + + # ip cidr + os_install_net_cidr = {} + + # routing + os_install_net_route_hash = {} + + # net for route + os_install_net_route_network = {} + + # gw for route + os_install_net_route_gw = {} + + # dev for route + os_install_net_route_dev = {} + + # src for route + os_install_net_route_src = {} + + # data by route for conf.d/net + os_install_net_route = {'hide':True} + + # data by route for NetworkManager + os_install_net_nmroute = {'hide':True} + + # dns servers + os_install_net_dns = {} + + # net setup (networkmanager or openrc) + os_install_net_conf = {} + + # net service configured + os_install_net_settings = {'mode':'w', + 'value':''} + + # dhcp or not + os_install_net_dhcp_set = {} + + # dns search + os_install_net_dns_search = {'mode':"w"} + + # domain + os_install_net_domain = {'mode':"w"} + diff --git a/install/variables/system.py b/install/variables/system.py new file mode 100644 index 0000000..d195fe3 --- /dev/null +++ b/install/variables/system.py @@ -0,0 +1,108 @@ +#-*- coding: utf-8 -*- + +# Copyright 2008-2012 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 sys +from os import path +from calculate.lib.cl_datavars import Variables +from calculate.lib.variables import System + +from calculate.lib.cl_lang import setLocalTranslate +setLocalTranslate('cl_install',sys.modules[__name__]) + +class InstallSystem(System): + vars = ["os_install_scratch","cl_autoupdate_set", + "cl_install_autoupdate_set","os_install_arch_machine", + "os_install_proxy","os_install_ntp","os_install_root_type", + "os_install_root_dev","os_install_dev_from","os_install_lvm_set", + "os_install_mdadm_set","os_grub_conf","os_grub2_path", + "cl_chroot_grub","os_install_grub_devicemap_conf", + "cl_distfiles_path","cl_pkgdir_path","os_format_type", + "os_format_use","os_install_makeopts","cl_migrate_user", + "cl_migrate_user_pwd","os_nvidia_mask","cl_autologin"] + # install system in scratch mode + os_install_scratch = {} + + # (on or off) autoupdate config from install program + cl_autoupdate_set = {'value': "off"} + + # (on or off) autoupdate config from install program for install + cl_install_autoupdate_set = {'mode':'w','value': "off"} + + # install maching architecture + os_install_arch_machine = {'mode':'w'} + + # proxy server for system + os_install_proxy = {'mode':'w', + 'value':''} + + # nt server for system + os_install_ntp = {'mode':'w', + 'value':'ntp0.zenon.net'} + + # type of device for install + os_install_root_type = {'mode':'w'} + # root device of installed os + os_install_root_dev = {} + + # root device of previous installed os + os_install_dev_from = {} + + # using lvm + os_install_lvm_set = {} + + # using mdadm + os_install_mdadm_set = {} + + # current grub + os_grub_conf = {} + + # grub2 install path + os_grub2_path = {'mode':'w'} + + # grub chroot need for grub-mkconfig + cl_chroot_grub = {} + + # content of device.map file for grub + os_install_grub_devicemap_conf = {} + + # DISTFILES value + cl_distfiles_path = {'mode':'w', + 'value':'/var/calculate/remote/distfiles'} + # PKGDIR value + cl_pkgdir_path = {'mode':'w'} + + # filesystem format support by calcualte-install + os_format_type = {} + + # avialable format by mkfs utility + os_format_use = {} + + # makeconf makeopts + os_install_makeopts = {'mode':'w'} + + # migrate users + cl_migrate_user = {} + + # migrate users who need to change passwords + cl_migrate_user_pwd = {} + + # nvidia-drivers atom mask + os_nvidia_mask = {} + + # variable for autologin + cl_autologin = {} + diff --git a/scripts/cl-install b/scripts/cl-install deleted file mode 100644 index fb030b5..0000000 --- a/scripts/cl-install +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python2 -#-*- coding: utf-8 -*- - -# Copyright 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 sys -import os -sys.path.insert(0,os.path.abspath('/usr/lib/calculate-2.2/calculate-lib/pym')) -sys.path.insert(0, - os.path.abspath('/usr/lib/calculate-2.2/calculate-install/pym')) - -from cl_lang import lang -tr = lang() -tr.setGlobalDomain('cl_install') -tr.setLanguage(sys.modules[__name__]) -from cl_install_cmd import install_cmd - - -if __name__ == "__main__": - install = install_cmd() - install.logicObj.initVars() - # set lang - ret = install.optobj.parse_args() - if ret is False: - sys.exit(1) - options, args = ret - # set color/nocolor for display messages - install.setPrintNoColor(options) - # init variables - install.setProxyNtpHostname(options.proxy,options.ntp,options.hostname) - if not install.setNetworkParams(options.ip,options.route,options.dns, - options.netconf,options.dhcp): - sys.exit(1) - if options.l: - if not install.setLang(options.l): - sys.exit(1) - # set values to variables - if not install.setVars(options): - sys.exit(1) - # check and set installed options - install.setAction(options.startup,options.live) - if not (options.startup or options.install or options.uninstall or - options.live): - if not install.checkAndSetInstallOptions(options.d,options.w, - options.u,options.A): - 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) - # configurate current system - if options.startup: - if not install.configureSystem(options.A): - sys.exit(1) - elif options.install: - if not install.installPackage(): - sys.exit(1) - elif options.uninstall: - if not install.uninstallPackage(): - sys.exit(1) - else: - forceOpions = options.f or options.P - flagSpinner = not options.nospinner - if not install.installSystem(force=forceOpions, bootDisk=options.mbr, - stdinReadPwd=options.P,builder=options.build, - flagSpinner=flagSpinner,update=options.U): - sys.exit(1) - #if not install.writeVars(options): - # sys.exit(1) - sys.exit(0) diff --git a/scripts/cl-install3 b/scripts/cl-install3 new file mode 100644 index 0000000..2ad8312 --- /dev/null +++ b/scripts/cl-install3 @@ -0,0 +1,372 @@ +#!/usr/bin/python +#-*- coding: utf-8 -*- + +# Copyright 2012 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. + +from suds.client import Client +from suds import WebFault +import traceback as tb +from getpass import getpass +import time, logging +import glob, os +from OpenSSL.crypto import load_certificate, FILETYPE_PEM +import re, threading +from calculate.api.client.function import * +from calculate.api.client.pid_information import * +from calculate.api.client.cert_func import * +from calculate.api.client.sid_func import * +from calculate.lib.cl_datavars import DataVars + +from calculate.api.client.client_class import HTTPSClientAuthHandler, HTTPSClientCertTransport + +VERSION = 0.1 + +class Client_suds(Client): + def set_parameters (self, path_to_cert): + self.CERT_FILE = path_to_cert + 'client.crt' + self.CERT_PEM = path_to_cert + 'client.pem' + self.REQ_FILE = path_to_cert + 'client.csr' + self.PKEY_FILE = path_to_cert + 'client.key' + self.SID_FILE = path_to_cert + 'sid.int' + + +t = time + +help_ = ''' + useradd, cl-unix-useradd - add unix user + + say, say_hello - server function + + halt, server_shutdown - shutdown server + + run, server_start - start server + +---- process methods ---- + + lsp, list-pid - listing all pids for this session + + pi, pid-info - get information about select pid (0 for all) + + kill, pid-kill - kill select pid + +---- sessions methods ---- + + lss, list-session - listing all sessions in server + + si, session-info - get information about select session (sid) + + lsr, list-method - listing all accessible methods + + q, quit - exit + + h, help - display this help and exit + + v, version - output version information and exit''' + +#class NewType: + #def __init__ (self, a, b): + #self.a = int(a) + #self.b = str(b) + +def client_say_hello(client): + #try: + name2 = raw_input ("Enter your name: ") + times = raw_input ("Enter number repeating (1-100): ") + if (not name2.isalpha()): + print "Name input Error!" + return 2 + try: + times = int(times) + except: + print "Number repeating input Error!" + return 2 + if times < 1 or times > 100: + print "Number repeating must be > 0 and < 100" + return 2 + #get cert & sid + #try: + c_s = get_cert_sid(client.CERT_FILE, client.SID_FILE) + #name = client.factory.create('s1:NewType') + #name4 = client.factory.create('s1:UserInfoValue') + + #name.helper = 4 + #name4.table.name = name2 + #name4.table.surname = "fadf" + #name.value = name4 + #a = 3 + name = client.factory.create('s0:stringArray') + name['string'] = [name2,"BBBBBBB"] + s = client.service.say_hello(c_s[0], c_s[1], name, times) + #print s.helper + #print dir (s.value) + #print s.value.data.name + + #except: + #print "Connection error! " + #return 1 + try: + if s[1][0] == "Permission denied": + print s[1][0], s[1][1] + return 3 + except: + return 0 + + +def client_login (client): + login = raw_input ("Login: ") + password = raw_input ("password: ") + try: + name_re = re.compile("[^a-zA-Z_]") + if name_re.findall(login): + print "input error" + return 2 + param = "" + print login, password + print client.service.cl_login(login = login, password = password) + except: + print "create error" + +def client_useradd (client): + user_name = raw_input ("User name: ") + try: + name_re = re.compile("[^a-zA-Z_]") + if name_re.findall(user_name): + print "input error" + return 2 + param = "" + print client.service.cl_unix_useradd(param = user_name) + except: + print "create error" + +def client_userdel (client): + user_name = raw_input ("User name: ") + try: + name_re = re.compile("[^a-zA-Z_]") + if name_re.findall(user_name): + print "input error" + return 2 + param = "" + print client.service.cl_unix_userdel(param = user_name) + except: + print "deleted error" + +def client_shut (client): + import soaplib + try: + temp = client.service.server_shutdown() + if ( temp == 1): + print "Server shutting down..." + except: + print "Connection error! " + return 1 + +def client_signal(client): + while True: + time.sleep(5) + if os.path.exists(client.SID_FILE) : + fi = open(client.SID_FILE, 'r') + temp = fi.read() + fi.close() + sid = int(temp) + else: + sid = 0 + reply = client.service.active_client(sid) + +import argparse + +def parse(): + parser = argparse.ArgumentParser() + parser.add_argument( + '-p', '--port', type=int, default = '8888', dest='port', + help='port number') + parser.add_argument( + '--script', type=str, default = '/Server', dest='script_name', + help='name script in server') + parser.add_argument( + '--host', type=str, default = 'localhost', dest='host', + help='host destination') + parser.add_argument( + '--cert-path', type=str, + default = '~/.calculate/client_cert/', + nargs ='?', dest='path_to_cert', + help='path to cert and key file') + return parser.parse_args() + + +#url = 'http://localhost:8888/TestService/?wsdl' + +def https_server(client, signaling): + global url + client_post_auth(client) + signaling.start() + client_list_methods(client) + sid = get_sid(client.SID_FILE)[1] + print client.service.install_system_view(sid ,0) + installInfo = create_obj(client,"install_system") + for params in [ +# ("cl-install -d /dev/sda3:/:reiserfs:format -d /dev/sda5:/var/calculate:ext4:noformat", +# listToArrayArray(client, +# [["/dev/sda3","/","reiserfs","format"], +# ["/dev/sda5","/var/calculate","ext4","noformat"]])), +# ("cl-install -d /dev/sda3:swap -d /dev/sda5:/var/calculate:ext4:noformat", +# listToArrayArray(client, +# [["/dev/sda3","swap"], +# ["/dev/sda5","/var/calculate","ext4","noformat"]])), +# ("cl-install -d /var/calculate/home:/home -d /dev/sda5:/var/calculate:ext4:noformat", +# listToArrayArray(client, +# [["/var/calculate/home","/home"], +# ["/dev/sda5","/var/calculate","ext4","noformat"]])), +# ("cl-install -d /dev/sda10:/ -d /var/calculate/home:/home -d /dev/sda5:/var/calculate:ext4:noformat", +# listToArrayArray(client, +# [["/dev/sda10","/"], +# ["/var/calculate/home","/home"], +# ["/dev/sda5","/var/calculate","ext4","noformat"]])), +# ("cl-install -d /dev/sda4:/ -d /var/calculate/home:/home -d /dev/sda5:/var/calculate:ext4:noformat", +# listToArrayArray(client, +# [["/dev/sda4","/"], +# ["/var/calculate/home","/home"], +# ["/dev/sda5","/var/calculate","ext4","noformat"]])), +# ("cl-install -d /dev/sr0:/ -d /var/calculate/home:/home -d /dev/sda5:/var/calculate:ext4:noformat", +# listToArrayArray(client, +# [["/dev/sr0","/"], +# ["/var/calculate/home","/home"], +# ["/dev/sda5","/var/calculate","ext4","noformat"]])), +# ("cl-install -d /var/calculate/home:/home -d /home:/test", +# listToArrayArray(client, +# [["/var/calculate/home","/home"], +# ["/home","/test"]])), +# ("cl-install -d var/calculate/home:/home -d /home2:test", +# listToArrayArray(client, +# [["var/calculate/home","/home"], +# ["/home2","test"]])), +# ("cl-install -d /dev/sda2:/ -d /dev/sda2:/var/calculate", +# listToArrayArray(client, +# [["/dev/sda2","/"], +# ["/dev/sda2","/var/calculate"]])), +# ("cl-install -d /dev/sda2:/ -d /dev/sda2:/var/calculate", +# listToArrayArray(client, +# [["/dev/sda2","/"], +# ["/dev/sda3","/"]])), +# ("cl-install -d /dev/sda2:/ -d /dev/sda5:/var/calculate", +# listToArrayArray(client, +# [["/dev/sda2","/"], +# ["/dev/sda5","/var/calculate"]])), +# ("cl-install -d /dev/sda3:/:vfat -d /dev/sda5:/var/calculate", +# listToArrayArray(client, +# [["/dev/sda3","/","vfat"], +# ["/dev/sda5","/var/calculate"]])), +# ("cl-install -d /dev/sda3:/:ntfs -d /dev/sda2:/var/calculate:ext3", +# listToArrayArray(client, +# [["/dev/sda3","/","ntfs"], +# ["/dev/sda2","/var/calculate","ext3"]])), +# ("cl-install -d /dev/sda3:/:flaksjdf -d /dev/sda5:/var/calculate", +# listToArrayArray(client, +# [["/dev/sda3","/","flaksjdf"], +# ["/dev/sda5","/var/calculate"]])), + ("cl-install -d /dev/sda3:/ -d /dev/sda5:/var/calculate", + listToArrayArray(client, + [["/dev/sda3","/"], + ["/dev/sda5","/var/calculate"]]), + listToArray(client,["falksdjflkasd"])), + ("cl-install -d /dev/sda3:/:flaksjdf -d /dev/sda5:/var/calculate", + listToArrayArray(client, + [["/dev/sda3","/","flaksjdf"], + ["/dev/sda5","/var/calculate"]]), + listToArray(client,["/dev/sda"])), + ]: + print params[0] + installInfo.disk = params[1] + if len(params) > 2: + installInfo.mbr = params[2] + errs = client.service.install_system(sid,installInfo,True) + if errs: + for err in errs[0]: + print "Wrong value for '%s':%s"%(err.name,err.message) + +def main(): + clear() + #password = getpass(prompt="Password: ") + logging.basicConfig(level=logging.FATAL) + logging.getLogger('suds.client').setLevel(logging.FATAL) + logging.getLogger('suds.transport').setLevel(logging.FATAL) + logging.getLogger('suds.transport.http').setLevel(logging.FATAL) + + #fmt = '%(asctime)s [%(levelname)s] %(funcName)s() @%(filename)s:%(lineno)d\n%(message)s\n' + #logging.basicConfig(level=logging.INFO, format=fmt) + + logging.getLogger('suds.umx.typed').setLevel(logging.ERROR) + clVars = DataVars() + clVars.flIniFile() + homePath = clVars.Get('ur_home_path') + + args = parse() + + port = args.port + host = args.host + path_to_cert = args.path_to_cert + path_to_cert = path_to_cert.replace("~",homePath) + + script_name = args.script_name + + print "wsdl is at: https://%s:%d%s/?wsdl" %(host, port, script_name) + url = "https://%s:%d%s/?wsdl" %(host, port, script_name) + + try: +# client_start() + + CERT_FILE = path_to_cert + 'client.crt' + CERT_PEM = path_to_cert + 'client.pem' + CERT_KEY = path_to_cert + 'client.key' + + #If the certificate file is created + if os.path.exists(CERT_KEY) and \ + os.path.exists(CERT_FILE): + client = Client_suds(url,\ + transport = HTTPSClientCertTransport(CERT_KEY, CERT_FILE,\ + path_to_cert)) + #If the certificate file misses + else: + CERT_FILE = None + CERT_KEY = None + CERT_PEM = None + client = Client_suds(url,\ + transport = HTTPSClientCertTransport(CERT_KEY, CERT_FILE,\ + path_to_cert)) + + #print CERT_PEM + #print "#######################################" + + #print dir (client) + + #print "#######################################" + + #threads = [] + + client.set_parameters (path_to_cert.replace("~",homePath)) + signaling = threading.Thread(target=client_signal, args = (client, )) + #threads.append(signaling) + signaling.setDaemon(True) + https_server(client, signaling) +#---------------------------------------------------- + except WebFault, f: + print f + print f.fault + except Exception, e: + #signaling.killed = True + print e + tb.print_exc() + +if __name__=='__main__': + main() diff --git a/setup.py b/setup.py index 2c7d5ae..f3ea140 100755 --- a/setup.py +++ b/setup.py @@ -174,9 +174,9 @@ setup( url = "http://calculate-linux.org", license = "http://www.apache.org/licenses/LICENSE-2.0", package_dir = {'calculate.install': "install"}, - packages = ['calculate.install'], + packages = ['calculate.install','calculate.install.variables'], data_files = data_files, - scripts=[], + scripts=['scripts/cl-install3'], cmdclass={'install_data': cl_install_data, 'build':build,'build_man':build_man, 'install':install,'install_man':install_man},