Esempio n. 1
0
    def delete(self, vmid, dev_name):
        dom = VMModel.get_vm(vmid, self.conn)
        xmlstr = dom.XMLDesc(0)
        root = objectify.fromstring(xmlstr)

        try:
            hostdev = root.devices.hostdev
        except AttributeError:
            raise NotFoundError('KCHVMHDEV0001E', {
                'vmid': vmid,
                'dev_name': dev_name
            })

        pci_devs = [(DeviceModel.deduce_dev_name(e, self.conn), e)
                    for e in hostdev if e.attrib['type'] == 'pci']

        for e in hostdev:
            if DeviceModel.deduce_dev_name(e, self.conn) == dev_name:
                xmlstr = etree.tostring(e)
                dom.detachDeviceFlags(xmlstr,
                                      get_vm_config_flag(dom, mode='all'))
                if e.attrib['type'] == 'pci':
                    self._delete_affected_pci_devices(dom, dev_name, pci_devs)
                break
        else:
            raise NotFoundError('KCHVMHDEV0001E', {
                'vmid': vmid,
                'dev_name': dev_name
            })
Esempio n. 2
0
    def lookup(self, vmid, dev_name):
        dom = VMModel.get_vm(vmid, self.conn)
        xmlstr = dom.XMLDesc(0)
        root = objectify.fromstring(xmlstr)
        try:
            hostdev = root.devices.hostdev
        except AttributeError:
            raise NotFoundError('KCHVMHDEV0001E', {
                                'vmid': vmid, 'dev_name': dev_name})

        for e in hostdev:
            deduced_name = DeviceModel.deduce_dev_name(e, self.conn)
            if deduced_name == dev_name:
                dev_info = self.dev_model.lookup(dev_name)
                return {
                    'name': dev_name,
                    'type': e.attrib['type'],
                    'product': dev_info.get('product', None),
                    'vendor': dev_info.get('vendor', None),
                    'multifunction': dev_info.get('multifunction', None),
                    'vga3d': dev_info.get('vga3d', None),
                }

        raise NotFoundError('KCHVMHDEV0001E', {
                            'vmid': vmid, 'dev_name': dev_name})
Esempio n. 3
0
 def lookup(self, user):
     if isinstance(user, str):
         user = user.encode('utf-8')
     if not isinstance(user, str) or not user.strip():
         raise InvalidParameter('GINUSER0002E')
     try:
         user_info = get_users_info([user])
     except Exception:
         raise NotFoundError('GINUSER0011E', {'user': user})
     if not user_info:
         raise NotFoundError('GINUSER0011E', {'user': user})
     return user_info[0]
Esempio n. 4
0
 def get_sockets(self):
     """
         param self: object of the class self
         return: Socket(s) (information about the CPU architecture)
     """
     try:
         sockets = "Socket(s)"
         if len(self.lsCpuInfo) > 0 and sockets in self.lsCpuInfo.keys():
             return int(self.lsCpuInfo[sockets])
         else:
             raise NotFoundError("GGBCPUINF0005E")
     except IndexError, e:
         self.log_error(e)
         raise NotFoundError("GGBCPUINF0005E")
Esempio n. 5
0
 def get_threads_per_core(self):
     """
         param self: object of the class self
         return: Thread(s) per core (information about the CPU architecture)
     """
     try:
         threads_per_core = "Thread(s) per core"
         if len(self.lsCpuInfo) > 0 and threads_per_core \
                 in self.lsCpuInfo.keys():
             return int(self.lsCpuInfo[threads_per_core])
         else:
             raise NotFoundError("GGBCPUINF0007E")
     except IndexError, e:
         self.log_error(e)
         raise NotFoundError("GGBCPUINF0007E")
Esempio n. 6
0
 def get_cores_per_socket(self):
     """
         param self: object of the class self
         return: Core(s) per socket (information about the CPU architecture)
     """
     try:
         cores_per_socket = "Core(s) per socket"
         if len(self.lsCpuInfo) > 0 and cores_per_socket \
                 in self.lsCpuInfo.keys():
             return int(self.lsCpuInfo[cores_per_socket])
         else:
             raise NotFoundError("GGBCPUINF0006E")
     except IndexError, e:
         self.log_error(e)
         raise NotFoundError("GGBCPUINF0006E")
Esempio n. 7
0
 def lookup(self, nodedev_name):
     conn = self.conn.get()
     try:
         dev = conn.nodeDeviceLookupByName(nodedev_name)
     except:
         raise NotFoundError('KCHHOST0003E', {'name': nodedev_name})
     return hostdev.get_dev_info(dev)
Esempio n. 8
0
 def lookup(self, path):
     try:
         path_components = utils.validate_lun_path(path)
         return utils.get_lun_info(*path_components)
     except ValueError:
         wok_log.error("Fetching LUN info failed, %s", path)
         raise NotFoundError("GS390XSTG00008", {'path': path})
Esempio n. 9
0
    def toggleRepo(self, repo_id, enable):
        """
        Enable a given repository
        """
        r = self._get_source_entry(repo_id)
        if r is None:
            raise NotFoundError('GGBREPOS0012E', {'repo_id': repo_id})

        if enable and not r.disabled:
            raise InvalidOperation('GGBREPOS0015E', {'repo_id': repo_id})

        if not enable and r.disabled:
            raise InvalidOperation('GGBREPOS0016E', {'repo_id': repo_id})

        if enable:
            line = 'deb'
        else:
            line = '#deb'

        gingerBaseLock.acquire()
        try:
            repos = self._get_repos()
            repos.remove(r)
            repos.add(line, r.uri, r.dist, r.comps, file=self.filename)
            repos.save()
        except Exception:
            if enable:
                raise OperationFailed('GGBREPOS0020E', {'repo_id': repo_id})

            raise OperationFailed('GGBREPOS0021E', {'repo_id': repo_id})
        finally:
            gingerBaseLock.release()

        return repo_id
Esempio n. 10
0
    def toggleRepo(self, repo_id, enable):
        repos = self._get_repos('GGBREPOS0011E')
        if repo_id not in repos.keys():
            raise NotFoundError('GGBREPOS0012E', {'repo_id': repo_id})

        entry = repos.get(repo_id)
        if enable and entry.enabled:
            raise InvalidOperation('GGBREPOS0015E', {'repo_id': repo_id})

        if not enable and not entry.enabled:
            raise InvalidOperation('GGBREPOS0016E', {'repo_id': repo_id})

        gingerBaseLock.acquire()
        try:
            if enable:
                entry.enable()
            else:
                entry.disable()

            write_repo_to_file(entry)
        except Exception:
            if enable:
                raise OperationFailed('GGBREPOS0020E', {'repo_id': repo_id})

            raise OperationFailed('GGBREPOS0021E', {'repo_id': repo_id})
        finally:
            gingerBaseLock.release()

        return repo_id
Esempio n. 11
0
    def getRepo(self, repo_id):
        """
        Return a dictionary in the repositories.Repositories() of the given
        repository ID format with the information of a YumRepository object.
        """
        repos = self._get_repos('GGBREPOS0025E')

        if repo_id not in repos.keys():
            raise NotFoundError('GGBREPOS0012E', {'repo_id': repo_id})

        entry = repos.get(repo_id)

        display_name = get_display_name(entry.name)

        info = {}
        info['enabled'] = entry.enabled
        info['baseurl'] = entry.baseurl or ''
        info['config'] = {}
        info['config']['display_repo_name'] = display_name
        info['config']['repo_name'] = entry.name or ''
        info['config']['gpgcheck'] = entry.gpgcheck
        info['config']['gpgkey'] = entry.gpgkey or ''
        info['config']['mirrorlist'] = entry.mirrorlist or ''
        info['config']['metalink'] = entry.metalink or ''
        return info
Esempio n. 12
0
    def getPackageInfo(self, pkg_name):
        """
        Get package information. The return is a dictionary containg the
        information about a package, in the format:

        package = {'package_name': <string>,
                   'version': <string>,
                   'arch': <string>,
                   'repository': <string>
                  }
        """
        self.wait_pkg_manager_available()

        package = {}
        try:
            self._apt_cache.open()
            self._apt_cache.upgrade()
            pkgs = self._apt_cache.get_changes()
            self._apt_cache.close()
        except Exception as e:
            raise OperationFailed('GGBPKGUPD0006E', {'err': e.message})

        pkg = next((x for x in pkgs if x.shortname == pkg_name), None)
        if not pkg:
            message = 'No package found'
            raise NotFoundError('GGBPKGUPD0006E', {'err': message})

        package = {
            'package_name': pkg.shortname,
            'version': pkg.candidate.version,
            'arch': pkg._pkg.architecture,
            'repository': pkg.candidate.origins[0].label
        }
        return package
Esempio n. 13
0
    def lookup(self, vm, mac):
        info = {}

        iface = self._get_vmiface(vm, mac)
        if iface is None:
            raise NotFoundError("KCHVMIF0001E", {'name': vm, 'iface': mac})

        info['type'] = iface.attrib['type']
        info['mac'] = iface.mac.get('address')

        if iface.find('virtualport') is not None:
            info['virtualport'] = iface.virtualport.get('type')

        if info['type'] == 'direct':
            info['source'] = iface.source.get('dev')
            info['mode'] = iface.source.get('mode')
            info['type'] = 'macvtap'
        elif (info['type'] == 'bridge' and
              info.get('virtualport') == 'openvswitch'):
            info['source'] = iface.source.get('bridge')
            info['type'] = 'ovs'
        else:
            info['network'] = iface.source.get('network')

        if iface.find("model") is not None:
            info['model'] = iface.model.get('type')
        if info['type'] == 'bridge' and \
           info.get('virtualport') != 'openvswitch':
            info['bridge'] = iface.source.get('bridge')
        if info.get('network'):
            info['ips'] = self._get_ips(vm, info['mac'], info['network'])
        info.pop('virtualport', None)
        return info
Esempio n. 14
0
def _create_dasd_part(dev, size):
    """
    This method creates a DASD partition
    :param dev: name of DASD device for creation of partition
    :param size: block size
    :return:
    """
    devname = '/dev/' + dev
    device = PDevice(devname)
    disk = PDisk(device)
    num_parts = len(disk.partitions)
    if num_parts == 3:
        raise OperationFailed("GINDASDPAR0016E")

    def kill_proc(proc, timeout_flag):
        try:
            parent = psutil.Process(proc.pid)
            for child in parent.get_children(recursive=True):
                child.kill()
            # kill the process after no children is left
            proc.kill()
        except OSError:
            pass
        else:
            timeout_flag[0] = True

    dasd_devs = _get_dasd_names()
    if dev not in dasd_devs:
        raise NotFoundError("GINDASDPAR0012E", {'name': dev})
    p_str = _form_part_str(size)
    try:
        p1_out = subprocess.Popen(["echo", "-e", "\'", p_str, "\'"],
                                  stdout=subprocess.PIPE)
        p2_out = subprocess.Popen(["fdasd", devname],
                                  stdin=p1_out.stdout,
                                  stderr=subprocess.PIPE,
                                  stdout=subprocess.PIPE)
        p1_out.stdout.close()
        timeout = 2.0
        timeout_flag = [False]
        timer = Timer(timeout, kill_proc, [p2_out, timeout_flag])
        timer.setDaemon(True)
        timer.start()
        out, err = p2_out.communicate()
        if timeout_flag[0]:
            msg_args = {'cmd': "fdasd " + devname, 'seconds': str(timeout)}
            raise TimeoutExpired("WOKUTILS0002E", msg_args)
        if p2_out.returncode != 0:
            if 'error while rereading partition table' in err.lower():
                run_command(["partprobe", devname, "-s"])
            else:
                raise OperationFailed("GINDASDPAR0007E", {
                    'name': devname,
                    'err': err
                })
    except TimeoutExpired:
        raise
    finally:
        if timer and not timeout_flag[0]:
            timer.cancel()
Esempio n. 15
0
    def getPackageDeps(self, pkg_name):
        self.wait_pkg_manager_available()

        cmd = ["zypper", "--non-interactive", "update", "--dry-run", pkg_name]
        (stdout, stderr, returncode) = run_command(cmd)

        if len(stderr) > 0:
            raise OperationFailed('GGBPKGUPD0006E', {'err': stderr})

        # Zypper returns returncode == 0 and stderr <= 0, even if package is
        # not found in it's base. Need check the output of the command to parse
        # correctly.
        message = '\'%s\' not found' % pkg_name
        if message in stdout:
            raise NotFoundError('GGBPKGUPD0006E', {'err': message})

        # get the list of dependencies
        out = stdout.split('\n')
        for line in out:
            if line.startswith("The following"):
                deps_index = out.index(line) + 1
                break

        deps = out[deps_index].split()
        deps.remove(pkg_name)
        return deps
Esempio n. 16
0
 def get_sockets(self):
     """
         param self: object of the class self
         return: Socket(s) (information about the CPU architecture)
     """
     try:
         sockets = 'Socket(s)'
         if ARCH.startswith('s390x'):
             sockets = 'Socket(s) per book'
         if len(self.lsCpuInfo) > 0 and sockets in self.lsCpuInfo.keys():
             return int(self.lsCpuInfo[sockets])
         else:
             raise NotFoundError('GGBCPUINF0005E')
     except IndexError as e:
         self.log_error(e)
         raise NotFoundError('GGBCPUINF0005E')
Esempio n. 17
0
    def lookup(self, subscription):
        """
        Returns a dictionary with all SEP information.
        """
        cmd = ['/opt/ibm/seprovider/bin/getSubscriber']
        output, error, rc = run_command(cmd)

        # error: report
        if rc != 0:
            wok_log.error('SEP execution error: %s - %s - %s' %
                          (cmd, rc, error))
            raise OperationFailed('GINSEP0005E', {'error': error})

        if len(output) > 1:

            # iterate over lines and parse to dict
            for line in output.splitlines():
                if len(line) > 0:
                    entry = SUBSCRIBER.search(line).groupdict()

                    # subscriber found
                    if entry["hostname"] == subscription:
                        return entry

        raise NotFoundError("GINSEP0006E", {'hostname': subscription})
Esempio n. 18
0
 def lookup(self, name):
     discovered_qns = utils.get_discovered_iscsi_qns()
     iqn_exists = any(qn["iqn"] == name for qn in discovered_qns)
     if iqn_exists:
         return utils.get_iqn_info(name)
     else:
         raise NotFoundError("GINISCSI020E")
Esempio n. 19
0
    def update(self, vm, mac, params):
        dom = VMModel.get_vm(vm, self.conn)
        iface = self._get_vmiface(vm, mac)

        if iface is None:
            raise NotFoundError("KCHVMIF0001E", {'name': vm, 'iface': mac})

        # cannot change mac address in a running system
        if DOM_STATE_MAP[dom.info()[0]] != "shutoff":
            raise InvalidOperation('KCHVMIF0011E')

        # mac address is a required parameter
        if 'mac' not in params:
            raise MissingParameter('KCHVMIF0008E')

        # new mac address must be unique
        if self._get_vmiface(vm, params['mac']) is not None:
            raise InvalidParameter('KCHVMIF0009E',
                                   {'name': vm, 'mac': params['mac']})

        flags = 0
        if dom.isPersistent():
            flags |= libvirt.VIR_DOMAIN_AFFECT_CONFIG

        # remove the current nic
        xml = etree.tostring(iface)
        dom.detachDeviceFlags(xml, flags=flags)

        # add the nic with the desired mac address
        iface.mac.attrib['address'] = params['mac']
        xml = etree.tostring(iface)
        dom.attachDeviceFlags(xml, flags=flags)

        return [vm, params['mac']]
Esempio n. 20
0
 def _get_volume_path(self, pool, vol):
     pool = self._get_storage_pool(pool)
     try:
         return pool.storageVolLookupByName(vol).path()
     except:
         raise NotFoundError("KCHVOL0002E", {'name': vol,
                                             'pool': pool})
Esempio n. 21
0
 def lookup(self, name):
     """
     Gets list of all configured device info(dictionary) devices
     with name of device as key.
     If the list has the device lookup is looking for then returns
     the device info.
     Otherwise gets list of all un-configured device info devices
     with name of device as key.
     If the list has the device lookup is looking for then returns
     the device info.
     Otherwise raises InvalidParameter exception.
     :param name: name of device to lookup.
     :return: OSA device info if device found otherwise InvalidParameter
     """
     wok_log.info('Fetching attributes of network devices %s' % name)
     _validate_device(name)
     configured_devices = _get_configured_devices(key=UNIQUE_COL_NAME)
     device = configured_devices.get(name, None)
     if not device:
         unconfigured_devices = _get_unconfigured_devices(
             key=UNIQUE_COL_NAME)
         device = unconfigured_devices.get(name, None)
     if not device:
         wok_log.error('Given device is not of type OSA. Device: %s', name)
         raise NotFoundError("GS390XIONW006E", {'device': name})
     wok_log.info('Attributes of network devices %s: %s' % (name, device))
     return device
Esempio n. 22
0
    def lookup(name):
        """Method that retrieves information about a service.

        Returns:
            dic: A dictionary that represents the state of the service.
                Format:
                {
                    'cgroup': (str),
                    'desc': (str),
                    'load': (str),
                    'active': (str),
                    'sub': (str),
                    'autostart': (bool)
                }

        Raises:
            NotFoundError if the service does not exist.

        """
        if not service_exists(name):
            raise NotFoundError('GINSERV00002E', {'name': name})

        lookup_dict = get_service_info(name)
        lookup_dict['name'] = name
        if lookup_dict.get('cgroup'):
            lookup_dict['cgroup'] = get_cgroup_info(lookup_dict['cgroup'])

        return lookup_dict
Esempio n. 23
0
def _pvdisplay_out(name):
    """
    This method fetches the details of particular PV
    :param name: path of the PV
    :return:
    """
    pv_version = get_lvm_version()
    # Disabled unsupported options to vgs command below
    # a threshold version
    if LooseVersion(pv_version) < LooseVersion(LVM_THR_VERSION):
        below_threshold_version = True
        cmd = ['pvs', '-o', 'pv_name,vg_name,'
               'pv_size,'
               'pv_pe_count,pv_pe_alloc_count,'
               'pv_uuid,vg_extent_size,'
               'vg_free_count', "--separator", ":", name,
               "--units", "K"]
    else:
        below_threshold_version = False
        cmd = ['pvs', '-o', 'pv_name,vg_name,'
               'pv_size,pv_allocatable,'
               'pv_pe_count,pv_pe_alloc_count,'
               'pv_uuid,vg_extent_size,'
               'vg_free_count', "--separator", ":", name,
               "--units", "K"]
    out, err, rc = run_command(cmd)

    if rc == 5 and 'Failed to find device' in err:
        raise NotFoundError("GINPV00011E", {'dev': name})

    elif rc != 0:
        raise OperationFailed("GINPV00007E",
                              {'dev': name, 'err': err})

    return parse_pvdisplay_output(out, below_threshold_version)
Esempio n. 24
0
    def lookup(self, name):
        try:
            return fs_utils._get_fs_info(name)

        except ValueError:
            wok_log.error("Filesystem %s" " not found." % name)
            raise NotFoundError("GINFS00001E", {'name': name})
Esempio n. 25
0
    def lookup(self, name):
        try:
            out_dict = utils._lvdisplay_out(name)
            return out_dict

        except OperationFailed:
            raise NotFoundError("GINLV00005E", {'name': name})
Esempio n. 26
0
    def lookup(self, name):
        if encode_value(name) not in map(encode_value, ethtool.get_devices()):
            raise NotFoundError('KCHIFACE0001E', {'name': name})

        ipaddr = ''
        netmask = ''
        module = 'unknown'
        status = 'down'
        try:
            ipaddr = ethtool.get_ipaddr(encode_value(name))
            netmask = ethtool.get_netmask(encode_value(name))
            module = ethtool.get_module(encode_value(name))

            flags = ethtool.get_flags(encode_value(name))
            status = 'up' if flags & (ethtool.IFF_RUNNING
                                      | ethtool.IFF_UP) else 'down'
        except IOError:
            pass

        iface_type = netinfo.get_interface_type(name)

        return {
            'name': name,
            'type': iface_type,
            'status': status,
            'ipaddr': ipaddr,
            'netmask': netmask,
            'module': module,
        }
Esempio n. 27
0
    def delete(self, vmid, dev_name):
        dom = VMModel.get_vm(vmid, self.conn)
        xmlstr = dom.XMLDesc(0)
        root = objectify.fromstring(xmlstr)

        try:
            hostdev = root.devices.hostdev

        except AttributeError:
            raise NotFoundError('KCHVMHDEV0001E', {
                                'vmid': vmid, 'dev_name': dev_name})

        task_params = {
            'vmid': vmid,
            'dev_name': dev_name,
            'dom': dom,
            'hostdev': hostdev,
            'lock': threading.RLock(),
        }
        task_uri = u'/plugins/kimchi/vms/%s/hostdevs/%s' % (
            VMModel.get_vm(vmid, self.conn).name(),
            dev_name,
        )
        taskid = AsyncTask(task_uri, self._detach_device, task_params).id
        return self.task.lookup(taskid)
Esempio n. 28
0
    def getUpdate(self, name):
        """
        Return a dictionary with all info from a given package name.
        """
        if name not in self._packages.keys():
            raise NotFoundError('GGBPKGUPD0002E', {'name': name})

        return self._packages[name]
Esempio n. 29
0
    def _get_user(self, _user_id):
        ldap_server = config.get('authentication', 'ldap_server').strip('"')
        ldap_search_base = config.get(
            'authentication', 'ldap_search_base').strip('"')
        ldap_search_filter = config.get(
            'authentication', 'ldap_search_filter',
            vars={'username': _user_id.encode('utf-8')}).strip('"')

        connect = ldap.open(ldap_server)
        try:
            result = connect.search_s(
                ldap_search_base, ldap.SCOPE_SUBTREE, ldap_search_filter)
            if len(result) == 0:
                raise NotFoundError('KCHAUTH0004E', {'user_id': _user_id})
            return result[0][1]
        except ldap.NO_SUCH_OBJECT:
            raise NotFoundError('KCHAUTH0004E', {'user_id': _user_id})
Esempio n. 30
0
 def delete(self, obj_type, ident, ignore_missing=False):
     c = self.conn.cursor()
     c.execute('DELETE FROM objects WHERE type=? AND id=?',
               (obj_type, ident))
     if c.rowcount != 1 and not ignore_missing:
         self.conn.rollback()
         raise NotFoundError("WOKOBJST0001E", {'item': ident})
     self.conn.commit()