コード例 #1
0
ファイル: inventory_rel_3_0.py プロジェクト: 18782967131/test
    def va_inventory_get_hosts_by_datacenter(self, data_center_name):
        """
        return all hosts information according to a data center parameter
        Args:
            :dataCenterName (str): name of the datacenter

        Returns (list): all host information in the datacenter

        """
        clustered_hosts = []
        standalone_hosts = []
        params = {'datacenter': data_center_name}
        hosts_by_datacenter = self.va_rest_get_hosts_inventory(params=params)
        if isinstance(hosts_by_datacenter, dict):
            try:
                for hosts_list_cluster in hosts_by_datacenter['response'][
                        'clusters']:
                    for data in hosts_list_cluster['hosts']:
                        clustered_hosts.append(str(data['name']))
                for hosts_list in hosts_by_datacenter['response']['hosts']:
                    standalone_hosts.append(str(hosts_list['name']))
            except KeyError:
                logger.error('Error Found in Getting Hosts from REST API'
                             ',Please Check ')
                raise InvalidKey('va_inventory_get_hosts_by_datacenter')
        else:
            raise InvalidResponseFormat('va_inventory_get_hosts_by_datacenter')
        total_hosts_in_datacenter = clustered_hosts + standalone_hosts
        return total_hosts_in_datacenter
コード例 #2
0
    def __show_error_log(self, verb, url, reason, response_message):
        """

        :param verb:
        :param url:
        :param reason:
        :param response_message:
        :return:
        """
        logger.error('error sending {} to url {}'.format(verb, url))
        logger.error('reason: {}'.format(reason))
        resp_msg = None
        try:
            resp_msg = response_message.json()
        except Exception as e:
            pass

        if self.__format_console and type(
                response_message) is requests.models.Response:
            logger.error('message:\n{}'.format(pprint.pformat(resp_msg)))
        elif not self.__format_console and type(
                response_message) is requests.models.Response:
            logger.error('message:\n{}'.format(resp_msg))
        else:
            logger.error('message:\n{}'.format(response_message))
        logger.debug('----------end {} request----------\n'.format(verb))
コード例 #3
0
ファイル: inventory_rel_3_0.py プロジェクト: 18782967131/test
    def va_inventory_get_workload_information(self, host_name, port_group):
        """
        return workload information
        Args:
            :host_name (str): hostname
            :port_group (str): portgroup

        Returns (list): workload information

        """
        data_center_name = self.va_inventory_get_datacenters_by_host(host_name)
        params = {'datacenter': data_center_name}
        hosts_by_datacenter = self.va_rest_get_hosts_inventory(params=params)
        try:
            hosts_by_datacenter = hosts_by_datacenter['response']
            hosts = []
            clusters = hosts_by_datacenter['clusters']
            for cluster in clusters:
                hosts.append(cluster['hosts'])
            hosts.append(hosts_by_datacenter['hosts'])
            workloads = []
            for host in hosts:
                for h in host:
                    workloads_data = h['workloads']
                    for workload in workloads_data:
                        vnics = workload['vnics']
                        for vnic in vnics:
                            if h['name'] == host_name and vnic['pre-mseg'][
                                    'portgroup'] == port_group:
                                workloads.append(workload)
                                break
        except KeyError:
            logger.error("Error Found in Getting workload information.")
            raise InvalidKey('va_inventory_get_host_uuid')
        return workloads
コード例 #4
0
ファイル: inventory_rel_3_0.py プロジェクト: 18782967131/test
    def va_inventory_get_datacenters(self):
        """

        Returns (list): all datacenter names

        """
        datacenters = []
        params = {'datacenter': ''}
        data_centers = self.va_rest_get_inventory(params=params)
        if isinstance(data_centers, dict):
            try:
                if data_centers['status'] == 'ok':
                    datacenters_list = data_centers['response']['datacenters']
                    for item in datacenters_list:
                        datacenters.append(str(item['name']))
                else:
                    return None
            except (KeyError, ResponseFailed):
                logger.error('Error Found in Getting Datacenter ' +
                             'from REST API, Please Check')
                raise InvalidKey('va_inventory_get_datacenters')

        else:
            raise InvalidResponseFormat('va_inventory_get_datacenters')
        return datacenters
コード例 #5
0
ファイル: inventory_rel_3_0.py プロジェクト: 18782967131/test
    def va_inventory_get_host_uuid(self, host_name):
        """
        return host's uuid
        Args:
            :host_name (str): host name

        Returns (str): uuid of the host

        """
        data_center_name = self.va_inventory_get_datacenters_by_host(host_name)
        params = {'datacenter': data_center_name}
        hosts_by_datacenter = self.va_rest_get_hosts_inventory(params=params)
        if isinstance(hosts_by_datacenter, dict):
            try:
                for hosts_list_cluster in hosts_by_datacenter['response'][
                        'clusters']:
                    for data in hosts_list_cluster['hosts']:
                        if data['name'] == host_name:
                            host_uuid = data['uuid']
                            return str(host_uuid)

                for hosts_list in hosts_by_datacenter['response']['hosts']:
                    if hosts_list['name'] == host_name:
                        host_uuid = hosts_list['uuid']
                        return str(host_uuid)

            except KeyError:
                logger.error('Error Found in Getting EPi '
                             'from Hosts,Please EPi is installed on host ')
                raise InvalidKey('va_inventory_get_host_uuid')
コード例 #6
0
ファイル: inventory_rel_3_1.py プロジェクト: 18782967131/test
    def _va_message_helper(self,
                           method_name,
                           position='start',
                           result=None,
                           success=True):
        """
        print message

        :param method_name: method name
        :type method_name: str
        :param position: beginning or end of message
        :type position: str
        :param success: method runs successful or not
        :type success: bool
        """
        if position == 'start':
            logger.info('%s %s start %s' %
                        (self.STARS, method_name, self.STARS))
        else:
            if result:
                if success:
                    logger.info('%s %s returns - %s %s' %
                                (self.DOTS, method_name, result, self.DOTS))
                else:
                    logger.error('%s %s returns empty result %s' %
                                 (self.DOTS, method_name, self.DOTS))
            else:
                if success:
                    logger.info('%s %s succeeded %s' %
                                (self.DOTS, method_name, self.DOTS))
                else:
                    logger.error('%s %s failed %s' %
                                 (self.DOTS, method_name, self.DOTS))
            logger.info('%s %s finish %s' %
                        (self.STARS, method_name, self.STARS))
コード例 #7
0
ファイル: rest_api_rel_3_1.py プロジェクト: 18782967131/test
    def _va_error_message(self, method_name, reasons, show=False):
        """
        display error message

        :param method_name: method name
        :type method_name: str
        :param reasons: error message
        :type reasons: dict
        :return: error message
        :type: str
        """
        error_message = None
        if reasons and type(reasons) is str:
            error_message = 'method {} failed\nreasons {}'.format(
                method_name, reasons)
        elif reasons and 'response' in reasons.keys():
            error_message = 'method {} failed\nreasons {}'.format(
                method_name, reasons['response'])
        else:
            error_message = 'method {} failed'.format(method_name)
        if show:
            logger.error(error_message)
        return error_message
コード例 #8
0
ファイル: inventory_rel_3_0.py プロジェクト: 18782967131/test
    def va_inventory_get_datacenters_by_host(self, host_name):
        """
        return datacenter name with hostname parameter
        Args:
            :hostName (list): list of hostnames

        Returns (list): datacenter

        """
        data_center = None
        data_center_found = False
        datacenters_in_vcenter = self.va_inventory_get_datacenters()
        if datacenters_in_vcenter:
            for dc in datacenters_in_vcenter:
                if host_name in self.va_inventory_get_hosts_by_datacenter(dc):
                    data_center_found = True
                    data_center = dc
                    break
            if not data_center_found:
                logger.error('datacenter is not found for hostname {}'.format(
                    host_name))
                raise InvalidData('va_inventory_get_datacenters_by_host')
        return data_center
コード例 #9
0
ファイル: inventory_rel_3_0.py プロジェクト: 18782967131/test
    def va_inventory_get_vlan_by_portgroup(self, host_name, port_group):
        """
        return vlan information
        Args:
            :host_name (str): hostname
            :port_group (str): portgroup

        Returns (str): vlan information

        """
        data_center_name = self.va_inventory_get_datacenters_by_host(host_name)
        params = {'datacenter': data_center_name}
        hosts_by_datacenter = self.va_rest_get_hosts_inventory(params=params)
        data = dict()
        if isinstance(hosts_by_datacenter, dict):
            try:
                for hosts_list_cluster in hosts_by_datacenter['response'][
                        'clusters']:
                    for data in hosts_list_cluster['hosts']:
                        if str(data['name']) == host_name:
                            workload_list = data['workloads']
                            if workload_list is not None:
                                for workload in workload_list:
                                    for vnic in workload['vnics']:
                                        if vnic['pre-mseg'][
                                                'portgroup'] == port_group:
                                            return str(
                                                vnic['pre-mseg']['vlan'])
                            else:
                                logger.error(
                                    'Selected host {} '
                                    'has no workloads'.format(host_name))
                                raise InvalidData(
                                    'va_inventory_get_vlan_by_portgroup')
                            break

                for hosts_list in hosts_by_datacenter['response']['hosts']:
                    if str(hosts_list['name']) == host_name:
                        workload_list = data['workloads']
                        if workload_list:
                            for workload in workload_list:
                                for vnic in workload['vnics']:
                                    if vnic['pre-mseg'][
                                            'portgroup'] == port_group:
                                        return str(vnic['pre-mseg']['vlan'])
                        else:
                            logger.error(
                                'Selected host {} has no workloads'.format(
                                    host_name))
                            raise InvalidData(
                                'va_inventory_get_vlan_by_portgroup')
                        break

            except KeyError:
                logger.error(
                    'Error Found in Getting vlan from provided port group.')
                raise InvalidKey('va_inventory_get_host_uuid')
コード例 #10
0
ファイル: inventory_rel_3_0.py プロジェクト: 18782967131/test
    def va_inventory_get_epi_uuid_by_host(self, host_name):
        """
        returns epi uuid according to host name
        Args:
            :hostName (str): host name

        Returns (str): epi uuid

        """
        data_center_name = self.va_inventory_get_datacenters_by_host(host_name)
        params = {'datacenter': data_center_name}

        hosts_by_datacenter = self.va_rest_get_hosts_inventory(params=params)

        if isinstance(hosts_by_datacenter, dict):
            try:
                for hosts_list_cluster in hosts_by_datacenter['response'][
                        'clusters']:
                    for data in hosts_list_cluster['hosts']:
                        if str(data['name']) == host_name:
                            epi_list = data['epis']
                            if len(epi_list) > 1:
                                logger.error(
                                    'Host {} has multiple EPi. '
                                    'We are not supporting Multiple EPi'.
                                    formnat(host_name))
                                raise InvalidData(
                                    'va_inventory_get_epi_uuid_by_host')
                            if len(epi_list) == 0:
                                logger.error(
                                    "Host {} has no Epi, "
                                    "Please Install Epi First "
                                    "and then Microsegmentation".format(
                                        host_name))
                                raise InvalidData(
                                    'va_inventory_get_epi_uuid_by_host')
                            for epi in epi_list:
                                return str(epi['uuid'])
                            break
                for hosts_list in hosts_by_datacenter['response']['hosts']:
                    if str(hosts_list['name']) == host_name:
                        epi_list = hosts_list['epis']
                        if len(epi_list) > 1:
                            logger.error(
                                'Host {} has multiple EPi. '
                                'We are not supporting Multiple EPi'.formnat(
                                    host_name))
                            raise InvalidData(
                                'va_inventory_get_epi_uuid_by_host')
                        if len(epi_list) == 0:
                            logger.error('Host {} has no Epi, '
                                         'Please Install Epi First and then '
                                         'Microsegmentation'.format(host_name))
                            raise InvalidData(
                                'va_inventory_get_epi_uuid_by_host')
                        for epi in epi_list:
                            return str(epi['uuid'])
                        break

            except KeyError:
                logger.error('Error Found in Getting EPi from Hosts, '
                             'Please EPi is installed on host ')
                raise InvalidKey('va_inventory_get_epi_uuid_by_host')
コード例 #11
0
ファイル: varmour_3_1.py プロジェクト: 18782967131/test
    def va_reboot(self,
                  cmd=None,
                  timeout=60,
                  persistent=False,
                  reconnect_delay=100,
                  typemode='cli'):
        """
        method to perform a system reboot on cli or shell mode on a varmour vm.

        Kwargs:
            :cmd (str): command to reboot
            :timeout (int): wait time for device to come back up.
            :persistent (bool): after reboot need access to device
            :reconnect_delay (int): timeout of reconnect
            :typemode (str) : cli or shell
        """
        cli = self.cli
        cli_prompt = cli.get_prompt()
        mgt_ip = self._resource.get_mgmt_ip()

        if typemode == 'cli':
            self.va_cli()
        else:
            self.va_shell()

        self.va_log_command(cmd)

        if typemode == 'cli':
            i = 0
            while i < 5:
                try:
                    cli.exec_command(cmd,
                                     timeout=timeout,
                                     prompt=cli_prompt.sys_reboot())
                    break
                except Exception as err:
                    cli.va_exec_cli('\003')
                    logger.error(err)
                    i += 1
                    continue

            cli.exec_command('Y',
                             timeout=timeout,
                             command_output=False,
                             prompt=cli_prompt.sys_reboot_ack())
        else:
            try:
                cli.exec_command(cmd)
            except Exception as err:
                logger.info(err)

        if persistent:
            logger.debug('disconnect device')
            self.va_disconnect()
            logger.debug('Sleep 30 seconds to wait device reboot')

            max = int(reconnect_delay / 5) + 1
            time.sleep(30)

            logger.debug('Start to connect device after reboot')
            index = 1
            for i in range(1, max):
                try:
                    if platform.system() == 'Windows':
                        ping_info = os.popen('ping {} -n 2'.format(mgt_ip))
                        match_reg = 'Packets: Sent = \d+, Received = \d+, Lost = (\d+) \(\d+% loss\)'
                    elif platform.system() == 'Darwin':
                        ping_info = os.popen('ping -c 2 {}'.format(mgt_ip))
                        match_reg = '\d+ packets transmitted, \d+ packets received, (\d+)\.\d+% packet loss'
                    else:
                        ping_info = os.popen('ping {} -c 2'.format(mgt_ip))
                        match_reg = '\d+ packets transmitted, \d+ received, (\d+)% packet loss'

                    ping_content = ping_info.readlines()
                    ping_content = ''.join(ping_content)
                    loss_match = re.search(r'%s' % match_reg, ping_content,
                                           re.I | re.M)

                    ping_info.close()
                    logger.debug('Check the status of mgt interface')
                    logger.debug(ping_content)
                    if loss_match is not None and int(
                            loss_match.group(1)) == 0:
                        logger.debug('The management interface was UP')
                        logger.debug(
                            'Try to connect device on {} time'.format(index))
                        time.sleep(2)
                        self.va_init_cli(timeout=10, persistent=persistent)
                        return True
                    else:
                        log_info = 'The management interface was down. sleep 5 time,'
                        log_info += ' then try to check the interface again'
                        logger.debug(log_info)
                        time.sleep(5)
                        continue
                except Exception as err:
                    logger.error(err)
                    time.sleep(5)
                    continue

                index += 1