Пример #1
0
def list_disks(ctx):
    try:
        restore_session(ctx, vdc_required=True)
        client = ctx.obj['client']
        vdc_href = ctx.obj['profiles'].get('vdc_href')
        vdc = VDC(client, href=vdc_href)
        disks = vdc.get_disks()
        result = []
        for disk in disks:
            attached_vms = ''
            if hasattr(disk, 'attached_vms') and \
               hasattr(disk.attached_vms, 'VmReference'):
                attached_vms = disk.attached_vms.VmReference.get('name')
            result.append({
                'name':
                disk.get('name'),
                'id':
                extract_id(disk.get('id')),
                'owner':
                disk.Owner.User.get('name'),
                'size':
                humanfriendly.format_size(int(disk.get('size'))),
                'size_bytes':
                disk.get('size'),
                'status':
                VCLOUD_STATUS_MAP.get(int(disk.get('status'))),
                'vms_attached':
                attached_vms
            })
        stdout(result, ctx, show_id=True)
    except Exception as e:
        stderr(e, ctx)
Пример #2
0
 def get_cluster_info(self, name, headers, body):
     result = {}
     try:
         result['body'] = []
         result['status_code'] = OK
         self._connect_tenant(headers)
         clusters = load_from_metadata(self.client_tenant, name=name)
         if len(clusters) == 0:
             raise Exception('Cluster \'%s\' not found.' % name)
         vapp = VApp(self.client_tenant, href=clusters[0]['vapp_href'])
         vms = vapp.get_all_vms()
         for vm in vms:
             node_info = {
                 'name': vm.get('name'),
                 'numberOfCpus': vm.VmSpecSection.NumCpus.text,
                 'memoryMB':
                 vm.VmSpecSection.MemoryResourceMb.Configured.text,
                 'status': VCLOUD_STATUS_MAP.get(int(vm.get('status'))),
                 'ipAddress': vapp.get_primary_ip(vm.get('name'))
             }
             if vm.get('name').startswith(TYPE_MASTER):
                 node_info['node_type'] = 'master'
                 clusters[0].get('master_nodes').append(node_info)
             elif vm.get('name').startswith(TYPE_NODE):
                 node_info['node_type'] = 'node'
                 clusters[0].get('nodes').append(node_info)
         result['body'] = clusters[0]
     except Exception as e:
         LOGGER.error(traceback.format_exc())
         result['body'] = []
         result['status_code'] = INTERNAL_SERVER_ERROR
         result['message'] = str(e)
     return result
Пример #3
0
def list_disks(ctx):
    try:
        client = ctx.obj['client']
        vdc_href = ctx.obj['profiles'].get('vdc_href')
        vdc = VDC(client, href=vdc_href)
        disks = vdc.get_disks()
        result = []
        for disk in disks:
            attached_vms = ''
            if hasattr(disk, 'attached_vms') and \
               hasattr(disk.attached_vms, 'VmReference'):
                attached_vms = disk.attached_vms.VmReference.get('name')
            result.append({
                'name':
                disk.get('name'),
                'id':
                extract_id(disk.get('id')),
                'owner':
                disk.Owner.User.get('name'),
                'size':
                humanfriendly.format_size(int(disk.get('size'))),
                'size_bytes':
                disk.get('size'),
                'status':
                VCLOUD_STATUS_MAP.get(int(disk.get('status'))),
                'vms_attached':
                attached_vms
            })
        stdout(result, ctx, show_id=True)
    except Exception as e:
        stderr(e, ctx)
    def get_node_info(self, cluster_name, node_name):
        """Get the info of a given node in the cluster.

        :param cluster_name: (str): Name of the cluster
        :param node_name: (str): Name of the node

        :return: (dict): Info of the node.
        """
        self._connect_tenant()
        clusters = load_from_metadata(
            self.tenant_client,
            name=cluster_name,
            org_name=self.req_spec.get(RequestKey.ORG_NAME),
            vdc_name=self.req_spec.get(RequestKey.OVDC_NAME))
        if len(clusters) > 1:
            raise CseDuplicateClusterError(f"Multiple clusters of name"
                                           f" '{cluster_name}' detected.")
        if len(clusters) == 0:
            raise ClusterNotFoundError(f"Cluster '{cluster_name}' not found.")

        vapp = VApp(self.tenant_client, href=clusters[0]['vapp_href'])
        vms = vapp.get_all_vms()
        node_info = None
        for vm in vms:
            if (node_name == vm.get('name')):
                node_info = {
                    'name': vm.get('name'),
                    'numberOfCpus': '',
                    'memoryMB': '',
                    'status': VCLOUD_STATUS_MAP.get(int(vm.get('status'))),
                    'ipAddress': ''
                }
                if hasattr(vm, 'VmSpecSection'):
                    node_info[
                        'numberOfCpus'] = vm.VmSpecSection.NumCpus.text
                    node_info[
                        'memoryMB'] = \
                        vm.VmSpecSection.MemoryResourceMb.Configured.text
                try:
                    node_info['ipAddress'] = vapp.get_primary_ip(
                        vm.get('name'))
                except Exception:
                    LOGGER.debug(f"Unable to get ip address of node "
                                 f"{vm.get('name')}")
                if vm.get('name').startswith(NodeType.MASTER):
                    node_info['node_type'] = 'master'
                elif vm.get('name').startswith(NodeType.WORKER):
                    node_info['node_type'] = 'worker'
                elif vm.get('name').startswith(NodeType.NFS):
                    node_info['node_type'] = 'nfs'
                    exports = self._get_nfs_exports(node_info['ipAddress'],
                                                    vapp,
                                                    vm)
                    node_info['exports'] = exports
        if node_info is None:
            raise NodeNotFoundError(f"Node '{node_name}' not found in "
                                    f"cluster '{cluster_name}'")
        return node_info
    def get_node_info(self, data):
        """Get node metadata as dictionary.

        Required data: cluster_name, node_name
        Optional data and default values: org_name=None, ovdc_name=None
        """
        required = [
            RequestKey.CLUSTER_NAME,
            RequestKey.NODE_NAME
        ]
        utils.ensure_keys_in_dict(required, data, dict_name='data')
        defaults = {
            RequestKey.ORG_NAME: None,
            RequestKey.OVDC_NAME: None
        }
        validated_data = {**defaults, **data}
        cluster_name = validated_data[RequestKey.CLUSTER_NAME]
        node_name = validated_data[RequestKey.NODE_NAME]

        cluster = get_cluster(self.tenant_client, cluster_name,
                              org_name=validated_data[RequestKey.ORG_NAME],
                              ovdc_name=validated_data[RequestKey.OVDC_NAME])

        vapp = VApp(self.tenant_client, href=cluster['vapp_href'])
        vms = vapp.get_all_vms()
        node_info = None
        for vm in vms:
            vm_name = vm.get('name')
            if node_name != vm_name:
                continue

            node_info = {
                'name': vm_name,
                'numberOfCpus': '',
                'memoryMB': '',
                'status': VCLOUD_STATUS_MAP.get(int(vm.get('status'))),
                'ipAddress': ''
            }
            if hasattr(vm, 'VmSpecSection'):
                node_info['numberOfCpus'] = vm.VmSpecSection.NumCpus.text
                node_info['memoryMB'] = vm.VmSpecSection.MemoryResourceMb.Configured.text # noqa: E501
            try:
                node_info['ipAddress'] = vapp.get_primary_ip(vm_name)
            except Exception:
                LOGGER.debug(f"Unable to get ip address of node {vm_name}")
            if vm_name.startswith(NodeType.MASTER):
                node_info['node_type'] = 'master'
            elif vm_name.startswith(NodeType.WORKER):
                node_info['node_type'] = 'worker'
            elif vm_name.startswith(NodeType.NFS):
                node_info['node_type'] = 'nfs'
                node_info['exports'] = self._get_nfs_exports(node_info['ipAddress'], vapp, vm_name) # noqa: E501
        if node_info is None:
            raise NodeNotFoundError(f"Node '{node_name}' not found in "
                                    f"cluster '{cluster_name}'")
        return node_info
    def get_node_info(self, cluster_name, node_name, headers):
        """Get the info of a given node in the cluster.

        :param cluster_name: (str): Name of the cluster
        :param node_name: (str): Name of the node
        :param headers: (str): Request headers

        :return: (dict): Info of the node.
        """
        result = {}

        result['body'] = []
        result['status_code'] = OK
        self._connect_tenant(headers)
        clusters = load_from_metadata(self.client_tenant, name=cluster_name)
        if len(clusters) == 0:
            raise CseServerError('Cluster \'%s\' not found.' % cluster_name)
        vapp = VApp(self.client_tenant, href=clusters[0]['vapp_href'])
        vms = vapp.get_all_vms()
        node_info = None
        for vm in vms:
            if (node_name == vm.get('name')):
                node_info = {
                    'name': vm.get('name'),
                    'numberOfCpus': '',
                    'memoryMB': '',
                    'status': VCLOUD_STATUS_MAP.get(int(vm.get('status'))),
                    'ipAddress': ''
                }
                if hasattr(vm, 'VmSpecSection'):
                    node_info['numberOfCpus'] = vm.VmSpecSection.NumCpus.text
                    node_info[
                        'memoryMB'] = \
                        vm.VmSpecSection.MemoryResourceMb.Configured.text
                try:
                    node_info['ipAddress'] = vapp.get_primary_ip(
                        vm.get('name'))
                except Exception:
                    LOGGER.debug('cannot get ip address '
                                 'for node %s' % vm.get('name'))
                if vm.get('name').startswith(TYPE_MASTER):
                    node_info['node_type'] = 'master'
                elif vm.get('name').startswith(TYPE_NODE):
                    node_info['node_type'] = 'node'
                elif vm.get('name').startswith(TYPE_NFS):
                    node_info['node_type'] = 'nfsd'
                    exports = self._get_nfs_exports(node_info['ipAddress'],
                                                    vapp, vm)
                    node_info['exports'] = exports
        if node_info is None:
            raise CseServerError('Node \'%s\' not found in cluster \'%s\'' %
                                 (node_name, cluster_name))
        result['body'] = node_info
        return result
Пример #7
0
def find_vm_in_vapp(ctx, vm_name=None, vm_id=None):
    result = []
    try:
        resource_type = 'vApp'
        query = ctx.client.get_typed_query(
            resource_type, query_result_format=QueryResultFormat.ID_RECORDS)
        records = list(query.execute())
        vdc_resource = ctx.vdc.get_resource()
        vdc_id = vdc_resource.get('id')
        vdc_name = vdc_resource.get('name')
        for curr_vapp in records:
            vapp_vdc = curr_vapp.get('vdc')
            if vdc_id != vapp_vdc:
                continue
            vapp_id = curr_vapp.get('id')
            vapp_name = curr_vapp.get('name')
            vapp_href = curr_vapp.get('href')
            the_vapp = ctx.vdc.get_vapp(vapp_name)
            for vm in the_vapp.Children.Vm:
                if vm.get('name') == vm_name or \
                        extract_id(vm.get('id')) == vm_id:
                    result.append({
                        'vdc':
                        extract_id(vapp_vdc),
                        'vdc_name':
                        vdc_name,
                        'vapp':
                        extract_id(vapp_id),
                        'vapp_name':
                        vapp_name,
                        'vm':
                        extract_id(vm.get('id')),
                        'vm_name':
                        vm.get('name'),
                        'vm_href':
                        vm.get('href'),
                        'status':
                        VCLOUD_STATUS_MAP.get(int(vm.get('status')))
                    })
                    break
        # Refresh session after Typed Query
        Client.login(session_id=ctx.token)
    except Exception as e:
        if ctx.config['debug'] == True:
            raise
        else:
            pass
    return result
Пример #8
0
def list_disks(ctx):
    try:
        client = ctx.obj['client']
        vdc_href = ctx.obj['profiles'].get('vdc_href')
        vdc = VDC(client, href=vdc_href)
        disks = vdc.get_disks()
        result = []
        for disk in disks:
            result.append({
                'name':
                disk.get('name'),
                'id':
                extract_id(disk.get('id')),
                'size_MB':
                disk.get('size'),
                'status':
                VCLOUD_STATUS_MAP.get(int(disk.get('status')))
            })
        stdout(result, ctx, show_id=True)
    except Exception as e:
        stderr(e, ctx)
Пример #9
0
def get_disks(ctx):
    result = []
    attached_vm = \
        lambda x, disk: next((i['vm'] for i in x if i['disk'] == disk), None)
    try:
        disks = ctx.vdc.get_disks()
        disks_relation = get_vm_disk_relation(ctx)
        for disk in disks:
            disk_id = extract_id(disk.get('id'))
            result.append({
                'name':
                disk.get('name'),
                'id':
                disk_id,
                'href':
                disk.get('href'),
                'bus_type':
                int(disk.get('busType')),
                'bus_sub_type':
                disk.get('busSubType'),
                'size_bytes':
                int(disk.get('size')),
                'size_human':
                bytes_to_size(int(disk.get('size'))),
                'status':
                VCLOUD_STATUS_MAP.get(int(disk.get('status'))),
                'attached_vm':
                attached_vm(disks_relation, disk_id),
                'vdc':
                extract_id(ctx.vdc.resource.get('id'))
            })
        # Refresh session after Typed Query
        Client.login(session_id=ctx.token)
    except Exception as e:
        if ctx.config['debug'] == True:
            raise
        else:
            pass
    return result
Пример #10
0
def get_disks(ctx):
    result = []
    try:
        disks = ctx.vdc.get_disks()
        for disk in disks:
            disk_id = extract_id(disk.get('id'))
            attached_vm = None
            attached_vm_href = None
            if hasattr(disk, 'attached_vms') and hasattr(disk.attached_vms, 'VmReference'):
                attached_vm = disk.attached_vms.VmReference.get('name')
                attached_vm_href = disk.attached_vms.VmReference.get('href')
            result.append(
                {
                    'name': disk.get('name'),
                    'id': disk_id,
                    'href': disk.get('href'),
                    'storage_profile': disk.StorageProfile.get('name'),
                    'storage_profile_href': disk.StorageProfile.get('href'),
                    'bus_type': int(disk.get('busType')),
                    'bus_sub_type': disk.get('busSubType'),
                    'size_bytes': int(disk.get('size')),
                    'size_human': bytes_to_size(
                            int(disk.get('size'))
                    ),
                    'status': VCLOUD_STATUS_MAP.get(int(disk.get('status'))),
                    'attached_vm': attached_vm,
                    'attached_vm_href': attached_vm_href,
                    'vdc': extract_id(ctx.vdc.resource.get('id'))
                }

            )
    except Exception as e:
        if ctx.config['debug'] == True:
            raise
        else:
            pass
    return result
Пример #11
0
def vapp_to_dict(vapp, metadata=None, access_control_settings=None):
    """Converts a lxml.objectify.ObjectifiedElement vApp object to a dict.

    :param lxml.objectify.ObjectifiedElement vapp: an object containing
        EntityType.VAPP XML data.
    :param lxml.objectify.ObjectifiedElement access_control_settings: an object
        containing EntityType.CONTROL_ACCESS_PARAMS XML data.

    :return: dictionary representation of vApp object.

    :rtype: dict
    """
    result = {}
    result['name'] = vapp.get('name')
    if hasattr(vapp, 'Description'):
        result['description'] = str('%s' % vapp.Description)
    result['id'] = extract_id(vapp.get('id'))
    if 'ownerName' in vapp:
        result['owner'] = [vapp.get('ownerName')]
    if hasattr(vapp, 'Owner') and hasattr(vapp.Owner, 'User'):
        result['owner'] = []
        for user in vapp.Owner.User:
            result['owner'].append(user.get('name'))
    items = vapp.xpath('//ovf:NetworkSection/ovf:Network', namespaces=NSMAP)
    n = 0
    for item in items:
        n += 1
        network_name = item.get('{' + NSMAP['ovf'] + '}name')
        result['vapp-net-%s' % n] = network_name
        if hasattr(vapp, 'NetworkConfigSection'):
            for nc in vapp.NetworkConfigSection.NetworkConfig:
                if nc.get('networkName') == network_name:
                    result['vapp-net-%s-mode' % n] = \
                        nc.Configuration.FenceMode.text
    if hasattr(vapp, 'LeaseSettingsSection'):
        if hasattr(vapp.LeaseSettingsSection, 'DeploymentLeaseInSeconds'):
            result['deployment_lease'] = to_human(
                int(vapp.LeaseSettingsSection.DeploymentLeaseInSeconds))
        if hasattr(vapp.LeaseSettingsSection, 'StorageLeaseInSeconds'):
            result['storage_lease'] = to_human(
                int(vapp.LeaseSettingsSection.StorageLeaseInSeconds))
        if hasattr(vapp.LeaseSettingsSection, 'DeploymentLeaseExpiration'):
            result['deployment_lease_expiration'] = \
                vapp.LeaseSettingsSection.DeploymentLeaseExpiration
    if hasattr(vapp, 'Children') and hasattr(vapp.Children, 'Vm'):
        n = 0
        for vm in vapp.Children.Vm:
            n += 1
            k = 'vm-%s' % n
            result[k + ': name'] = vm.get('name')
            items = vm.xpath('ovf:VirtualHardwareSection/ovf:Item',
                             namespaces=NSMAP)
            for item in items:
                element_name = item.find('rasd:ElementName', NSMAP)
                connection = item.find('rasd:Connection', NSMAP)
                if connection is None:
                    quantity = item.find('rasd:VirtualQuantity', NSMAP)
                    if quantity is None or isinstance(quantity, NoneElement):
                        value = item.find('rasd:Description', NSMAP)
                    else:
                        units = item.find('rasd:VirtualQuantityUnits', NSMAP)
                        if isinstance(units, NoneElement):
                            units = ''
                        value = '{:,} {}'.format(int(quantity), units).strip()
                else:
                    value = '{}: {}'.format(
                        connection.get('{' + NSMAP['vcloud'] +
                                       '}ipAddressingMode'),
                        connection.get('{' + NSMAP['vcloud'] + '}ipAddress'))
                result['%s: %s' % (k, element_name)] = value
            env = vm.xpath('ovfenv:Environment', namespaces=NSMAP)
            if len(env) > 0:
                result['%s: %s' % (k, 'moid')] = env[0].get('{' + NSMAP['ve'] +
                                                            '}vCenterId')
            if hasattr(vm, 'StorageProfile'):
                result['%s: %s' % (k, 'storage-profile')] = \
                    vm.StorageProfile.get('name')
            if hasattr(vm, 'GuestCustomizationSection'):
                if hasattr(vm.GuestCustomizationSection, 'AdminPassword'):
                    element_name = 'password'
                    value = vm.GuestCustomizationSection.AdminPassword
                    result['%s: %s' % (k, element_name)] = value
                if hasattr(vm.GuestCustomizationSection, 'ComputerName'):
                    element_name = 'computer-name'
                    value = vm.GuestCustomizationSection.ComputerName
                    result['%s: %s' % (k, element_name)] = value
            if hasattr(vm, 'NetworkConnectionSection'):
                ncs = vm.NetworkConnectionSection
                if 'PrimaryNetworkConnectionIndex' in ncs:
                    result['%s: %s' % (k, 'primary-net')] = \
                        ncs.PrimaryNetworkConnectionIndex.text
                if 'NetworkConnection' in ncs:
                    for nc in ncs.NetworkConnection:
                        nci = nc.NetworkConnectionIndex.text
                        result['%s: net-%s' % (k, nci)] = nc.get('network')
                        result['%s: net-%s-mode' % (k, nci)] = \
                            nc.IpAddressAllocationMode.text
                        result['%s: net-%s-connected' % (k, nci)] = \
                            nc.IsConnected.text
                        if hasattr(nc, 'MACAddress'):
                            result['%s: net-%s-mac' % (k, nci)] = \
                                nc.MACAddress.text
                        if hasattr(nc, 'IpAddress'):
                            result['%s: net-%s-ip' %
                                   (k, nci)] = nc.IpAddress.text
            if 'VmSpecSection' in vm:
                for setting in vm.VmSpecSection.DiskSection.DiskSettings:
                    if hasattr(setting, 'Disk'):
                        result['%s: attached-disk-%s-name' %
                               (k, setting.DiskId.text)] = \
                            '%s' % (setting.Disk.get('name'))
                        result['%s: attached-disk-%s-size-Mb' %
                               (k, setting.DiskId.text)] = \
                            '%s' % (setting.SizeMb.text)
                        result['%s: attached-disk-%s-bus' %
                               (k, setting.DiskId.text)] = \
                            '%s' % (setting.BusNumber.text)
                        result['%s: attached-disk-%s-unit' %
                               (k, setting.DiskId.text)] = \
                            '%s' % (setting.UnitNumber.text)

    result['status'] = VCLOUD_STATUS_MAP.get(int(vapp.get('status')))
    if access_control_settings is not None:
        result.update(access_control_settings)
    if metadata is not None and hasattr(metadata, 'MetadataEntry'):
        for me in metadata.MetadataEntry:
            result['metadata: %s' % me.Key.text] = me.TypedValue.Value.text
    return result
Пример #12
0
def vm_to_dict(vm):
    """Converts a lxml.objectify.ObjectifiedElement VM object to a dict.

    :param lxml.objectify.ObjectifiedElement vm: an object containing
        EntityType.VM XML data.

    :return: dictionary representation of vApp object.

    :rtype: dict
    """
    result = {}
    result['name'] = vm.get('name')
    if hasattr(vm, 'Description'):
        result['description'] = vm.Description.text
    result['id'] = vm.get('id')

    result['deployed'] = vm.get('deployed')
    result['status'] = VCLOUD_STATUS_MAP.get(int(vm.get('status')))
    result['needs-customization'] = vm.get('needsCustomization')
    if hasattr(vm, 'VCloudExtension'):
        result['moref'] = vm.VCloudExtension[
            '{' + NSMAP['vmext'] + '}VmVimInfo'][
                '{' + NSMAP['vmext'] + '}VmVimObjectRef']['{' + NSMAP['vmext']
                                                          + '}MoRef'].text
    result['computer-name'] = vm.GuestCustomizationSection.ComputerName.text

    disk_instance_name_map = {}
    nic_instance_name_map = {}
    for item in vm['{' + NSMAP['ovf'] +
                   '}VirtualHardwareSection']['{' + NSMAP['ovf'] + '}Item']:
        if item['{' + NSMAP['rasd'] + '}ResourceType'].text == str(10):
            nic_instance_name_map[item[
                '{' + NSMAP['rasd'] + '}AddressOnParent'].text] = item[
                    '{' + NSMAP['rasd'] + '}ElementName'].text
        if item['{' + NSMAP['rasd'] + '}ResourceType'].text == str(17):
            disk_instance_name_map[item['{' + NSMAP['rasd'] + '}InstanceID'].
                                   text] = item['{' + NSMAP['rasd'] +
                                                '}ElementName'].text

    if hasattr(vm, 'NetworkConnectionSection'):
        ncs = vm.NetworkConnectionSection
        if hasattr(ncs, 'PrimaryNetworkConnectionIndex'):
            idx = ncs.PrimaryNetworkConnectionIndex.text
            result['primary-nic'] = 'nic-' + idx
        if hasattr(ncs, 'NetworkConnection'):
            for nc in ncs.NetworkConnection:
                nci = nc.NetworkConnectionIndex.text
                nic_props = {}
                result['nic-' + nci] = nic_props
                nic_props['name'] = nic_instance_name_map[nci]
                nic_props['network'] = nc.get('network')
                nic_props['mode'] = nc.IpAddressAllocationMode.text
                nic_props['connected'] = nc.IsConnected.text
                if hasattr(nc, 'MACAddress'):
                    nic_props['mac'] = nc.MACAddress.text
                if hasattr(nc, 'IpAddress'):
                    nic_props['ip'] = nc.IpAddress.text

    if hasattr(vm, 'VmSpecSection'):
        result['vm-tools-version'] = vm.VmSpecSection.VmToolsVersion.text
        result['os'] = vm.VmSpecSection.OsType.text
        result['cpu'] = vm.VmSpecSection.NumCpus.text
        result['cores-per-socket'] = vm.VmSpecSection.NumCoresPerSocket.text
        result['memory-MB'] = vm.VmSpecSection.MemoryResourceMb.Configured.text
        for setting in vm.VmSpecSection.DiskSection.DiskSettings:
            disk_props = {}
            result['disk-' + setting.DiskId.text] = disk_props
            disk_props['name'] = disk_instance_name_map[setting.DiskId.text]
            disk_props['size-MB'] = setting.SizeMb.text
            disk_props['bus'] = setting.BusNumber.text
            disk_props['unit'] = setting.UnitNumber.text

    return result
Пример #13
0
def vapp_to_dict(vapp, metadata=None, access_control_settings=None):
    """Converts a lxml.objectify.ObjectifiedElement vApp object to a dict.

    :param lxml.objectify.ObjectifiedElement vapp: an object containing
        EntityType.VAPP XML data.
    :param lxml.objectify.ObjectifiedElement access_control_settings: an object
        containing EntityType.CONTROL_ACCESS_PARAMS XML data.

    :return: dictionary representation of vApp object.

    :rtype: dict
    """
    result = {}
    result['name'] = vapp.get('name')
    if hasattr(vapp, 'Description'):
        result['description'] = str('%s' % vapp.Description)
    result['id'] = extract_id(vapp.get('id'))
    if 'ownerName' in vapp:
        result['owner'] = [vapp.get('ownerName')]
    if hasattr(vapp, 'Owner') and hasattr(vapp.Owner, 'User'):
        result['owner'] = []
        for user in vapp.Owner.User:
            result['owner'].append(user.get('name'))
    items = vapp.xpath('//ovf:NetworkSection/ovf:Network', namespaces=NSMAP)
    n = 0
    for item in items:
        n += 1
        network_name = item.get('{' + NSMAP['ovf'] + '}name')
        result['vapp-net-%s' % n] = network_name
        if hasattr(vapp, 'NetworkConfigSection'):
            for nc in vapp.NetworkConfigSection.NetworkConfig:
                if nc.get('networkName') == network_name:
                    result['vapp-net-%s-mode' % n] = \
                        nc.Configuration.FenceMode.text
    if hasattr(vapp, 'LeaseSettingsSection'):
        if hasattr(vapp.LeaseSettingsSection, 'DeploymentLeaseInSeconds'):
            result['deployment_lease'] = to_human(
                int(vapp.LeaseSettingsSection.DeploymentLeaseInSeconds))
        if hasattr(vapp.LeaseSettingsSection, 'StorageLeaseInSeconds'):
            result['storage_lease'] = to_human(
                int(vapp.LeaseSettingsSection.StorageLeaseInSeconds))
        if hasattr(vapp.LeaseSettingsSection, 'DeploymentLeaseExpiration'):
            result['deployment_lease_expiration'] = \
                vapp.LeaseSettingsSection.DeploymentLeaseExpiration
    if hasattr(vapp, 'Children') and hasattr(vapp.Children, 'Vm'):
        n = 0
        for vm in vapp.Children.Vm:
            n += 1
            k = 'vm-%s' % n
            result[k + ': name'] = vm.get('name')
            items = vm.xpath(
                'ovf:VirtualHardwareSection/ovf:Item', namespaces=NSMAP)
            for item in items:
                element_name = item.find('rasd:ElementName', NSMAP)
                connection = item.find('rasd:Connection', NSMAP)
                if connection is None:
                    quantity = item.find('rasd:VirtualQuantity', NSMAP)
                    if quantity is None or isinstance(quantity, NoneElement):
                        value = item.find('rasd:Description', NSMAP)
                    else:
                        units = item.find('rasd:VirtualQuantityUnits', NSMAP)
                        if isinstance(units, NoneElement):
                            units = ''
                        value = '{:,} {}'.format(int(quantity), units).strip()
                else:
                    value = '{}: {}'.format(
                        connection.get('{' + NSMAP['vcloud'] +
                                       '}ipAddressingMode'),
                        connection.get('{' + NSMAP['vcloud'] + '}ipAddress'))
                result['%s: %s' % (k, element_name)] = value
            env = vm.xpath('ovfenv:Environment', namespaces=NSMAP)
            if len(env) > 0:
                result['%s: %s' % (k, 'moid')] = env[0].get('{' + NSMAP['ve'] +
                                                            '}vCenterId')
            if hasattr(vm, 'StorageProfile'):
                result['%s: %s' % (k, 'storage-profile')] = \
                    vm.StorageProfile.get('name')
            if hasattr(vm, 'GuestCustomizationSection'):
                if hasattr(vm.GuestCustomizationSection, 'AdminPassword'):
                    element_name = 'password'
                    value = vm.GuestCustomizationSection.AdminPassword
                    result['%s: %s' % (k, element_name)] = value
                if hasattr(vm.GuestCustomizationSection, 'ComputerName'):
                    element_name = 'computer-name'
                    value = vm.GuestCustomizationSection.ComputerName
                    result['%s: %s' % (k, element_name)] = value
            if hasattr(vm, 'NetworkConnectionSection'):
                ncs = vm.NetworkConnectionSection
                if 'PrimaryNetworkConnectionIndex' in ncs:
                    result['%s: %s' % (k, 'primary-net')] = \
                        ncs.PrimaryNetworkConnectionIndex.text
                if 'NetworkConnection' in ncs:
                    for nc in ncs.NetworkConnection:
                        nci = nc.NetworkConnectionIndex.text
                        result['%s: net-%s' % (k, nci)] = nc.get('network')
                        result['%s: net-%s-mode' % (k, nci)] = \
                            nc.IpAddressAllocationMode.text
                        result['%s: net-%s-connected' % (k, nci)] = \
                            nc.IsConnected.text
                        if hasattr(nc, 'MACAddress'):
                            result['%s: net-%s-mac' % (k, nci)] = \
                                nc.MACAddress.text
                        if hasattr(nc, 'IpAddress'):
                            result['%s: net-%s-ip' % (k,
                                                      nci)] = nc.IpAddress.text
            if 'VmSpecSection' in vm:
                for setting in vm.VmSpecSection.DiskSection.DiskSettings:
                    if hasattr(setting, 'Disk'):
                        result['%s: attached-disk-%s-name' %
                               (k, setting.DiskId.text)] = \
                            '%s' % (setting.Disk.get('name'))
                        result['%s: attached-disk-%s-size-Mb' %
                               (k, setting.DiskId.text)] = \
                            '%s' % (setting.SizeMb.text)
                        result['%s: attached-disk-%s-bus' %
                               (k, setting.DiskId.text)] = \
                            '%s' % (setting.BusNumber.text)
                        result['%s: attached-disk-%s-unit' %
                               (k, setting.DiskId.text)] = \
                            '%s' % (setting.UnitNumber.text)

    result['status'] = VCLOUD_STATUS_MAP.get(int(vapp.get('status')))
    if access_control_settings is not None:
        result.update(access_control_settings)
    if metadata is not None and hasattr(metadata, 'MetadataEntry'):
        for me in metadata.MetadataEntry:
            result['metadata: %s' % me.Key.text] = me.TypedValue.Value.text
    return result
Пример #14
0
def vm_to_dict(vm):
    """Converts a lxml.objectify.ObjectifiedElement VM object to a dict.

    :param lxml.objectify.ObjectifiedElement vm: an object containing
        EntityType.VM XML data.

    :return: dictionary representation of vApp object.

    :rtype: dict
    """
    result = {}
    result['name'] = vm.get('name')
    if hasattr(vm, 'Description'):
        result['description'] = vm.Description.text
    result['id'] = vm.get('id')

    result['deployed'] = vm.get('deployed')
    result['status'] = VCLOUD_STATUS_MAP.get(int(vm.get('status')))
    result['needs-customization'] = vm.get('needsCustomization')
    if hasattr(vm, 'VCloudExtension'):
        result['moref'] = vm.VCloudExtension[
            '{' + NSMAP['vmext'] + '}VmVimInfo'][
                '{' + NSMAP['vmext'] + '}VmVimObjectRef']['{' + NSMAP['vmext']
                                                          + '}MoRef'].text
    result['computer-name'] = vm.GuestCustomizationSection.ComputerName.text

    disk_instance_name_map = {}
    nic_instance_name_map = {}
    for item in vm['{' + NSMAP['ovf'] +
                   '}VirtualHardwareSection']['{' + NSMAP['ovf'] + '}Item']:
        if item['{' + NSMAP['rasd'] + '}ResourceType'].text == str(10):
            nic_instance_name_map[item[
                '{' + NSMAP['rasd'] + '}AddressOnParent'].text] = item[
                    '{' + NSMAP['rasd'] + '}ElementName'].text
        if item['{' + NSMAP['rasd'] + '}ResourceType'].text == str(17):
            disk_instance_name_map[item['{' + NSMAP['rasd'] + '}InstanceID'].
                                   text] = item['{' + NSMAP['rasd'] +
                                                '}ElementName'].text

    if hasattr(vm, 'NetworkConnectionSection'):
        ncs = vm.NetworkConnectionSection
        if hasattr(ncs, 'PrimaryNetworkConnectionIndex'):
            idx = ncs.PrimaryNetworkConnectionIndex.text
            result['primary-nic'] = 'nic-' + idx
        if hasattr(ncs, 'NetworkConnection'):
            for nc in ncs.NetworkConnection:
                nci = nc.NetworkConnectionIndex.text
                nic_props = {}
                result['nic-' + nci] = nic_props
                nic_props['name'] = nic_instance_name_map[nci]
                nic_props['network'] = nc.get('network')
                nic_props['mode'] = nc.IpAddressAllocationMode.text
                nic_props['connected'] = nc.IsConnected.text
                if hasattr(nc, 'MACAddress'):
                    nic_props['mac'] = nc.MACAddress.text
                if hasattr(nc, 'IpAddress'):
                    nic_props['ip'] = nc.IpAddress.text

    if hasattr(vm, 'VmSpecSection'):
        result['vm-tools-version'] = vm.VmSpecSection.VmToolsVersion.text
        result['os'] = vm.VmSpecSection.OsType.text
        result['cpu'] = vm.VmSpecSection.NumCpus.text
        result['cores-per-socket'] = vm.VmSpecSection.NumCoresPerSocket.text
        result['memory-MB'] = vm.VmSpecSection.MemoryResourceMb.Configured.text
        for setting in vm.VmSpecSection.DiskSection.DiskSettings:
            disk_props = {}
            result['disk-' + setting.DiskId.text] = disk_props
            disk_props['name'] = disk_instance_name_map[setting.DiskId.text]
            disk_props['size-MB'] = setting.SizeMb.text
            disk_props['bus'] = setting.BusNumber.text
            disk_props['unit'] = setting.UnitNumber.text

    return result
Пример #15
0
def vapp_to_dict(vapp):
    result = {}
    result['name'] = vapp.get('name')
    result['id'] = extract_id(vapp.get('id'))
    if 'ownerName' in vapp:
        result['owner'] = [vapp.get('ownerName')]
    if hasattr(vapp, 'Owner') and hasattr(vapp.Owner, 'User'):
        result['owner'] = []
        for user in vapp.Owner.User:
            result['owner'].append(user.get('name'))
    if hasattr(vapp, 'LeaseSettingsSection'):
        if hasattr(vapp.LeaseSettingsSection, 'DeploymentLeaseInSeconds'):
            result['deployment_lease'] = to_human(
                int(vapp.LeaseSettingsSection.DeploymentLeaseInSeconds))
        if hasattr(vapp.LeaseSettingsSection, 'StorageLeaseInSeconds'):
            result['storage_lease'] = to_human(
                int(vapp.LeaseSettingsSection.StorageLeaseInSeconds))
        if hasattr(vapp.LeaseSettingsSection, 'DeploymentLeaseExpiration'):
            result['deployment_lease_expiration'] = \
                vapp.LeaseSettingsSection.DeploymentLeaseExpiration
    if hasattr(vapp, 'Children') and hasattr(vapp.Children, 'Vm'):
        n = 0
        for vm in vapp.Children.Vm:
            n += 1
            k = 'vm-%s' % n
            result[k] = vm.get('name')
            items = vm.xpath('//ovf:VirtualHardwareSection/ovf:Item',
                             namespaces=NSMAP)
            for item in items:
                element_name = item.find('rasd:ElementName', NSMAP)
                connection = item.find('rasd:Connection', NSMAP)
                if connection is None:
                    quantity = item.find('rasd:VirtualQuantity', NSMAP)
                    if quantity is None or isinstance(quantity, NoneElement):
                        value = item.find('rasd:Description', NSMAP)
                    else:
                        units = item.find('rasd:VirtualQuantityUnits', NSMAP)
                        if isinstance(units, NoneElement):
                            units = ''
                        value = '{:,} {}'.format(int(quantity), units).strip()
                else:
                    value = '{}: {}'.format(
                        connection.get(
                            '{http://www.vmware.com/vcloud/v1.5}ipAddressingMode'
                        ),  # NOQA
                        connection.get(
                            '{http://www.vmware.com/vcloud/v1.5}ipAddress')
                    )  # NOQA
                result['%s: %s' % (k, element_name)] = value
            env = vm.xpath('//ovfenv:Environment', namespaces=NSMAP)
            if len(env) > 0:
                result['%s: %s' % (k, 'moid')] = env[0].get(
                    '{http://www.vmware.com/schema/ovfenv}vCenterId')  # NOQA
            if hasattr(vm.GuestCustomizationSection, 'AdminPassword'):
                element_name = 'password'
                value = vm.GuestCustomizationSection.AdminPassword
                result['%s: %s' % (k, element_name)] = value
            if hasattr(vm.GuestCustomizationSection, 'ComputerName'):
                element_name = 'computer-name'
                value = vm.GuestCustomizationSection.ComputerName
                result['%s: %s' % (k, element_name)] = value
    result['status'] = VCLOUD_STATUS_MAP.get(int(vapp.get('status')))
    return result
Пример #16
0
def vapp_to_dict(vapp, metadata=None):
    result = {}
    result['name'] = vapp.get('name')
    result['id'] = extract_id(vapp.get('id'))
    if 'ownerName' in vapp:
        result['owner'] = [vapp.get('ownerName')]
    if hasattr(vapp, 'Owner') and hasattr(vapp.Owner, 'User'):
        result['owner'] = []
        for user in vapp.Owner.User:
            result['owner'].append(user.get('name'))
    items = vapp.xpath('//ovf:NetworkSection/ovf:Network', namespaces=NSMAP)
    n = 0
    for item in items:
        n += 1
        network_name = item.get('{http://schemas.dmtf.org/ovf/envelope/1}name')
        result['vapp-net-%s' % n] = network_name
        if hasattr(vapp, 'NetworkConfigSection'):
            for nc in vapp.NetworkConfigSection.NetworkConfig:
                if nc.get('networkName') == network_name:
                    result['vapp-net-%s-mode' % n] = \
                        nc.Configuration.FenceMode.text
    if hasattr(vapp, 'LeaseSettingsSection'):
        if hasattr(vapp.LeaseSettingsSection, 'DeploymentLeaseInSeconds'):
            result['deployment_lease'] = to_human(
                int(vapp.LeaseSettingsSection.DeploymentLeaseInSeconds))
        if hasattr(vapp.LeaseSettingsSection, 'StorageLeaseInSeconds'):
            result['storage_lease'] = to_human(
                int(vapp.LeaseSettingsSection.StorageLeaseInSeconds))
        if hasattr(vapp.LeaseSettingsSection, 'DeploymentLeaseExpiration'):
            result['deployment_lease_expiration'] = \
                vapp.LeaseSettingsSection.DeploymentLeaseExpiration
    if hasattr(vapp, 'Children') and hasattr(vapp.Children, 'Vm'):
        n = 0
        for vm in vapp.Children.Vm:
            n += 1
            k = 'vm-%s' % n
            result[k + ': name'] = vm.get('name')
            items = vm.xpath('//ovf:VirtualHardwareSection/ovf:Item',
                             namespaces=NSMAP)
            for item in items:
                element_name = item.find('rasd:ElementName', NSMAP)
                connection = item.find('rasd:Connection', NSMAP)
                if connection is None:
                    quantity = item.find('rasd:VirtualQuantity', NSMAP)
                    if quantity is None or isinstance(quantity, NoneElement):
                        value = item.find('rasd:Description', NSMAP)
                    else:
                        units = item.find('rasd:VirtualQuantityUnits', NSMAP)
                        if isinstance(units, NoneElement):
                            units = ''
                        value = '{:,} {}'.format(int(quantity), units).strip()
                else:
                    value = '{}: {}'.format(
                        connection.get(
                            '{http://www.vmware.com/vcloud/v1.5}ipAddressingMode'
                        ),  # NOQA
                        connection.get(
                            '{http://www.vmware.com/vcloud/v1.5}ipAddress')
                    )  # NOQA
                result['%s: %s' % (k, element_name)] = value
            env = vm.xpath('//ovfenv:Environment', namespaces=NSMAP)
            if len(env) > 0:
                result['%s: %s' % (k, 'moid')] = env[0].get(
                    '{http://www.vmware.com/schema/ovfenv}vCenterId')  # NOQA
            if hasattr(vm, 'GuestCustomizationSection'):
                if hasattr(vm.GuestCustomizationSection, 'AdminPassword'):
                    element_name = 'password'
                    value = vm.GuestCustomizationSection.AdminPassword
                    result['%s: %s' % (k, element_name)] = value
                if hasattr(vm.GuestCustomizationSection, 'ComputerName'):
                    element_name = 'computer-name'
                    value = vm.GuestCustomizationSection.ComputerName
                    result['%s: %s' % (k, element_name)] = value
            if hasattr(vm, 'NetworkConnectionSection'):
                ncs = vm.NetworkConnectionSection
                result['%s: %s' % (k, 'primary-net')] = \
                    ncs.PrimaryNetworkConnectionIndex.text
                for nc in ncs.NetworkConnection:
                    nci = nc.NetworkConnectionIndex.text
                    result['%s: net-%s' % (k, nci)] = nc.get('network')
                    result['%s: net-%s-mode' % (k, nci)] = \
                        nc.IpAddressAllocationMode.text
                    result['%s: net-%s-connected' % (k, nci)] = \
                        nc.IsConnected.text
                    if hasattr(nc, 'MACAddress'):
                        result['%s: net-%s-mac' % (k, nci)] = \
                            nc.MACAddress.text
                    if hasattr(nc, 'IpAddress'):
                        result['%s: net-%s-ip' % (k, nci)] = nc.IpAddress.text
    result['status'] = VCLOUD_STATUS_MAP.get(int(vapp.get('status')))
    if metadata is not None and hasattr(metadata, 'MetadataEntry'):
        for me in metadata.MetadataEntry:
            result['metadata: %s' % me.Key.text] = me.TypedValue.Value.text
    return result