예제 #1
0
 def get_current_settings_s390x(self):
     """
     Method to return current SMT settings ('/proc/cmdline')
     for s390x architecture.
     Returns:
     current_smt_settings: dictionary {status, value}
     """
     command = ['cat', '/proc/cmdline']
     threads_per_core = LsCpu().get_threads_per_core()
     output, error, retcode = run_command(command)
     if retcode != 0:
         raise OperationFailed('GINSMT003E', {'error': error})
     elif (SMT_TWO in output or SMT not in output):
         status = 'enabled'
         value = threads_per_core
     elif SMT_ONE in output and threads_per_core < 2:
         status = 'enabled'
         value = 1
     elif NOSMT in output and threads_per_core < 2:
         status = 'disabled'
         value = NOSMT
     else:
         raise InvalidOperation('GINSMT0001E')
     current_smt_settings = {'status': status, 'smt': value}
     return current_smt_settings
예제 #2
0
파일: cpuinfo.py 프로젝트: popbjc/kimchi
    def __init__(self, **kargs):
        self.guest_threads_enabled = False
        self.sockets = 0
        self.cores_present = 0
        self.cores_available = 0
        self.cores_per_socket = 0
        self.threads_per_core = 0
        self.max_threads = 0
        self.lscpu = LsCpu()

        if ARCH == 'power':
            # IBM PowerPC
            self.guest_threads_enabled = True
            out, error, rc = run_command(['ppc64_cpu', '--smt'])
            if rc or 'on' in out:
                # SMT has to be disabled for guest to use threads as CPUs.
                # rc is always zero, whether SMT is off or on.
                self.guest_threads_enabled = False
            out, error, rc = run_command(['ppc64_cpu', '--cores-present'])
            if not rc:
                self.cores_present = int(out.split()[-1])
            out, error, rc = run_command(['ppc64_cpu', '--cores-on'])
            if not rc:
                self.cores_available = int(out.split()[-1])
            out, error, rc = run_command(['ppc64_cpu', '--threads-per-core'])
            if not rc:
                self.threads_per_core = int(out.split()[-1])
            self.sockets = self.cores_present / self.threads_per_core
            if self.sockets == 0:
                self.sockets = 1
            self.cores_per_socket = self.cores_present / self.sockets
        else:
            # Intel or AMD
            self.guest_threads_enabled = True
            self.sockets = int(self.lscpu.get_sockets())
            self.cores_per_socket = int(self.lscpu.get_cores_per_socket())
            self.cores_present = self.cores_per_socket * self.sockets
            self.cores_available = self.cores_present
            self.threads_per_core = self.lscpu.get_threads_per_core()
예제 #3
0
    def __init__(self, **kargs):
        self.guest_threads_enabled = False
        self.sockets = 0
        self.cores_present = 0
        self.cores_available = 0
        self.cores_per_socket = 0
        self.threads_per_core = 0
        self.max_threads = 0
        self.lscpu = LsCpu()

        if ARCH == "power":
            # IBM PowerPC
            self.guest_threads_enabled = True
            out, error, rc = run_command(["ppc64_cpu", "--smt"])
            if rc or "on" in out:
                # SMT has to be disabled for guest to use threads as CPUs.
                # rc is always zero, whether SMT is off or on.
                self.guest_threads_enabled = False
            out, error, rc = run_command(["ppc64_cpu", "--cores-present"])
            if not rc:
                self.cores_present = int(out.split()[-1])
            out, error, rc = run_command(["ppc64_cpu", "--cores-on"])
            if not rc:
                self.cores_available = int(out.split()[-1])
            out, error, rc = run_command(["ppc64_cpu", "--threads-per-core"])
            if not rc:
                self.threads_per_core = int(out.split()[-1])
            self.sockets = self.cores_present / self.threads_per_core
            if self.sockets == 0:
                self.sockets = 1
            self.cores_per_socket = self.cores_present / self.sockets
        else:
            # Intel or AMD
            self.guest_threads_enabled = True
            self.sockets = int(self.lscpu.get_sockets())
            self.cores_per_socket = int(self.lscpu.get_cores_per_socket())
            self.cores_present = self.cores_per_socket * self.sockets
            self.cores_available = self.cores_present
            self.threads_per_core = self.lscpu.get_threads_per_core()
예제 #4
0
 def __init__(self, **kargs):
     # self.conn = kargs['conn']
     self.objstore = kargs['objstore']
     self.task = TaskModel(**kargs)
     self.lscpu = LsCpu()
예제 #5
0
class HostModel(object):
    def __init__(self, **kargs):
        # self.conn = kargs['conn']
        self.objstore = kargs['objstore']
        self.task = TaskModel(**kargs)
        self.lscpu = LsCpu()

    def _get_ppc_cpu_model(self):
        """
        method to get cpu_model for ppc architecture
        """
        res = {}
        with open(PROC_CPUINFO) as f:
            for line in f:
                # Parse CPU, CPU's revision and CPU's clock information
                for key in ['cpu', 'revision', 'clock']:
                    if key in line:
                        info = line.split(':')[1].strip()
                        if key == 'clock':
                            value = float(info.split('MHz')[0].strip()) / 1000
                        else:
                            value = info.split('(')[0].strip()
                        res[key] = value

                        # Power machines show, for each cpu/core, a block with
                        # all cpu information. Here we control the scan of the
                        # necessary information (1st block provides
                        # everything), skipping the function when find all
                        # information.
                        if len(res.keys()) == 3:
                            return '%(cpu)s (%(revision)s) @ %(clock)s GHz\
                                    ' % res

        return ''

    def _get_x86_cpu_model(self):
        """
        method to get cpu_model for x86 architecture
        """
        try:
            with open(PROC_CPUINFO) as f:
                for line in f:
                    if 'model name' in line:
                        return line.split(':')[1].strip()
                        break
        except Exception as e:
            wok_log.error('Failed to retrive cpu_model for '
                          '%s. Error: %s', ARCH, e.__str__())
        return ''

    def _get_s390x_host_info(self):
        """
        method to get additional host details
        specific to s390x architecture
        :return: dictionary
        """
        host_info = {}
        host_info['cpus'] = self._get_cpus()
        host_info['cpus']['dedicated'] = 0
        host_info['cpus']['shared'] = 0
        host_info['cpu_model'] = ''
        host_info['virtualization'] = {}
        s390x_sysinfo = self._get_s390x_sysinfo()
        if 'manufacturer' in s390x_sysinfo.keys():
            host_info['cpu_model'] = s390x_sysinfo['manufacturer']
        if 'type' in s390x_sysinfo.keys():
            host_info['cpu_model'] = \
                host_info['cpu_model'] + '/' + s390x_sysinfo['type']
        if 'model' in s390x_sysinfo.keys():
            host_info['cpu_model'] = \
                host_info['cpu_model'] + '/' + s390x_sysinfo['model']
        if CPUS_DEDICATED in s390x_sysinfo.keys():
            host_info['cpus']['dedicated'] = s390x_sysinfo[CPUS_DEDICATED]
        if CPUS_SHARED in s390x_sysinfo.keys():
            host_info['cpus']['shared'] = s390x_sysinfo[CPUS_SHARED]
        host_info['virtualization']['hypervisor'] = \
            self.lscpu.get_hypervisor()
        host_info['virtualization']['hypervisor_vendor'] = \
            self.lscpu.get_hypervisor_vendor()
        host_info['virtualization'][LPAR_NAME] = ''
        host_info['virtualization'][LPAR_NUMBER] = ''
        if LPAR_NAME in s390x_sysinfo.keys():
            host_info['virtualization'][LPAR_NAME] = s390x_sysinfo[LPAR_NAME]
        if LPAR_NUMBER in s390x_sysinfo.keys():
            host_info['virtualization'][LPAR_NUMBER] = \
                s390x_sysinfo[LPAR_NUMBER]

        return host_info

    def _get_s390x_sysinfo(self):
        """
        This method retrieves following system information
        for s390 architecture
        * manufacturer: Manufacturer of host machine
        * type: Type of the host machine
        * model:Model of host machine
        * LPAR_NUMBER: LPAR Number of host
        * LPAR_NAME: Name of host LPAR
        * CPUS_DEDICATED: LPAR CPUs Dedicated
        * CPUS_SHARED: LPAR CPUs Shared

        :param self: object of the class self
        :return: dictionary with following keys -
                 'manufacturer', 'type', 'model', CPUS_SHARED,
                 CPUS_DEDICATED, LPAR_NUMBER, LPAR_NAME
        """
        s390x_sysinfo = {}
        try:
            with open(PROC_SYSINFO) as f:
                for line in f:
                    if ':' in line and (len(line.split(':')) == 2):
                        info = line.split(':')
                        if info[0] == 'Model' and (len(info[1].split()) == 2):
                            s390x_sysinfo['model'] = \
                                info[1].split()[0].strip() +\
                                ' ' + info[1].split()[1].strip()
                        elif info[0] == 'Manufacturer':
                            s390x_sysinfo['manufacturer'] = info[1].strip()
                        elif info[0] == 'Type':
                            s390x_sysinfo['type'] = info[1].strip()
                        elif info[0] == 'LPAR Number':
                            s390x_sysinfo[LPAR_NUMBER] = int(info[1].strip())
                        elif info[0] == 'LPAR Name':
                            s390x_sysinfo[LPAR_NAME] = info[1].strip()
                        elif info[0] == 'LPAR CPUs Dedicated':
                            s390x_sysinfo[CPUS_DEDICATED] =\
                                int(info[1].strip())
                        elif info[0] == 'LPAR CPUs Shared':
                            s390x_sysinfo[CPUS_SHARED] = int(info[1].strip())
        except Exception as e:
            wok_log.error(
                'Failed to retrieve information from %s file. '
                'Error: %s', PROC_SYSINFO, e.__str__())

        return s390x_sysinfo

    def _get_memory(self):
        """
        method to retrieve memory information for all architecture
        :return: dictionary with keys "online" and "offline"
        """
        memory = {}
        online_memory = 0
        offline_memory = 0
        if ARCH.startswith('s390x'):
            online_mem_pat = r'^Total online memory :\s+(\d+)\s+MB$'
            offline_mem_pat = r'^Total offline memory:\s+(\d+)\s+MB$'
            out, err, rc = run_command(LSMEM)
            # output of lsmem in s390x architecture is expected to be
            # Address Range                          Size (MB)  State\
            #     Removable  Device
            # ========================================================\
            # =======================
            # 0x0000000000000000-0x000000000fffffff        256  online\
            #    no         0
            # 0x0000000010000000-0x000000002fffffff        512  online\
            #    yes        1-2
            # 0x0000000030000000-0x000000007fffffff       1280  online\
            #    no         3-7
            # 0x0000000080000000-0x00000000ffffffff       2048  offline\
            #   -          8-15
            #
            # Memory device size  : 256 MB
            # Memory block size   : 256 MB
            # Total online memory : 2048 MB
            # Total offline memory: 2048 MB
            if not rc:
                online_mem =\
                    re.search(online_mem_pat, out.strip(), re.M | re.I)
                offline_mem =\
                    re.search(offline_mem_pat, out.strip(), re.M | re.I)
                if online_mem and len(online_mem.groups()) == 1:
                    online_memory = int(online_mem.group(1)) * 1024 * 1024
                    # converting MB to bytes
                    # lsmem always returns memory in MB
                if offline_mem and len(offline_mem.groups()) == 1:
                    offline_memory = int(offline_mem.group(1)) * 1024 * 1024
            else:
                wok_log.error('Failed to retrieve memory information with'
                              ' command %s. Error: %s' % (LSMEM, err))
        else:
            if hasattr(psutil, 'phymem_usage'):
                online_memory = psutil.phymem_usage().total
            elif hasattr(psutil, 'virtual_memory'):
                online_memory = psutil.virtual_memory().total

        memory['online'] = online_memory
        memory['offline'] = offline_memory
        return memory

    def _get_cpus(self):
        """
        method to retrieve online cpus count and offline cpus
        count for all architecture
        :return: dictionary with keys "online" and "offline"
        """
        cpus = {}
        total_cpus = int(self.lscpu.get_total_cpus())

        # psutil is unstable on how to get the number of
        # cpus, different versions call it differently
        online_cpus = 0

        if hasattr(psutil, 'cpu_count'):
            online_cpus = psutil.cpu_count()

        elif hasattr(psutil, 'NUM_CPUS'):
            online_cpus = psutil.NUM_CPUS

        elif hasattr(psutil, '_psplatform'):
            for method_name in ['_get_num_cpus', 'get_num_cpus']:

                method = getattr(psutil._psplatform, method_name, None)
                if method is not None:
                    online_cpus = method()
                    break

        if online_cpus > 0:
            offline_cpus = 0
            if total_cpus > online_cpus:
                offline_cpus = total_cpus - online_cpus
        else:
            online_cpus = 'unknown'
            offline_cpus = 'unknown'

        cpus['online'] = online_cpus
        cpus['offline'] = offline_cpus
        return cpus

    def _get_base_info(self):
        """
        method to retrieve common host information for all architectures
        :return: dictionary with keys 'os_distro', 'os_version', 'os_codename'
                 'architecture', 'host', memory
        """
        common_info = {}
        # Include IBM PowerKVM name to supported distro names
        _sup_distros = platform._supported_dists + ('ibm_powerkvm', )
        # 'fedora' '17' 'Beefy Miracle'
        distro, version, codename = platform.linux_distribution(
            supported_dists=_sup_distros)
        common_info['os_distro'] = distro
        common_info['os_version'] = version
        common_info['os_codename'] = codename
        common_info['architecture'] = ARCH
        common_info['host'] = platform.node()
        common_info['memory'] = self._get_memory()
        common_info['cpu_threads'] = {}
        common_info['cpu_threads']['sockets'] = self.lscpu.get_sockets()
        common_info['cpu_threads']['cores_per_socket'] = \
            self.lscpu.get_cores_per_socket()
        common_info['cpu_threads']['threads_per_core'] = \
            self.lscpu.get_threads_per_core()
        if ARCH.startswith('s390x'):
            common_info['cpu_threads']['books'] = self.lscpu.get_books()

        return common_info

    def lookup(self, *name):
        """
        method to get basic information for host
        """
        host_info = self._get_base_info()
        if ARCH.startswith('s390x'):
            host_info.update(self._get_s390x_host_info())
        elif ARCH.startswith('ppc'):
            host_info['cpus'] = self._get_cpus()
            host_info['cpu_model'] = self._get_ppc_cpu_model()
        else:
            host_info['cpus'] = self._get_cpus()
            host_info['cpu_model'] = self._get_x86_cpu_model()
        return host_info

    def swupdate(self, *name):
        try:
            swupdate = SoftwareUpdate()
        except Exception:
            raise OperationFailed('GGBPKGUPD0004E')

        pkgs = swupdate.getNumOfUpdates()
        if pkgs == 0:
            wok_log.debug(messages['GGBPKGUPD0001E'])
            return {'message': messages['GGBPKGUPD0001E']}

        wok_log.debug('Host is going to be updated.')
        taskid = AsyncTask('/plugins/gingerbase/host/swupdate',
                           swupdate.doUpdate).id
        return self.task.lookup(taskid)

    def shutdown(self, args=None):
        # Check for running vms before shutdown
        running_vms = self.get_vmlist_bystate('running')
        if len(running_vms) > 0:
            raise OperationFailed('GGBHOST0001E')

        wok_log.info('Host is going to shutdown.')
        os.system('shutdown -h now')

    def reboot(self, args=None):
        # Check for running vms before reboot
        running_vms = self.get_vmlist_bystate('running')
        if len(running_vms) > 0:
            raise OperationFailed('GGBHOST0002E')

        wok_log.info('Host is going to reboot.')
        os.system('reboot')

    def get_vmlist_bystate(self, state='running'):
        try:
            libvirt_mod = __import__('libvirt')
        except Exception as e:
            wok_log.info('Unable to import libvirt module. Details:',
                         e.message)
            # Ignore any error and assume there is no vm running in the host
            return []

        libvirtd_running = ['systemctl', 'is-active', 'libvirtd', '--quiet']
        _, _, rcode = run_command(libvirtd_running, silent=True)
        if rcode != 0:
            return []

        try:
            conn = libvirt_mod.open(None)
            return [
                dom.name().decode('utf-8') for dom in conn.listAllDomains(0)
                if (DOM_STATE_MAP[dom.info()[0]] == state)
            ]
        except Exception as e:
            wok_log.info(
                'Unable to get virtual machines information. '
                'Details:', e.message)
            raise OperationFailed('GGBHOST0003E')
예제 #6
0
파일: cpuinfo.py 프로젝트: popbjc/kimchi
class CPUInfoModel(object):
    """
    Get information about a CPU for hyperthreading (on x86)
    or SMT (on POWER) for logic when creating templates and VMs.
    """
    def __init__(self, **kargs):
        self.guest_threads_enabled = False
        self.sockets = 0
        self.cores_present = 0
        self.cores_available = 0
        self.cores_per_socket = 0
        self.threads_per_core = 0
        self.max_threads = 0
        self.lscpu = LsCpu()

        if ARCH == 'power':
            # IBM PowerPC
            self.guest_threads_enabled = True
            out, error, rc = run_command(['ppc64_cpu', '--smt'])
            if rc or 'on' in out:
                # SMT has to be disabled for guest to use threads as CPUs.
                # rc is always zero, whether SMT is off or on.
                self.guest_threads_enabled = False
            out, error, rc = run_command(['ppc64_cpu', '--cores-present'])
            if not rc:
                self.cores_present = int(out.split()[-1])
            out, error, rc = run_command(['ppc64_cpu', '--cores-on'])
            if not rc:
                self.cores_available = int(out.split()[-1])
            out, error, rc = run_command(['ppc64_cpu', '--threads-per-core'])
            if not rc:
                self.threads_per_core = int(out.split()[-1])
            self.sockets = self.cores_present / self.threads_per_core
            if self.sockets == 0:
                self.sockets = 1
            self.cores_per_socket = self.cores_present / self.sockets
        else:
            # Intel or AMD
            self.guest_threads_enabled = True
            self.sockets = int(self.lscpu.get_sockets())
            self.cores_per_socket = int(self.lscpu.get_cores_per_socket())
            self.cores_present = self.cores_per_socket * self.sockets
            self.cores_available = self.cores_present
            self.threads_per_core = self.lscpu.get_threads_per_core()

    def lookup(self, ident):
        return {
            'guest_threads_enabled': self.guest_threads_enabled,
            'sockets': self.sockets,
            'cores_per_socket': self.cores_per_socket,
            'cores_present': self.cores_present,
            'cores_available': self.cores_available,
            'threads_per_core': self.threads_per_core,
        }

    def check_topology(self, vcpus, topology):
        """
            param vcpus: should be an integer
            param iso_path: the path of the guest ISO
            param topology: {'sockets': x, 'cores': x, 'threads': x}
        """
        sockets = topology['sockets']
        cores = topology['cores']
        threads = topology['threads']

        if not self.guest_threads_enabled:
            raise InvalidOperation("GGBCPUINF0003E")
        if vcpus != sockets * cores * threads:
            raise InvalidParameter("GGBCPUINF0002E")
        if vcpus > self.cores_available * self.threads_per_core:
            raise InvalidParameter("GGBCPUINF0001E")
        if threads > self.threads_per_core:
            raise InvalidParameter("GGBCPUINF0002E")
예제 #7
0
class CPUInfoModel(object):
    """
    Get information about a CPU for hyperthreading (on x86)
    or SMT (on POWER) for logic when creating templates and VMs.
    """

    def __init__(self, **kargs):
        self.guest_threads_enabled = False
        self.sockets = 0
        self.cores_present = 0
        self.cores_available = 0
        self.cores_per_socket = 0
        self.threads_per_core = 0
        self.max_threads = 0
        self.lscpu = LsCpu()

        if ARCH == "power":
            # IBM PowerPC
            self.guest_threads_enabled = True
            out, error, rc = run_command(["ppc64_cpu", "--smt"])
            if rc or "on" in out:
                # SMT has to be disabled for guest to use threads as CPUs.
                # rc is always zero, whether SMT is off or on.
                self.guest_threads_enabled = False
            out, error, rc = run_command(["ppc64_cpu", "--cores-present"])
            if not rc:
                self.cores_present = int(out.split()[-1])
            out, error, rc = run_command(["ppc64_cpu", "--cores-on"])
            if not rc:
                self.cores_available = int(out.split()[-1])
            out, error, rc = run_command(["ppc64_cpu", "--threads-per-core"])
            if not rc:
                self.threads_per_core = int(out.split()[-1])
            self.sockets = self.cores_present / self.threads_per_core
            if self.sockets == 0:
                self.sockets = 1
            self.cores_per_socket = self.cores_present / self.sockets
        else:
            # Intel or AMD
            self.guest_threads_enabled = True
            self.sockets = int(self.lscpu.get_sockets())
            self.cores_per_socket = int(self.lscpu.get_cores_per_socket())
            self.cores_present = self.cores_per_socket * self.sockets
            self.cores_available = self.cores_present
            self.threads_per_core = self.lscpu.get_threads_per_core()

    def lookup(self, ident):
        return {
            "guest_threads_enabled": self.guest_threads_enabled,
            "sockets": self.sockets,
            "cores_per_socket": self.cores_per_socket,
            "cores_present": self.cores_present,
            "cores_available": self.cores_available,
            "threads_per_core": self.threads_per_core,
        }

    def check_topology(self, vcpus, topology):
        """
            param vcpus: should be an integer
            param iso_path: the path of the guest ISO
            param topology: {'sockets': x, 'cores': x, 'threads': x}
        """
        sockets = topology["sockets"]
        cores = topology["cores"]
        threads = topology["threads"]

        if not self.guest_threads_enabled:
            raise InvalidOperation("GGBCPUINF0003E")
        if vcpus != sockets * cores * threads:
            raise InvalidParameter("GGBCPUINF0002E")
        if vcpus > self.cores_available * self.threads_per_core:
            raise InvalidParameter("GGBCPUINF0001E")
        if threads > self.threads_per_core:
            raise InvalidParameter("GGBCPUINF0002E")
예제 #8
0
파일: host.py 프로젝트: Clevero/gingerbase
 def __init__(self, **kargs):
     # self.conn = kargs['conn']
     self.objstore = kargs['objstore']
     self.task = TaskModel(**kargs)
     self.lscpu = LsCpu()
예제 #9
0
파일: host.py 프로젝트: Clevero/gingerbase
class HostModel(object):
    def __init__(self, **kargs):
        # self.conn = kargs['conn']
        self.objstore = kargs['objstore']
        self.task = TaskModel(**kargs)
        self.lscpu = LsCpu()

    def _get_ppc_cpu_model(self):
        """
        method to get cpu_model for ppc architecture
        """
        res = {}
        with open(PROC_CPUINFO) as f:
            for line in f.xreadlines():
                # Parse CPU, CPU's revision and CPU's clock information
                for key in ['cpu', 'revision', 'clock']:
                    if key in line:
                        info = line.split(':')[1].strip()
                        if key == 'clock':
                            value = float(info.split('MHz')[0].strip()) / 1000
                        else:
                            value = info.split('(')[0].strip()
                        res[key] = value

                        # Power machines show, for each cpu/core, a block with
                        # all cpu information. Here we control the scan of the
                        # necessary information (1st block provides
                        # everything), skipping the function when find all
                        # information.
                        if len(res.keys()) == 3:
                            return "%(cpu)s (%(revision)s) @ %(clock)s GHz\
                                    " % res

        return ""

    def _get_x86_cpu_model(self):
        """
        method to get cpu_model for x86 architecture
        """
        try:
            with open(PROC_CPUINFO) as f:
                for line in f.xreadlines():
                    if "model name" in line:
                        return line.split(':')[1].strip()
                        break
        except Exception as e:
            wok_log.error("Failed to retrive cpu_model for "
                          "%s. Error: %s", ARCH, e.__str__())
        return ""

    def _get_s390x_host_info(self):
        """
        method to get additional host details
        specific to s390x architecture
        :return: dictionary
        """
        host_info = {}
        host_info['cpus'] = self._get_cpus()
        host_info['cpus']['dedicated'] = 0
        host_info['cpus']['shared'] = 0
        host_info['cpu_model'] = ""
        host_info['virtualization'] = {}
        s390x_sysinfo = self._get_s390x_sysinfo()
        if 'manufacturer' in s390x_sysinfo.keys():
            host_info['cpu_model'] = s390x_sysinfo['manufacturer']
        if 'type' in s390x_sysinfo.keys():
            host_info['cpu_model'] = \
                host_info['cpu_model'] + "/" + s390x_sysinfo['type']
        if 'model' in s390x_sysinfo.keys():
            host_info['cpu_model'] = \
                host_info['cpu_model'] + "/" + s390x_sysinfo['model']
        if CPUS_DEDICATED in s390x_sysinfo.keys():
            host_info['cpus']['dedicated'] = s390x_sysinfo[CPUS_DEDICATED]
        if CPUS_SHARED in s390x_sysinfo.keys():
            host_info['cpus']['shared'] = s390x_sysinfo[CPUS_SHARED]
        host_info['virtualization']['hypervisor'] = \
            self.lscpu.get_hypervisor()
        host_info['virtualization']['hypervisor_vendor'] = \
            self.lscpu.get_hypervisor_vendor()
        host_info['virtualization'][LPAR_NAME] = ''
        host_info['virtualization'][LPAR_NUMBER] = ''
        if LPAR_NAME in s390x_sysinfo.keys():
            host_info['virtualization'][LPAR_NAME] = s390x_sysinfo[LPAR_NAME]
        if LPAR_NUMBER in s390x_sysinfo.keys():
            host_info['virtualization'][LPAR_NUMBER] = \
                s390x_sysinfo[LPAR_NUMBER]

        return host_info

    def _get_s390x_sysinfo(self):
        """
        This method retrieves following system information
        for s390 architecture
        * manufacturer: Manufacturer of host machine
        * type: Type of the host machine
        * model:Model of host machine
        * LPAR_NUMBER: LPAR Number of host
        * LPAR_NAME: Name of host LPAR
        * CPUS_DEDICATED: LPAR CPUs Dedicated
        * CPUS_SHARED: LPAR CPUs Shared

        :param self: object of the class self
        :return: dictionary with following keys -
                 'manufacturer', 'type', 'model', CPUS_SHARED,
                 CPUS_DEDICATED, LPAR_NUMBER, LPAR_NAME
        """
        s390x_sysinfo = {}
        try:
            with open(PROC_SYSINFO) as f:
                for line in f.xreadlines():
                    if ":" in line and (len(line.split(':')) == 2):
                        info = line.split(':')
                        if info[0] == 'Model' and (len(info[1].split()) == 2):
                            s390x_sysinfo['model'] = \
                                info[1].split()[0].strip() +\
                                " "+info[1].split()[1].strip()
                        elif info[0] == 'Manufacturer':
                            s390x_sysinfo['manufacturer'] = info[1].strip()
                        elif info[0] == 'Type':
                            s390x_sysinfo['type'] = info[1].strip()
                        elif info[0] == 'LPAR Number':
                            s390x_sysinfo[LPAR_NUMBER] = int(info[1].strip())
                        elif info[0] == 'LPAR Name':
                            s390x_sysinfo[LPAR_NAME] = info[1].strip()
                        elif info[0] == 'LPAR CPUs Dedicated':
                            s390x_sysinfo[CPUS_DEDICATED] =\
                                int(info[1].strip())
                        elif info[0] == 'LPAR CPUs Shared':
                            s390x_sysinfo[CPUS_SHARED] = int(info[1].strip())
        except Exception as e:
            wok_log.error("Failed to retrieve information from %s file. "
                          "Error: %s", PROC_SYSINFO, e.__str__())

        return s390x_sysinfo

    def _get_memory(self):
        """
        method to retrieve memory information for all architecture
        :return: dictionary with keys "online" and "offline"
        """
        memory = {}
        online_memory = 0
        offline_memory = 0
        if ARCH.startswith('s390x'):
            online_mem_pat = r'^Total online memory :\s+(\d+)\s+MB$'
            offline_mem_pat = r'^Total offline memory:\s+(\d+)\s+MB$'
            out, err, rc = run_command(LSMEM)
            # output of lsmem in s390x architecture is expected to be
            # Address Range                          Size (MB)  State\
            #     Removable  Device
            # ========================================================\
            # =======================
            # 0x0000000000000000-0x000000000fffffff        256  online\
            #    no         0
            # 0x0000000010000000-0x000000002fffffff        512  online\
            #    yes        1-2
            # 0x0000000030000000-0x000000007fffffff       1280  online\
            #    no         3-7
            # 0x0000000080000000-0x00000000ffffffff       2048  offline\
            #   -          8-15
            #
            # Memory device size  : 256 MB
            # Memory block size   : 256 MB
            # Total online memory : 2048 MB
            # Total offline memory: 2048 MB
            if not rc:
                online_mem =\
                    re.search(online_mem_pat, out.strip(), re.M | re.I)
                offline_mem =\
                    re.search(offline_mem_pat, out.strip(), re.M | re.I)
                if online_mem and len(online_mem.groups()) == 1:
                    online_memory = int(online_mem.group(1)) * 1024 * 1024
                    # converting MB to bytes
                    # lsmem always returns memory in MB
                if offline_mem and len(offline_mem.groups()) == 1:
                    offline_memory = int(offline_mem.group(1)) * 1024 * 1024
            else:
                wok_log.error('Failed to retrieve memory information with'
                              ' command %s. Error: %s' % (LSMEM, err))
        else:
            if hasattr(psutil, 'phymem_usage'):
                online_memory = psutil.phymem_usage().total
            elif hasattr(psutil, 'virtual_memory'):
                online_memory = psutil.virtual_memory().total

        memory['online'] = online_memory
        memory['offline'] = offline_memory
        return memory

    def _get_cpus(self):
        """
        method to retrieve online cpus count and offline cpus
        count for all architecture
        :return: dictionary with keys "online" and "offline"
        """
        cpus = {}
        total_cpus = int(self.lscpu.get_total_cpus())

        # psutil is unstable on how to get the number of
        # cpus, different versions call it differently
        online_cpus = 0

        if hasattr(psutil, 'cpu_count'):
            online_cpus = psutil.cpu_count()

        elif hasattr(psutil, 'NUM_CPUS'):
            online_cpus = psutil.NUM_CPUS

        elif hasattr(psutil, '_psplatform'):
            for method_name in ['_get_num_cpus', 'get_num_cpus']:

                method = getattr(psutil._psplatform, method_name, None)
                if method is not None:
                    online_cpus = method()
                    break

        if online_cpus > 0:
            offline_cpus = 0
            if total_cpus > online_cpus:
                offline_cpus = total_cpus - online_cpus
        else:
            online_cpus = "unknown"
            offline_cpus = "unknown"

        cpus['online'] = online_cpus
        cpus['offline'] = offline_cpus
        return cpus

    def _get_base_info(self):
        """
        method to retrieve common host information for all architectures
        :return: dictionary with keys 'os_distro', 'os_version', 'os_codename'
                 'architecture', 'host', memory
        """
        common_info = {}
        # Include IBM PowerKVM name to supported distro names
        _sup_distros = platform._supported_dists + ('ibm_powerkvm',)
        # 'fedora' '17' 'Beefy Miracle'
        distro, version, codename = platform.linux_distribution(
            supported_dists=_sup_distros)
        common_info['os_distro'] = distro
        common_info['os_version'] = version
        common_info['os_codename'] = unicode(codename, "utf-8")
        common_info['architecture'] = ARCH
        common_info['host'] = platform.node()
        common_info['memory'] = self._get_memory()
        common_info['cpu_threads'] = {}
        common_info['cpu_threads']['sockets'] = self.lscpu.get_sockets()
        common_info['cpu_threads']['cores_per_socket'] = \
            self.lscpu.get_cores_per_socket()
        common_info['cpu_threads']['threads_per_core'] = \
            self.lscpu.get_threads_per_core()
        if ARCH.startswith('s390x'):
            common_info['cpu_threads']['books'] = self.lscpu.get_books()

        return common_info

    def lookup(self, *name):
        """
        method to get basic information for host
        """
        host_info = self._get_base_info()
        if ARCH.startswith('s390x'):
            host_info.update(self._get_s390x_host_info())
        elif ARCH.startswith('ppc'):
            host_info['cpus'] = self._get_cpus()
            host_info['cpu_model'] = self._get_ppc_cpu_model()
        else:
            host_info['cpus'] = self._get_cpus()
            host_info['cpu_model'] = self._get_x86_cpu_model()
        return host_info

    def swupdate(self, *name):
        try:
            swupdate = SoftwareUpdate()
        except:
            raise OperationFailed('GGBPKGUPD0004E')

        pkgs = swupdate.getNumOfUpdates()
        if pkgs == 0:
            wok_log.debug(messages['GGBPKGUPD0001E'])
            return {'message': messages['GGBPKGUPD0001E']}

        wok_log.debug('Host is going to be updated.')
        taskid = add_task('/plugins/gingerbase/host/swupdate',
                          swupdate.doUpdate,
                          self.objstore, None)
        return self.task.lookup(taskid)

    def shutdown(self, args=None):
        # Check for running vms before shutdown
        running_vms = self.get_vmlist_bystate('running')
        if len(running_vms) > 0:
            raise OperationFailed("GGBHOST0001E")

        wok_log.info('Host is going to shutdown.')
        os.system('shutdown -h now')

    def reboot(self, args=None):
        # Check for running vms before reboot
        running_vms = self.get_vmlist_bystate('running')
        if len(running_vms) > 0:
            raise OperationFailed("GGBHOST0002E")

        wok_log.info('Host is going to reboot.')
        os.system('reboot')

    def get_vmlist_bystate(self, state='running'):
        try:
            libvirt_mod = __import__('libvirt')
        except Exception, e:
            wok_log.info("Unable to import libvirt module. Details:",
                         e.message)
            # Ignore any error and assume there is no vm running in the host
            return []

        try:
            conn = libvirt_mod.open(None)
            return [dom.name().decode('utf-8')
                    for dom in conn.listAllDomains(0)
                    if (DOM_STATE_MAP[dom.info()[0]] == state)]
        except Exception, e:
            wok_log.info("Unable to get virtual machines information. "
                         "Details:", e.message)
            raise OperationFailed("GGBHOST0003E")