示例#1
0
    def create(self, params):
        name = params.get('name', '').strip()
      #  import pdb
      #  pdb.set_trace()
        conn = self.conn.get()
        for net_name in params.get(u'networks', []):
            try:
                conn.networkLookupByName(net_name.encode('utf-8'))
            except Exception:
                raise InvalidParameter("KCHTMPL0003E", {'network': net_name,
                                                        'template': name})

        # get source_media
        source_media = params.pop("source_media")

        if source_media['type'] == 'netboot':
            params['netboot'] = True
            return self.save_template(params)

        # Get path of source media if it's based on disk type.
        path = source_media.get('path', None)
        if path is None:
            raise InvalidParameter("KCHTMPL0016E")

        # not local image: set as remote ISO
        path = path.encode('utf-8')
        if urlparse.urlparse(path).scheme in ["http", "https", "tftp", "ftp",
                                              "ftps"]:
            params["cdrom"] = path
            return self.save_template(params)

        # Local file (ISO/Img) does not exist: raise error
        if not os.path.exists(path):
            raise InvalidParameter("KCHTMPL0002E", {'path': path})

        # create magic object to discover file type
        file_type = magic.open(magic.MAGIC_NONE)
        file_type.load()
        ftype = file_type.file(path)

        # cdrom
        if ISO_TYPE in ftype:
            params["cdrom"] = path

            # check search permission
            st_mode = os.stat(path).st_mode
            if stat.S_ISREG(st_mode) or stat.S_ISBLK(st_mode):
                user = UserTests().probe_user()
                run_setfacl_set_attr(path, user=user)
                ret, excp = probe_file_permission_as_user(path, user)
                if ret is False:
                    raise InvalidParameter('KCHISO0008E',
                                           {'filename': path, 'user': user,
                                            'err': excp})
        # disk
        else:
            params["disks"] = params.get('disks', [])
            params["disks"].append({"base": path})

        return self.save_template(params)
示例#2
0
    def create(self, params):
        name = params.get('name', '').strip()
        iso = params.get('cdrom')
        # check search permission
        if iso and iso.startswith('/') and os.path.exists(iso):
            st_mode = os.stat(iso).st_mode
            if stat.S_ISREG(st_mode) or stat.S_ISBLK(st_mode):
                user = UserTests().probe_user()
                run_setfacl_set_attr(iso, user=user)
                ret, excp = probe_file_permission_as_user(iso, user)
                if ret is False:
                    raise InvalidParameter('KCHISO0008E',
                                           {'filename': iso, 'user': user,
                                            'err': excp})

        conn = self.conn.get()
        for net_name in params.get(u'networks', []):
            try:
                conn.networkLookupByName(net_name.encode('utf-8'))
            except Exception:
                raise InvalidParameter("KCHTMPL0003E", {'network': net_name,
                                                        'template': name})
        # Creates the template class with necessary information
        # Checkings will be done while creating this class, so any exception
        # will be raised here
        t = LibvirtVMTemplate(params, scan=True, conn=self.conn)

        # Validate cpu info
        t.cpuinfo_validate()

        # Validate max memory
        maxMem = (t._get_max_memory(t.info.get('memory')) >> 10)
        if t.info.get('memory') > maxMem:
            raise OperationFailed("KCHVM0041E", {'maxmem': str(maxMem)})

        # Validate volumes
        for disk in t.info.get('disks'):
            volume = disk.get('volume')
            # volume can be None
            if 'volume' in disk.keys():
                self.template_volume_validate(volume, disk['pool'])

        # Store template on objectstore
        name = params['name']
        try:
            with self.objstore as session:
                if name in session.get_list('template'):
                    raise InvalidOperation("KCHTMPL0001E", {'name': name})
                session.store('template', name, t.info,
                              get_kimchi_version())
        except InvalidOperation:
            raise
        except Exception, e:
            raise OperationFailed('KCHTMPL0020E', {'err': e.message})
示例#3
0
    def create(self, params):
        name = params.get('name', '').strip()

        conn = self.conn.get()
        for net_name in params.get(u'networks', []):
            try:
                conn.networkLookupByName(net_name.encode('utf-8'))
            except Exception:
                raise InvalidParameter("KCHTMPL0003E", {'network': net_name,
                                                        'template': name})

        # get source_media
        path = params.pop("source_media")

        # not local image: set as remote ISO
        if urlparse.urlparse(path).scheme in ["http", "https", "tftp", "ftp",
                                              "ftps"]:
            params["cdrom"] = path

        # image does not exists: raise error
        elif not os.path.exists(path):
            raise InvalidParameter("Unable to find file %(path)s" %
                                   {"path": path})

        # create magic object to discover file type
        file_type = magic.open(magic.MAGIC_NONE)
        file_type.load()
        ftype = file_type.file(path)

        # cdrom
        if ISO_TYPE in ftype:
            params["cdrom"] = path

            # check search permission
            st_mode = os.stat(path).st_mode
            if stat.S_ISREG(st_mode) or stat.S_ISBLK(st_mode):
                user = UserTests().probe_user()
                run_setfacl_set_attr(path, user=user)
                ret, excp = probe_file_permission_as_user(path, user)
                if ret is False:
                    raise InvalidParameter('KCHISO0008E',
                                           {'filename': path, 'user': user,
                                            'err': excp})
        # disk
        else:
            params["disks"] = params.get('disks', [])
            params["disks"].append({"base": path})

        return self.save_template(params)
示例#4
0
    def create(self, params):
        name = params.get('name', '').strip()
        iso = params.get('cdrom')
        # check search permission
        if iso and iso.startswith('/') and os.path.exists(iso):
            st_mode = os.stat(iso).st_mode
            if stat.S_ISREG(st_mode) or stat.S_ISBLK(st_mode):
                user = UserTests().probe_user()
                run_setfacl_set_attr(iso, user=user)
                ret, excp = probe_file_permission_as_user(iso, user)
                if ret is False:
                    raise InvalidParameter('KCHISO0008E', {
                        'filename': iso,
                        'user': user,
                        'err': excp
                    })

        cpu_info = params.get('cpu_info')
        if cpu_info:
            topology = cpu_info.get('topology')
            # Check, even though currently only topology
            #   is supported.
            if topology:
                sockets = topology['sockets']
                cores = topology['cores']
                threads = topology['threads']
                if params.get('cpus') is None:
                    params['cpus'] = sockets * cores * threads
                # check_topoology will raise the appropriate
                # exception if a topology is invalid.
                CPUInfoModel(conn=self.conn).\
                    check_topology(params['cpus'], topology)

        conn = self.conn.get()
        pool_uri = params.get(u'storagepool', '')
        if pool_uri:
            try:
                pool_name = pool_name_from_uri(pool_uri)
                pool = conn.storagePoolLookupByName(pool_name.encode("utf-8"))
            except Exception:
                raise InvalidParameter("KCHTMPL0004E", {
                    'pool': pool_uri,
                    'template': name
                })

            tmp_volumes = [
                disk['volume'] for disk in params.get('disks', [])
                if 'volume' in disk
            ]
            self.template_volume_validate(tmp_volumes, pool)

        for net_name in params.get(u'networks', []):
            try:
                conn.networkLookupByName(net_name.encode('utf-8'))
            except Exception:
                raise InvalidParameter("KCHTMPL0003E", {
                    'network': net_name,
                    'template': name
                })
        # Creates the template class with necessary information
        # Checkings will be done while creating this class, so any exception
        # will be raised here
        t = LibvirtVMTemplate(params, scan=True, conn=self.conn)
        name = params['name']
        try:
            with self.objstore as session:
                if name in session.get_list('template'):
                    raise InvalidOperation("KCHTMPL0001E", {'name': name})
                session.store('template', name, t.info)
        except InvalidOperation:
            raise
        except Exception, e:
            raise OperationFailed('KCHTMPL0020E', {'err': e.message})
示例#5
0
    def lookup(self, pool, name):
        vol = StorageVolumeModel.get_storagevolume(pool, name, self.conn)
        path = vol.path()
        info = vol.info()
        xml = vol.XMLDesc(0)
        try:
            fmt = xpath_get_text(xml, "/volume/target/format/@type")[0]
        except IndexError:
            # Not all types of libvirt storage can provide volume format
            # infomation. When there is no format information, we assume
            # it's 'raw'.
            fmt = 'raw'

        iso_img = None

        # 'raw' volumes from 'logical' pools may actually be 'iso';
        # libvirt always reports them as 'raw'
        pool_info = self.storagepool.lookup(pool)
        if pool_info['type'] == 'logical' and fmt == 'raw':
            try:
                iso_img = IsoImage(path)
            except IsoFormatError:
                # not 'iso' afterall
                pass
            else:
                fmt = 'iso'

        # 'raw' volumes can not be valid image disks (e.g. XML, PDF, TXT are
        # raw files), so it's necessary check the 'content' of them
        isvalid = True
        if fmt == 'raw':
            try:
                ms = magic.open(magic.NONE)
                ms.load()
                if ms.file(path).lower() not in VALID_RAW_CONTENT:
                    isvalid = False
                ms.close()
            except UnicodeDecodeError:
                isvalid = False

        used_by = get_disk_used_by(self.conn, path)
        if (self.libvirt_user is None):
            self.libvirt_user = UserTests().probe_user()
        ret, _ = probe_file_permission_as_user(os.path.realpath(path),
                                               self.libvirt_user)
        res = dict(type=VOLUME_TYPE_MAP[info[0]],
                   capacity=info[1],
                   allocation=info[2],
                   path=path,
                   used_by=used_by,
                   format=fmt,
                   isvalid=isvalid,
                   has_permission=ret)
        if fmt == 'iso':
            if os.path.islink(path):
                path = os.path.join(os.path.dirname(path), os.readlink(path))
            os_distro = os_version = 'unknown'
            try:
                if iso_img is None:
                    iso_img = IsoImage(path)
                os_distro, os_version = iso_img.probe()
                bootable = True
            except IsoFormatError:
                bootable = False

            res.update(
                dict(os_distro=os_distro, os_version=os_version, path=path,
                     bootable=bootable))
        return res
示例#6
0
    def lookup(self, pool, name):
        vol = StorageVolumeModel.get_storagevolume(pool, name, self.conn)
        path = vol.path()
        info = vol.info()
        xml = vol.XMLDesc(0)
        try:
            fmt = xpath_get_text(xml, "/volume/target/format/@type")[0]
        except IndexError:
            # Not all types of libvirt storage can provide volume format
            # infomation. When there is no format information, we assume
            # it's 'raw'.
            fmt = 'raw'

        iso_img = None

        # 'raw' volumes from 'logical' pools may actually be 'iso';
        # libvirt always reports them as 'raw'
        pool_info = self.storagepool.lookup(pool)
        if pool_info['type'] == 'logical' and fmt == 'raw':
            try:
                iso_img = IsoImage(path)
            except IsoFormatError:
                # not 'iso' afterall
                pass
            else:
                fmt = 'iso'

        # 'raw' volumes can not be valid image disks (e.g. XML, PDF, TXT are
        # raw files), so it's necessary check the 'content' of them
        isvalid = True
        if fmt == 'raw':
            try:
                ms = magic.open(magic.NONE)
                ms.load()
                if ms.file(path).lower() not in VALID_RAW_CONTENT:
                    isvalid = False
                ms.close()
            except UnicodeDecodeError:
                isvalid = False

        used_by = get_disk_used_by(self.conn, path)
        if (self.libvirt_user is None):
            self.libvirt_user = UserTests().probe_user()
        ret, _ = probe_file_permission_as_user(os.path.realpath(path),
                                               self.libvirt_user)
        res = dict(type=VOLUME_TYPE_MAP[info[0]],
                   capacity=info[1],
                   allocation=info[2],
                   path=path,
                   used_by=used_by,
                   format=fmt,
                   isvalid=isvalid,
                   has_permission=ret)
        if fmt == 'iso':
            if os.path.islink(path):
                path = os.path.join(os.path.dirname(path), os.readlink(path))
            os_distro = os_version = 'unknown'
            try:
                if iso_img is None:
                    iso_img = IsoImage(path)
                os_distro, os_version = iso_img.probe()
                bootable = True
            except IsoFormatError:
                bootable = False

            res.update(
                dict(os_distro=os_distro,
                     os_version=os_version,
                     path=path,
                     bootable=bootable))
        return res
示例#7
0
    def create(self, params):
        name = params.get('name', '').strip()

        conn = self.conn.get()
        for net_name in params.get(u'networks', []):
            try:
                conn.networkLookupByName(net_name.encode('utf-8'))
            except Exception:
                raise InvalidParameter("KCHTMPL0003E", {'network': net_name,
                                                        'template': name})
        # Valid interfaces
        interfaces = params.get('interfaces', [])
        validate_interfaces(interfaces)

        if os.uname()[4] not in ['s390x', 's390'] and 'console' in params:
            raise InvalidParameter("KCHTMPL0043E")

        # get source_media
        source_media = params.pop("source_media")

        if source_media['type'] == 'netboot':
            params['netboot'] = True
            return self.save_template(params)

        # Get path of source media if it's based on disk type.
        path = source_media.get('path', None)
        if path is None:
            raise InvalidParameter("KCHTMPL0016E")

        # not local image: set as remote ISO
        path = path.encode('utf-8')
        if urlparse.urlparse(path).scheme in ["http", "https", "tftp", "ftp",
                                              "ftps"]:
            params["cdrom"] = path
            return self.save_template(params)

        # Local file (ISO/Img) does not exist: raise error
        if not os.path.exists(path):
            raise InvalidParameter("KCHTMPL0002E", {'path': path})

        # create magic object to discover file type
        file_type = magic.open(magic.MAGIC_NONE)
        file_type.load()
        ftype = file_type.file(path)

        # cdrom
        if ISO_TYPE in ftype:
            params["cdrom"] = path

            # check search permission
            st_mode = os.stat(path).st_mode
            if stat.S_ISREG(st_mode) or stat.S_ISBLK(st_mode):
                user = UserTests().probe_user()
                realpath = os.path.realpath(path)
                run_setfacl_set_attr(realpath, user=user)
                ret, excp = probe_file_permission_as_user(realpath, user)
                if ret is False:
                    raise InvalidParameter('KCHISO0008E',
                                           {'filename': path, 'user': user,
                                            'err': excp})
        # disk
        else:
            params["disks"] = params.get('disks', [])
            params["disks"].append({"base": path})

        return self.save_template(params)
示例#8
0
    def create(self, params):
        name = params.get('name', '').strip()
        iso = params.get('cdrom')
        # check search permission
        if iso and iso.startswith('/') and os.path.exists(iso):
            st_mode = os.stat(iso).st_mode
            if stat.S_ISREG(st_mode) or stat.S_ISBLK(st_mode):
                user = UserTests().probe_user()
                run_setfacl_set_attr(iso, user=user)
                ret, excp = probe_file_permission_as_user(iso, user)
                if ret is False:
                    raise InvalidParameter('KCHISO0008E',
                                           {'filename': iso, 'user': user,
                                            'err': excp})

        cpu_info = params.get('cpu_info')
        if cpu_info:
            topology = cpu_info.get('topology')
            # Check, even though currently only topology
            #   is supported.
            if topology:
                sockets = topology['sockets']
                cores = topology['cores']
                threads = topology['threads']
                if params.get('cpus') is None:
                    params['cpus'] = sockets * cores * threads
                # check_topoology will raise the appropriate
                # exception if a topology is invalid.
                CPUInfoModel(conn=self.conn).\
                    check_topology(params['cpus'], topology)

        conn = self.conn.get()
        for net_name in params.get(u'networks', []):
            try:
                conn.networkLookupByName(net_name.encode('utf-8'))
            except Exception:
                raise InvalidParameter("KCHTMPL0003E", {'network': net_name,
                                                        'template': name})
        # Creates the template class with necessary information
        # Checkings will be done while creating this class, so any exception
        # will be raised here
        t = LibvirtVMTemplate(params, scan=True, conn=self.conn)

        # Validate volumes
        for disk in t.info.get('disks'):
            volume = disk.get('volume')
            # volume can be None
            if 'volume' in disk.keys():
                self.template_volume_validate(volume, disk['pool'])

        # Store template on objectstore
        name = params['name']
        try:
            with self.objstore as session:
                if name in session.get_list('template'):
                    raise InvalidOperation("KCHTMPL0001E", {'name': name})
                session.store('template', name, t.info,
                              get_kimchi_version())
        except InvalidOperation:
            raise
        except Exception, e:
            raise OperationFailed('KCHTMPL0020E', {'err': e.message})
示例#9
0
    def create(self, params):
        name = params.get('name', '').strip()

        conn = self.conn.get()
        for net_name in params.get(u'networks', []):
            try:
                conn.networkLookupByName(net_name)
            except Exception:
                raise InvalidParameter(
                    'KCHTMPL0003E', {'network': net_name, 'template': name}
                )
        # Valid interfaces
        interfaces = params.get('interfaces', [])
        validate_interfaces(interfaces)

        if os.uname()[4] not in ['s390x', 's390'] and 'console' in params:
            raise InvalidParameter('KCHTMPL0043E')

        # get source_media
        source_media = params.pop('source_media')

        if source_media['type'] == 'netboot':
            params['netboot'] = True
            return self.save_template(params)

        # Get path of source media if it's based on disk type.
        path = source_media.get('path', None)
        if path is None:
            raise InvalidParameter('KCHTMPL0016E')

        # not local image: set as remote ISO
        if urllib.parse.urlparse(path).scheme in [
            'http',
            'https',
            'tftp',
            'ftp',
            'ftps',
        ]:
            params['cdrom'] = path
            return self.save_template(params)

        # Local file (ISO/Img) does not exist: raise error
        if not os.path.exists(path):
            raise InvalidParameter('KCHTMPL0002E', {'path': path})

        # create magic object to discover file type
        file_type = magic.open(magic.MAGIC_NONE)
        file_type.load()
        ftype = file_type.file(path)

        # cdrom
        iscdrom = [t for t in ISO_TYPE if t in ftype]
        if iscdrom:
            params['cdrom'] = path

            # check search permission
            st_mode = os.stat(path).st_mode
            if stat.S_ISREG(st_mode) or stat.S_ISBLK(st_mode):
                user = UserTests().probe_user()
                realpath = os.path.realpath(path)
                run_setfacl_set_attr(realpath, user=user)
                ret, excp = probe_file_permission_as_user(realpath, user)
                if ret is False:
                    raise InvalidParameter(
                        'KCHISO0008E', {'filename': path,
                                        'user': user, 'err': excp}
                    )
        # disk
        else:
            params['disks'] = params.get('disks', [])
            params['disks'].append({'base': path})

        return self.save_template(params)