当前位置: 首页>>代码示例>>Python>>正文


Python VncApi.obj_to_dict方法代码示例

本文整理汇总了Python中vnc_api.vnc_api.VncApi.obj_to_dict方法的典型用法代码示例。如果您正苦于以下问题:Python VncApi.obj_to_dict方法的具体用法?Python VncApi.obj_to_dict怎么用?Python VncApi.obj_to_dict使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在vnc_api.vnc_api.VncApi的用法示例。


在下文中一共展示了VncApi.obj_to_dict方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_ztp_dhcp_config

# 需要导入模块: from vnc_api.vnc_api import VncApi [as 别名]
# 或者: from vnc_api.vnc_api.VncApi import obj_to_dict [as 别名]
    def get_ztp_dhcp_config(cls, job_ctx, fabric_uuid):
        dhcp_config = {}
        try:
            vncapi = VncApi(auth_type=VncApi._KEYSTONE_AUTHN_STRATEGY,
                            auth_token=job_ctx.get('auth_token'))
            fabric = vncapi.fabric_read(id=fabric_uuid)
            fabric_dict = vncapi.obj_to_dict(fabric)

            # From here we get the 'management' type virtual network
            vn_uuid = None
            virtual_network_refs = fabric_dict.get('virtual_network_refs') or []
            for virtual_net_ref in virtual_network_refs:
                if 'management' in virtual_net_ref['attr']['network_type']:
                    vn_uuid = virtual_net_ref['uuid']
                    break
            if vn_uuid is None:
                raise NoIdError("Cannot find mgmt virtual network on fabric")

            virtual_net = vncapi.virtual_network_read(id=vn_uuid)
            virtual_net_dict = vncapi.obj_to_dict(virtual_net)

            # Get the IPAM attached to the virtual network
            ipam_refs = virtual_net_dict.get('network_ipam_refs')
            if ipam_refs:
                ipam_ref = ipam_refs[0]
                ipam = vncapi.network_ipam_read(id=ipam_ref['uuid'])
                ipam_dict = vncapi.obj_to_dict(ipam)
                ipam_subnets = ipam_dict.get('ipam_subnets')
                if ipam_subnets:
                    dhcp_config['ipam_subnets'] = ipam_subnets.get('subnets')

            # Get static ip configuration for physical routers
            pr_refs = fabric.get_physical_router_back_refs()
            pr_uuids = [ref['uuid'] for ref in pr_refs]
            static_ips = {}
            for pr_uuid in pr_uuids:
                pr = vncapi.physical_router_read(id=pr_uuid)
                pr_dict = vncapi.obj_to_dict(pr)
                mac = pr_dict.get('physical_router_management_mac')
                ip = pr_dict.get('physical_router_management_ip')
                if mac and ip:
                    static_ips[ip] = mac
            if static_ips:
                dhcp_config['static_ips'] = static_ips
        except Exception as ex:
            logging.error("Error getting ZTP DHCP configuration: {}".format(ex))

        return dhcp_config
开发者ID:Juniper,项目名称:contrail-controller,代码行数:50,代码来源:ztp_filters.py

示例2: get_pr_subnet

# 需要导入模块: from vnc_api.vnc_api import VncApi [as 别名]
# 或者: from vnc_api.vnc_api.VncApi import obj_to_dict [as 别名]
    def get_pr_subnet(cls, job_ctx, fabric_uuid, device_fq_name):
        api = VncApi(auth_type=VncApi._KEYSTONE_AUTHN_STRATEGY,
                     auth_token=job_ctx.get('auth_token'))
        fabric = api.fabric_read(id=fabric_uuid)
        fabric_dict = api.obj_to_dict(fabric)

        vn_uuid = None
        virtual_network_refs = fabric_dict.get('virtual_network_refs') or []
        for virtual_net_ref in virtual_network_refs:
            if 'management' in virtual_net_ref['attr']['network_type']:
                vn_uuid = virtual_net_ref['uuid']
                break
        if vn_uuid is None:
            raise NoIdError("Cannot find mgmt virtual network on fabric")

        virtual_net = api.virtual_network_read(id=vn_uuid)
        virtual_net_dict = api.obj_to_dict(virtual_net)

        subnets = None
        ipam_refs = virtual_net_dict.get('network_ipam_refs')
        if ipam_refs:
            ipam_ref = ipam_refs[0]
            ipam = api.network_ipam_read(id=ipam_ref['uuid'])
            ipam_dict = api.obj_to_dict(ipam)
            ipam_subnets = ipam_dict.get('ipam_subnets')
            if ipam_subnets:
                subnets = ipam_subnets.get('subnets')

        gateway = None
        cidr = None
        if subnets:
            pr = api.physical_router_read(fq_name=device_fq_name)
            pr_dict = api.obj_to_dict(pr)
            ip = pr_dict.get('physical_router_management_ip')
            ip_addr = IPAddress(ip)
            for subnet in subnets:
                inner_subnet = subnet.get('subnet')
                cidr = inner_subnet.get('ip_prefix') + '/' + str(inner_subnet.get('ip_prefix_len'))
                if ip_addr in IPNetwork(cidr) and subnet.get('default_gateway'):
                    gateway = subnet.get('default_gateway')
                    break
        if cidr and gateway:
            return { 'cidr': cidr, 'gateway': gateway }

        raise Error("Cannot find cidr and gateway for device: %s" % str(device_fq_name))
开发者ID:Juniper,项目名称:contrail-controller,代码行数:47,代码来源:physical_router_filters.py

示例3: get_ztp_config

# 需要导入模块: from vnc_api.vnc_api import VncApi [as 别名]
# 或者: from vnc_api.vnc_api.VncApi import obj_to_dict [as 别名]
    def get_ztp_config(cls, job_ctx, fabric_uuid):
        ztp_config = {}
        try:
            vncapi = VncApi(auth_type=VncApi._KEYSTONE_AUTHN_STRATEGY,
                            auth_token=job_ctx.get('auth_token'))
            fabric = vncapi.fabric_read(id=fabric_uuid)
            fabric_dict = vncapi.obj_to_dict(fabric)
            fabric_creds = fabric_dict.get('fabric_credentials')
            if fabric_creds:
                device_creds = fabric_creds.get('device_credential')
                if device_creds:
                    dev_cred = device_creds[0]
                    ztp_config['password'] = dev_cred['credential']['password']

            # From here we get the 'management' type virtual network
            vn_uuid = None
            virtual_network_refs = fabric_dict.get('virtual_network_refs') or []
            for virtual_net_ref in virtual_network_refs:
                if "management" in virtual_net_ref['attr']['network_type']:
                    vn_uuid = virtual_net_ref['uuid']
                    break
            if vn_uuid is None:
                raise NoIdError("Cannot find mgmt virtual network on fabric")

            virtual_net = vncapi.virtual_network_read(id=vn_uuid)
            virtual_net_dict = vncapi.obj_to_dict(virtual_net)

            # Get the IPAM attached to the virtual network
            ipam_refs = virtual_net_dict.get('network_ipam_refs')
            if ipam_refs:
                ipam_ref = ipam_refs[0]
                ipam = vncapi.network_ipam_read(id=ipam_ref['uuid'])
                ipam_dict = vncapi.obj_to_dict(ipam)
                ipam_subnets = ipam_dict.get('ipam_subnets')
                if ipam_subnets:
                    ztp_config['ipam_subnets'] = ipam_subnets.get('subnets')
        except NoIdError:
            logging.error("Cannot find mgmt virtual network")
        except Exception as ex:
            logging.error("Error getting ZTP configuration: {}".format(ex))

        return ztp_config
开发者ID:rombie,项目名称:contrail-controller,代码行数:44,代码来源:ztp_filters.py

示例4: get_ztp_tftp_config

# 需要导入模块: from vnc_api.vnc_api import VncApi [as 别名]
# 或者: from vnc_api.vnc_api.VncApi import obj_to_dict [as 别名]
    def get_ztp_tftp_config(cls, job_ctx, fabric_uuid):
        tftp_config = {}
        try:
            vncapi = VncApi(auth_type=VncApi._KEYSTONE_AUTHN_STRATEGY,
                            auth_token=job_ctx.get('auth_token'))
            fabric = vncapi.fabric_read(id=fabric_uuid)
            fabric_dict = vncapi.obj_to_dict(fabric)
            fabric_creds = fabric_dict.get('fabric_credentials')
            if fabric_creds:
                device_creds = fabric_creds.get('device_credential')
                if device_creds:
                    dev_cred = device_creds[0]
                    password = JobVncApi.decrypt_password(
                        encrypted_password=dev_cred['credential']['password'],
                        admin_password=job_ctx.get(
                            'vnc_api_init_params').get(
                            'admin_password'))
                    tftp_config['password'] = password
        except Exception as ex:
            logging.error("Error getting ZTP TFTP configuration: {}".format(ex))

        return tftp_config
开发者ID:Juniper,项目名称:contrail-controller,代码行数:24,代码来源:ztp_filters.py

示例5: SanityBase

# 需要导入模块: from vnc_api.vnc_api import VncApi [as 别名]
# 或者: from vnc_api.vnc_api.VncApi import obj_to_dict [as 别名]
class SanityBase(object):
    """Base class for fabric ansible sanity tests"""

    @staticmethod
    def _init_logging(cfg, name):
        logger = logging.getLogger('sanity_test')
        logger.setLevel(cfg['level'])

        file_handler = logging.FileHandler(
            '%s/fabric_ansibile_%s.log' % (cfg['file']['dir'], name), mode='w')
        file_handler.setLevel(cfg['file']['level'])
        console_handler = logging.StreamHandler()
        console_handler.setLevel(cfg['console'])

        formatter = logging.Formatter(
            '%(asctime)s %(levelname)-8s %(message)s',
            datefmt='%Y/%m/%d %H:%M:%S')
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)

        return logger
    # end _init_logging

    def test(self):
        """Override this method in the derived class"""
        pass

    def __init__(self, cfg, name):
        if cfg is None:
            raise KeyError("Missing required args: cfg")
        if name is None:
            raise KeyError("Missing required args: name")

        self._name = name
        self._timeout = cfg['wait_for_job']['timeout']
        self._max_retries = cfg['wait_for_job']['max_retries']
        self._logger = SanityBase._init_logging(cfg['log'], name)
        self._api_server = cfg['api_server']
        self._analytics = cfg['analytics']
        self._api = VncApi(
            api_server_host=self._api_server['host'],
            api_server_port=self._api_server['port'],
            username=self._api_server['username'],
            password=self._api_server['password'],
            tenant_name=self._api_server['tenant'])
    # end __init__

    def create_fabric(self, fab_name, prouter_passwords):
        """create fabric with list of device passwords"""
        self._logger.info('Creating fabric: %s', fab_name)
        fq_name = ['default-global-system-config', fab_name]
        fab = Fabric(
            name=fab_name,
            fq_name=fq_name,
            parent_type='global-system-config',
            fabric_credentials={
                'device_credential': [{
                    'credential': {
                        'username': 'root', 'password': passwd
                    },
                    'vendor': 'Juniper',
                    'device_family': None
                } for passwd in prouter_passwords]
            }
        )
        try:
            fab_uuid = self._api.fabric_create(fab)
            fab = self._api.fabric_read(id=fab_uuid)
        except RefsExistError:
            self._logger.warn("Fabric '%s' already exists", fab_name)
            fab = self._api.fabric_read(fq_name=fq_name)

        self._logger.debug(
            "Fabric created:\n%s",
            pprint.pformat(self._api.obj_to_dict(fab), indent=4))
        return fab
    # end _create_fabric

    def add_mgmt_ip_namespace(self, fab, name, cidrs):
        """add management ip prefixes as fabric namespace"""
        ns_name = 'mgmt_ip-' + name
        self._logger.info(
            'Adding management ip namespace "%s" to fabric "%s" ...',
            ns_name, fab.name)

        subnets = []
        for cidr in cidrs:
            ip_prefix = cidr.split('/')
            subnets.append({
                'ip_prefix': ip_prefix[0],
                'ip_prefix_len': ip_prefix[1]
            })
        ns_fq_name = fab.fq_name + [ns_name]
        namespace = FabricNamespace(
            name=ns_name,
            fq_name=ns_fq_name,
            parent_type='fabric',
            fabric_namespace_type='IPV4-CIDR',
#.........这里部分代码省略.........
开发者ID:Juniper,项目名称:contrail-controller,代码行数:103,代码来源:sanity_base.py

示例6: DeviceInfo

# 需要导入模块: from vnc_api.vnc_api import VncApi [as 别名]
# 或者: from vnc_api.vnc_api.VncApi import obj_to_dict [as 别名]
class DeviceInfo(object):
    output = {}

    def __init__(self, module):
        self.module = module
        self.logger = module.logger
        self.job_ctx = module.job_ctx
        self.fabric_uuid = module.params['fabric_uuid']
        self.total_retry_timeout = float(module.params['total_retry_timeout'])
        self._job_file_write = JobFileWrite(self.logger)

    def initial_processing(self, concurrent):
        self.serial_num_flag = False
        self.all_serial_num = []
        serial_num = []
        self.per_greenlet_percentage = None

        self.job_ctx['current_task_index'] = 2

        try:
            total_percent = self.job_ctx.get('playbook_job_percentage')
            if total_percent:
                total_percent = float(total_percent)

            # Calculate the total percentage of this entire greenlet based task
            # This will be equal to the percentage alloted to this task in the
            # weightage array off the total job percentage. For example:
            # if the task weightage array is [10, 85, 5] and total job %
            # is 95. Then the 2nd task's effective total percentage is 85% of
            # 95%
            total_task_percentage = self.module.calculate_job_percentage(
                self.job_ctx.get('total_task_count'),
                task_seq_number=self.job_ctx.get('current_task_index'),
                total_percent=total_percent,
                task_weightage_array=self.job_ctx.get(
                    'task_weightage_array'))[0]

            # Based on the number of greenlets spawned (i.e num of sub tasks)
            # split the total_task_percentage equally amongst the greenlets.
            self.logger.info("Number of greenlets: {} and total_percent: "
                             "{}".format(concurrent, total_task_percentage))
            self.per_greenlet_percentage = \
                self.module.calculate_job_percentage(
                    concurrent, total_percent=total_task_percentage)[0]
            self.logger.info("Per greenlet percent: "
                             "{}".format(self.per_greenlet_percentage))

            self.vncapi = VncApi(auth_type=VncApi._KEYSTONE_AUTHN_STRATEGY,
                                 auth_token=self.job_ctx.get('auth_token'))
        except Exception as ex:
            self.logger.info("Percentage calculation failed with error "
                             "{}".format(str(ex)))

        try:
            self.vncapi = VncApi(auth_type=VncApi._KEYSTONE_AUTHN_STRATEGY,
                                 auth_token=self.job_ctx.get('auth_token'))
        except Exception as ex:
            self.module.results['failed'] = True
            self.module.results['msg'] = "Failed to connect to API server " \
                "due to error: %s"\
                % str(ex)
            self.module.exit_json(**self.module.results)

        # get credentials and serial number if greenfield
        if self.total_retry_timeout:
            # get device credentials
            fabric = self.vncapi.fabric_read(id=self.fabric_uuid)
            fabric_object = self.vncapi.obj_to_dict(fabric)
            self.credentials = fabric_object.get('fabric_credentials').get(
                'device_credential')

            # get serial numbers
            fabric_namespace_obj_list = self.vncapi.fabric_namespaces_list(
                parent_id=self.fabric_uuid, detail=True)
            fabric_namespace_list = self.vncapi.obj_to_dict(
                fabric_namespace_obj_list)

            for namespace in fabric_namespace_list:
                if namespace.get('fabric_namespace_type') == "SERIAL_NUM":
                    self.serial_num_flag = True
                    serial_num.append(namespace.get(
                        'fabric_namespace_value').get('serial_num'))

            if len(serial_num) > 1:
                for outer_list in serial_num:
                    for sn in outer_list:
                        self.all_serial_num.append(sn)

        else:
            self.credentials = self.module.params['credentials']

        for cred in self.credentials:
            if cred.get('credential', {}).get('password'):
                cred['credential']['password'] = JobVncApi.decrypt_password(
                    encrypted_password=cred.get('credential', {}).get('password'),
                    admin_password=self.job_ctx.get('vnc_api_init_params').get(
                        'admin_password'))

    def ping_sweep(self, host):
        try:
#.........这里部分代码省略.........
开发者ID:Juniper,项目名称:contrail-controller,代码行数:103,代码来源:device_info.py


注:本文中的vnc_api.vnc_api.VncApi.obj_to_dict方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。