示例#1
0
文件: vc.py 项目: vmware/vca-cli
def info(ctx, name):
    try:
        restore_session(ctx)
        platform = Platform(ctx.obj['client'])
        stdout(platform.get_vcenter(name=name), ctx)
    except Exception as e:
        stderr(e, ctx)
示例#2
0
文件: vc.py 项目: vmware/vca-cli
def list_vcenters(ctx):
    try:
        restore_session(ctx)
        platform = Platform(ctx.obj['client'])
        stdout(platform.list_vcenters(), ctx)
    except Exception as e:
        stderr(e, ctx)
示例#3
0
文件: catalog.py 项目: vmware/vca-cli
def info(ctx, catalog_name, item_name):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        in_use_org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, in_use_org_href)
        if item_name is None:
            catalog = org.get_catalog(catalog_name)
            result = to_dict(catalog)
            # We don't have a way to know in advance if a user has access to a
            # catalog's ACL or not. So we try to retrieve it always. If the
            # call fails due to permission issues, we silently eat the
            # exception and exclude ACL settings from the output of the current
            # command. Users who have access to ACL of the catalog will remain
            # unaffected. Also any other errors/exceptions will bubble up as
            # usual.
            try:
                access_control_settings = access_settings_to_dict(
                    org.get_catalog_access_settings(catalog_name))
                result.update(access_control_settings)
            except AccessForbiddenException as e:
                pass
        else:
            catalog_item = org.get_catalog_item(catalog_name, item_name)
            result = to_dict(catalog_item)
            vapp = VApp(client, href=catalog_item.Entity.get('href'))
            vapp.reload()
            template = vapp_to_dict(vapp.resource)
            for k, v in template.items():
                result['template-%s' % k] = v
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#4
0
文件: disk.py 项目: vmware/vca-cli
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)
示例#5
0
文件: vdc.py 项目: vmware/vca-cli
def create(ctx, name, pvdc_name, network_pool_name, allocation_model, sp_name,
           sp_limit, description, cpu_allocated, cpu_limit):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        in_use_org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, in_use_org_href)
        storage_profiles = [{
            'name': sp_name,
            'enabled': True,
            'units': 'MB',
            'limit': sp_limit,
            'default': True
        }]
        vdc_resource = org.create_org_vdc(
            name,
            pvdc_name,
            network_pool_name=network_pool_name,
            description=description,
            allocation_model=allocation_model,
            cpu_allocated=cpu_allocated,
            cpu_limit=cpu_limit,
            storage_profiles=storage_profiles,
            uses_fast_provisioning=True,
            is_thin_provision=True)
        stdout(vdc_resource.Tasks.Task[0], ctx)
    except Exception as e:
        stderr(e, ctx)
示例#6
0
文件: network.py 项目: vmware/vca-cli
def create_isolated_network(ctx, name, gateway_ip, netmask, description,
                            primary_dns_ip, secondary_dns_ip, dns_suffix,
                            ip_range_start, ip_range_end, is_dhcp_enabled,
                            default_lease_time, max_lease_time,
                            dhcp_ip_range_start, dhcp_ip_range_end, is_shared):
    try:
        restore_session(ctx, vdc_required=True)
        client = ctx.obj['client']
        in_use_vdc_href = ctx.obj['profiles'].get('vdc_href')
        vdc = VDC(client, href=in_use_vdc_href)
        prefix_len = netmask_to_cidr_prefix_len(gateway_ip, netmask)
        network_cidr = gateway_ip + '/' + str(prefix_len)

        result = vdc.create_isolated_vdc_network(
            network_name=name,
            network_cidr=network_cidr,
            description=description,
            primary_dns_ip=primary_dns_ip,
            secondary_dns_ip=secondary_dns_ip,
            dns_suffix=dns_suffix,
            ip_range_start=ip_range_start,
            ip_range_end=ip_range_end,
            is_dhcp_enabled=is_dhcp_enabled,
            default_lease_time=default_lease_time,
            max_lease_time=max_lease_time,
            dhcp_ip_range_start=dhcp_ip_range_start,
            dhcp_ip_range_end=dhcp_ip_range_end,
            is_shared=is_shared)

        stdout(result.Tasks.Task[0], ctx)
    except Exception as e:
        stderr(e, ctx)
示例#7
0
文件: vapp.py 项目: vmware/vca-cli
def capture(ctx, name, catalog, template, customizable, description):
    try:
        restore_session(ctx, vdc_required=True)
        client = ctx.obj['client']
        in_use_org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, in_use_org_href)
        catalog_resource = org.get_catalog(catalog)
        vdc_href = ctx.obj['profiles'].get('vdc_href')
        vdc = VDC(client, href=vdc_href)
        vapp_resource = vdc.get_vapp(name)
        overwrite = False
        if template is None:
            template = vapp_resource.get('name')
        else:
            overwrite = True
        task = org.capture_vapp(
            catalog_resource,
            vapp_href=vapp_resource.get('href'),
            catalog_item_name=template,
            description=description,
            customize_on_instantiate=customizable == 'customizable',
            overwrite=overwrite)
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#8
0
文件: vdc.py 项目: vmware/vca-cli
def use(ctx, name):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        in_use_org_name = ctx.obj['profiles'].get('org_in_use')
        orgs = client.get_org_list()
        for org_resource in orgs:
            if org_resource.get('name').lower() == in_use_org_name.lower():
                for link in get_links(org_resource,
                                      media_type=EntityType.VDC.value):
                    if link.name == name:
                        vdc_in_use = name
                        vapp_in_use = ''
                        vapp_href = ''
                        client.get_resource(link.href)
                        ctx.obj['profiles'].set('vdc_in_use', vdc_in_use)
                        ctx.obj['profiles'].set('vdc_href', str(link.href))
                        ctx.obj['profiles'].set('vapp_in_use', vapp_in_use)
                        ctx.obj['profiles'].set('vapp_href', vapp_href)
                        message = 'now using org: \'%s\', vdc: \'%s\', vApp:' \
                            ' \'%s\'.' % (in_use_org_name, vdc_in_use,
                                          vapp_in_use)
                        stdout({
                            'org': in_use_org_name,
                            'vdc': vdc_in_use,
                            'vapp': vapp_in_use
                        }, ctx, message)
                        return
        raise Exception('Org \'%s\' not found' % in_use_org_name)
    except Exception as e:
        stderr(e, ctx)
示例#9
0
文件: vapp.py 项目: vmware/vca-cli
def create(ctx, name, description, catalog, template, network, memory, cpu,
           disk_size, ip_allocation_mode, vm_name, hostname, storage_profile,
           accept_all_eulas):
    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)
        if catalog is None and template is None:
            vapp_resource = vdc.create_vapp(
                name,
                description=description,
                network=network,
                accept_all_eulas=accept_all_eulas)
        else:
            vapp_resource = vdc.instantiate_vapp(
                name,
                catalog,
                template,
                description=description,
                network=network,
                memory=memory,
                cpu=cpu,
                disk_size=disk_size,
                deploy=True,
                power_on=True,
                accept_all_eulas=accept_all_eulas,
                cust_script=None,
                ip_allocation_mode=ip_allocation_mode,
                vm_name=vm_name,
                hostname=hostname,
                storage_profile=storage_profile)
        stdout(vapp_resource.Tasks.Task[0], ctx)
    except Exception as e:
        stderr(e, ctx)
示例#10
0
文件: catalog.py 项目: vmware/vca-cli
def list_catalogs_or_items(ctx, catalog_name):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        if catalog_name is None:
            in_use_org_href = ctx.obj['profiles'].get('org_href')
            org = Org(client, in_use_org_href)
            result = org.list_catalogs()
        else:
            result = []
            if is_sysadmin(ctx):
                resource_type = ResourceType.ADMIN_CATALOG_ITEM.value
            else:
                resource_type = ResourceType.CATALOG_ITEM.value
            q = client.get_typed_query(
                resource_type,
                query_result_format=QueryResultFormat.ID_RECORDS,
                equality_filter=('catalogName', catalog_name))
            records = list(q.execute())
            if len(records) == 0:
                result = 'not found'
            else:
                for r in records:
                    result.append(to_dict(r, resource_type=resource_type))
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#11
0
文件: user.py 项目: vmware/vca-cli
def create(ctx, user_name, password, role_name, full_name, description, email,
           telephone, im, enabled, alert_enabled, alert_email,
           alert_email_prefix, external, default_cached, group_role,
           stored_vm_quota, deployed_vm_quota):
    try:
        if len(password) < 6:
            raise Exception('Password must be at least 6 characters long.')
        restore_session(ctx)
        client = ctx.obj['client']
        in_use_org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, in_use_org_href)
        role = org.get_role_record(role_name)
        role_href = role.get('href')
        result = org.create_user(
            user_name=user_name,
            password=password,
            role_href=role_href,
            full_name=full_name,
            description=description,
            email=email,
            telephone=telephone,
            im=im,
            alert_email=alert_email,
            alert_email_prefix=alert_email_prefix,
            stored_vm_quota=stored_vm_quota,
            deployed_vm_quota=deployed_vm_quota,
            is_group_role=group_role,
            is_default_cached=default_cached,
            is_external=external,
            is_alert_enabled=alert_enabled,
            is_enabled=enabled)
        stdout('User \'%s\' is successfully created.' % result.get('name'),
               ctx)
    except Exception as e:
        stderr(e, ctx)
示例#12
0
文件: org.py 项目: vmware/vca-cli
def use(ctx, name):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        org_resource = client.get_org_by_name(name)
        in_use_vdc = ''
        vdc_href = ''
        in_use_vapp = ''
        vapp_href = ''
        for link in get_links(org_resource, media_type=EntityType.VDC.value):
            in_use_vdc = link.name
            vdc_href = link.href
            break
        ctx.obj['profiles'].set('org_in_use', str(name))
        ctx.obj['profiles'].set('org_href', str(org_resource.get('href')))
        ctx.obj['profiles'].set('vdc_in_use', str(in_use_vdc))
        ctx.obj['profiles'].set('vdc_href', str(vdc_href))
        ctx.obj['profiles'].set('vapp_in_use', str(in_use_vapp))
        ctx.obj['profiles'].set('vapp_href', vapp_href)
        message = 'now using org: \'%s\', vdc: \'%s\', vApp: \'%s\'.' \
            % (name, in_use_vdc, in_use_vapp)
        stdout({
            'org': name,
            'vdc': in_use_vdc,
            'vapp': in_use_vapp
        }, ctx, message)
    except Exception as e:
        stderr(e, ctx)
示例#13
0
文件: vc.py 项目: vmware/vca-cli
def detach(ctx, name):
    try:
        restore_session(ctx)
        platform = Platform(ctx.obj['client'])
        stdout(platform.detach_vcenter(vc_name=name), ctx)
    except Exception as e:
        stderr(e, ctx)
示例#14
0
def list_allocated_ip(ctx, vapp_name, network_name):
    try:
        restore_session(ctx, vdc_required=True)
        vapp = get_vapp(ctx, vapp_name)
        task = vapp.list_ip_allocations(network_name)
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#15
0
def delete_vapp_network(ctx, vapp_name, network_name):
    try:
        restore_session(ctx, vdc_required=True)
        vapp = get_vapp(ctx, vapp_name)
        task = vapp.delete_vapp_network(network_name)
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#16
0
文件: vapp.py 项目: vmware/vca-cli
def discard_suspended_state_vapp(ctx, vapp_name):
    try:
        restore_session(ctx, vdc_required=True)
        vapp = get_vapp(ctx, vapp_name)
        task = vapp.discard_suspended_state_vapp()
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#17
0
文件: vapp.py 项目: vmware/vca-cli
def stop_vapp(ctx, vapp_name):
    try:
        restore_session(ctx, vdc_required=True)
        vapp = get_vapp(ctx, vapp_name)
        task = vapp.undeploy()
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#18
0
文件: vm.py 项目: vmware/vca-cli
def consolidate(ctx, vapp_name, vm_name):
    try:
        restore_session(ctx, vdc_required=True)
        vm = _get_vm(ctx, vapp_name, vm_name)
        task = vm.consolidate()
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#19
0
文件: vapp.py 项目: vmware/vca-cli
def exit_maintenance_mode(ctx, vapp_name):
    try:
        restore_session(ctx, vdc_required=True)
        vapp = get_vapp(ctx, vapp_name)
        vapp.exit_maintenance_mode()
        stdout('exited maintenance mode successfully', ctx)
    except Exception as e:
        stderr(e, ctx)
示例#20
0
文件: vm.py 项目: vmware/vca-cli
def eject_cd(ctx, vapp_name, vm_name, media_href):
    try:
        restore_session(ctx, vdc_required=True)
        vm = _get_vm(ctx, vapp_name, vm_name)
        task = vm.eject_cd(media_href)
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#21
0
文件: vm.py 项目: vmware/vca-cli
def list_nics(ctx, vapp_name, vm_name):
    try:
        restore_session(ctx, vdc_required=True)
        vm = _get_vm(ctx, vapp_name, vm_name)
        nics = vm.list_nics()
        stdout(nics, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#22
0
文件: vc.py 项目: vmware/vca-cli
def disable(ctx, name):
    try:
        restore_session(ctx)
        platform = Platform(ctx.obj['client'])
        stdout(platform.enable_disable_vcenter(
            vc_name=name, enable_flag=False), ctx)
    except Exception as e:
        stderr(e, ctx)
示例#23
0
文件: vm.py 项目: vmware/vca-cli
def discard_suspend(ctx, vapp_name, vm_name):
    try:
        restore_session(ctx, vdc_required=True)
        vm = _get_vm(ctx, vapp_name, vm_name)
        task = vm.discard_suspended_state()
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#24
0
文件: vm.py 项目: vmware/vca-cli
def install_vmware_tools(ctx, vapp_name, vm_name):
    try:
        restore_session(ctx, vdc_required=True)
        vm = _get_vm(ctx, vapp_name, vm_name)
        task = vm.install_vmware_tools()
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#25
0
文件: vm.py 项目: vmware/vca-cli
def delete_nic(ctx, vapp_name, vm_name, index):
    try:
        restore_session(ctx, vdc_required=True)
        vm = _get_vm(ctx, vapp_name, vm_name)
        task = vm.delete_nic(index)
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#26
0
文件: vm.py 项目: vmware/vca-cli
def insert_cd(ctx, vapp_name, vm_name, media_href):
    try:
        restore_session(ctx, vdc_required=True)
        vm = _get_vm(ctx, vapp_name, vm_name)
        task = vm.insert_cd_from_catalog(media_href)
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#27
0
文件: task.py 项目: vmware/vca-cli
def wait(ctx, task_id):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        task = client.get_resource('%s/task/%s' % (client._uri, task_id))
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#28
0
文件: task.py 项目: vmware/vca-cli
def info(ctx, task_id):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        result = client.get_resource('%s/task/%s' % (client._uri, task_id))
        stdout(task_to_dict(result), ctx, show_id=True)
    except Exception as e:
        stderr(e, ctx)
示例#29
0
文件: vm.py 项目: vmware/vca-cli
def reset(ctx, vapp_name, vm_name):
    try:
        restore_session(ctx, vdc_required=True)
        vm = _get_vm(ctx, vapp_name, vm_name)
        task = vm.power_reset()
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#30
0
文件: vm.py 项目: vmware/vca-cli
def info(ctx, vapp_name, vm_name):
    try:
        restore_session(ctx, vdc_required=True)
        vm = _get_vm(ctx, vapp_name, vm_name).get_resource()
        result = vm_to_dict(vm)
        result['vapp'] = vapp_name
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#31
0
def delete_gateway(ctx, name):
    """delete a gateway.
        \b
            Note
                System Administrators can delete gateway.
        \b
            Examples
                vcd gateway delete <gateway-name>
                 Delete gateway by providing gateway name
    """
    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)
        task = vdc.delete_gateway(name)
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
def cluster_config(ctx, name, vdc, org):
    """Display cluster configuration.

    To write to a file: `vcd cse cluster config mycluster > ~/.kube/my_config`
    """
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        cluster = Cluster(client)
        if not client.is_sysadmin() and org is None:
            org = ctx.obj['profiles'].get('org_in_use')
        cluster_config = cluster.get_cluster_config(
            name, vdc=vdc, org=org).get(RESPONSE_MESSAGE_KEY)  # noqa: E501
        if os.name == 'nt':
            cluster_config = str.replace(cluster_config, '\n', '\r\n')

        click.secho(cluster_config)
    except Exception as e:
        stderr(e, ctx)
示例#33
0
文件: login.py 项目: tjecheva/vcd-cli
def logout(ctx):
    """Logout from vCloud Director

    """
    try:
        try:
            restore_session(ctx)
            client = ctx.obj['client']
            client.logout()
        except Exception:
            pass
        if ctx is not None and ctx.obj is not None:
            profiles = ctx.obj['profiles']
            profiles.set('token', '')
            stdout('%s logged out.' % (profiles.get('user')), ctx)
        else:
            stderr('Not logged in.', ctx)
    except Exception as e:
        stderr(e, ctx)
示例#34
0
def list_nodes(ctx, name, org, vdc):
    """Display nodes of a cluster that uses native Kubernetes provider."""
    CLIENT_LOGGER.debug(f'Executing command: {ctx.command_path}')
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        if org is None and not client.is_sysadmin():
            org = ctx.obj['profiles'].get('org_in_use')
        cluster = Cluster(client)
        cluster_info = cluster.get_cluster_info(name, org=org, vdc=vdc)
        if cluster_info.get(K8S_PROVIDER_KEY) != K8sProvider.NATIVE:
            raise Exception("'node list' operation is not supported by non "
                            "native clusters.")
        all_nodes = cluster_info['master_nodes'] + cluster_info['nodes']
        stdout(all_nodes, ctx, show_id=True)
        CLIENT_LOGGER.debug(all_nodes)
    except Exception as e:
        stderr(e, ctx)
        CLIENT_LOGGER.error(str(e))
示例#35
0
def create(ctx, vc_name, resource_pool, storage_profile, pvdc_name, enable,
           description, highest_supp_hw_vers, vxlan_network_pool):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        platform = Platform(client)
        pvdc = \
            platform.create_provider_vdc(vim_server_name=vc_name,
                                         resource_pool_names=resource_pool,
                                         storage_profiles=storage_profile,
                                         pvdc_name=pvdc_name,
                                         is_enabled=enable,
                                         description=description,
                                         highest_hw_vers=highest_supp_hw_vers,
                                         vxlan_network_pool=vxlan_network_pool)
        stdout(pvdc.find('vcloud:Tasks', NSMAP).Task[0], ctx)
        stdout('PVDC created successfully.', ctx)
    except Exception as e:
        stderr(e, ctx)
示例#36
0
文件: vdc.py 项目: mlees19/vcd-cli
def vdc(ctx):
    """Work with virtual datacenters in vCloud Director.

\b
    Examples
        vcd vdc list
            Get list of virtual datacenters in current organization.
\b
        vcd vdc info my-vdc
            Get details of the virtual datacenter 'my-vdc'.
\b
        vcd vdc use my-vdc
            Set virtual datacenter 'my-vdc' as default.
    """  # NOQA
    if ctx.invoked_subcommand is not None:
        try:
            restore_session(ctx)
        except Exception as e:
            stderr(e, ctx)
示例#37
0
def org(ctx):
    """Work with organizations in vCloud Director.

\b
    Examples
        vcd org list
            Get list of organizations.
\b
        vcd org info my-org
            Get details of the organization 'my-org'.
\b
        vcd org use my-org
            Set organization 'my-org' as default.
    """  # NOQA
    if ctx.invoked_subcommand is not None:
        try:
            restore_session(ctx)
        except Exception as e:
            stderr(e, ctx)
def cluster_delete(ctx, name, vdc, org):
    """Delete a Kubernetes cluster."""
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        cluster = Cluster(client)
        if not client.is_sysadmin() and org is None:
            org = ctx.obj['profiles'].get('org_in_use')
        result = cluster.delete_cluster(name, org, vdc)
        # result is empty for delete cluster operation on PKS-managed clusters.
        # In that specific case, below check helps to print out a meaningful
        # message to users.
        if len(result) == 0:
            click.secho(f"Delete cluster operation has been initiated on "
                        f"{name}, please check the status using"
                        f" 'vcd cse cluster info {name}'.", fg='yellow')
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)
def cluster_upgrade(ctx, cluster_name, template_name, template_revision,
                    vdc, org_name):
    """Upgrade cluster software to specified template's software versions.

    Affected software: Docker-CE, Kubernetes, CNI
    """
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        cluster = Cluster(client)
        if not client.is_sysadmin() and org_name is None:
            org_name = ctx.obj['profiles'].get('org_in_use')

        result = cluster.upgrade_cluster(cluster_name, template_name,
                                         template_revision, ovdc_name=vdc,
                                         org_name=org_name)
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#40
0
def resize(ctx, name, node_count, network_name, vdc, disable_rollback):
    """Resize the cluster to contain the specified number of worker nodes.

    Clusters that use native Kubernetes provider can not be sized down
    (use 'vcd cse node delete' command to do so).
    """
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        cluster = Cluster(client)
        result = cluster.resize_cluster(
            network_name,
            name,
            node_count=node_count,
            vdc=ctx.obj['profiles'].get('vdc_in_use') if vdc is None else vdc,
            disable_rollback=disable_rollback)
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)
def list_templates(ctx):
    """Display CSE templates."""
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        cluster = Cluster(client)
        result = []
        templates = cluster.get_templates()
        for t in templates:
            result.append({
                'name': t['name'],
                'description': t['description'],
                'catalog': t['catalog'],
                'catalog_item': t['catalog_item'],
                'is_default': t['is_default'],
            })
        stdout(result, ctx, show_id=True)
    except Exception as e:
        stderr(e, ctx)
示例#42
0
def list_isolated_networks(ctx):
    try:
        restore_session(ctx, vdc_required=True)
        client = ctx.obj['client']
        in_use_vdc_href = ctx.obj['profiles'].get('vdc_href')
        vdc = VDC(client, href=in_use_vdc_href)

        isolated_nets = vdc.list_orgvdc_isolated_networks()

        result = []
        for isolated_net in isolated_nets:
            result.append({'name': isolated_net.get('name')})
        stdout(result, ctx)
    except Exception as e:
        if type(e).__name__ == 'AccessForbiddenException':
            message = "Access denied.\nPlease try following command"
            message += '\nvcd network list'
            stdout(message, ctx)
        stderr(e, ctx)
示例#43
0
def compute_policy_add(ctx, org_name, ovdc_name, compute_policy_name):
    CLIENT_LOGGER.debug(f'Executing command: {ctx.command_path}')
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        if not client.is_sysadmin():
            raise Exception("Insufficient permission to perform operation.")

        ovdc = Ovdc(client)
        result = ovdc.update_ovdc_compute_policies(ovdc_name,
                                                   org_name,
                                                   compute_policy_name,
                                                   ComputePolicyAction.ADD,
                                                   False)
        stdout(result, ctx)
        CLIENT_LOGGER.debug(result)
    except Exception as e:
        stderr(e, ctx)
        CLIENT_LOGGER.error(str(e))
示例#44
0
def shutdown(ctx, name, vm_names):
    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)
        vapp_resource = vdc.get_vapp(name)
        vapp = VApp(client, resource=vapp_resource)
        if len(vm_names) == 0:
            task = vapp.shutdown()
            stdout(task, ctx)
        else:
            for vm_name in vm_names:
                vm = VM(client, href=vapp.get_vm(vm_name).get('href'))
                vm.reload()
                task = vm.shutdown()
                stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#45
0
def remove(ctx, vapp_name, access_list, all):
    try:
        if all:
            click.confirm(
                'Do you want to remove all access settings from the vapp '
                '\'%s\'' % vapp_name,
                abort=True)
        restore_session(ctx, vdc_required=True)
        client = ctx.obj['client']
        vdc_href = ctx.obj['profiles'].get('vdc_href')
        vdc = VDC(client, href=vdc_href)
        vapp = VApp(client, resource=vdc.get_vapp(vapp_name))

        vapp.remove_access_settings(
            access_settings_list=acl_str_to_list_of_dict(access_list),
            remove_all=all)
        stdout('Access settings removed from vapp \'%s\'.' % vapp_name, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#46
0
def remove(ctx, catalog_name, access_list, all):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        in_use_org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, in_use_org_href)

        if all:
            click.confirm(
                'Do you want to remove all access settings from the catalog '
                '\'%s\'' % catalog_name,
                abort=True)
        org.remove_catalog_access_settings(
            catalog_name=catalog_name,
            access_settings_list=acl_str_to_list_of_dict(access_list),
            remove_all=all)
        stdout('Access settings removed from catalog \'%s\'.' % catalog_name,
               ctx)
    except Exception as e:
        stderr(e, ctx)
示例#47
0
def ovdc_info(ctx, ovdc_name, org_name):
    """Display information about Kubernetes provider for an org VDC."""
    CLIENT_LOGGER.debug(f'Executing command: {ctx.command_path}')
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        if client.is_sysadmin():
            ovdc = Ovdc(client)
            if org_name is None:
                org_name = ctx.obj['profiles'].get('org_in_use')
            result = ovdc.info_ovdc_for_k8s(ovdc_name, org_name)
            stdout(result, ctx)
            CLIENT_LOGGER.debug(result)
        else:
            msg = "Insufficient permission to perform operation"
            stderr(msg, ctx)
            CLIENT_LOGGER.error(msg)
    except Exception as e:
        stderr(e, ctx)
        CLIENT_LOGGER.error(str(e))
示例#48
0
文件: vm.py 项目: sompa/vcd-cli
def update(ctx, vapp_name, vm_name, cpu, cores, memory):
    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)
        vapp_resource = vdc.get_vapp(vapp_name)
        vapp = VApp(client, resource=vapp_resource)
        vm_resource = vapp.get_vm(vm_name)
        vm = VM(client, resource=vm_resource)
        if cpu is not None:
            task_cpu_update = vm.modify_cpu(cpu, cores)
            stdout("Updating cpu (and core(s) if specified) for the VM")
            stdout(task_cpu_update, ctx)
        if memory is not None:
            task_memory_update = vm.modify_memory(memory)
            stdout("Updating memory for the VM")
            stdout(task_memory_update, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#49
0
文件: vm.py 项目: rdbwebster/vcd-cli
def vm(ctx):
    """Manage VMs in vCloud Director.

\b
    Examples
        vcd vm list
            Get list of VMs in current virtual datacenter.
\b
        vcd vm info vapp1 vm1
            Get details of the VM 'vm1' in vApp 'vapp1'.
    """

    if ctx.invoked_subcommand is not None:
        try:
            restore_session(ctx)
            if not ctx.obj['profiles'].get('vdc_in_use') or \
               not ctx.obj['profiles'].get('vdc_href'):
                raise Exception('select a virtual datacenter')
        except Exception as e:
            stderr(e, ctx)
示例#50
0
def list_orgs(ctx):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        logged_in_org_name = ctx.obj['profiles'].get('org')
        in_use_org_name = ctx.obj['profiles'].get('org_in_use')
        orgs = client.get_org_list()
        result = []
        for org in [o for o in orgs.Org if hasattr(orgs, 'Org')]:
            result.append({
                'name':
                org.get('name'),
                'logged_in':
                logged_in_org_name.lower() == org.get('name').lower(),
                'in_use':
                in_use_org_name.lower() == org.get('name').lower()
            })
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#51
0
def list_vapps(ctx, name):
    try:
        restore_session(ctx, vdc_required=True)
        client = ctx.obj['client']
        result = []
        if name is None:
            if is_sysadmin(ctx):
                resource_type = ResourceType.ADMIN_VAPP.value
            else:
                resource_type = ResourceType.VAPP.value
            name_filter = None
            attributes = None
        else:
            if is_sysadmin(ctx):
                resource_type = ResourceType.ADMIN_VM.value
            else:
                resource_type = ResourceType.VM.value
            name_filter = ('containerName', name)
            attributes = [
                'name', 'containerName', 'ipAddress', 'status', 'memoryMB',
                'numberOfCpus'
            ]
        q = client.get_typed_query(
            resource_type,
            query_result_format=QueryResultFormat.ID_RECORDS,
            equality_filter=name_filter)
        records = list(q.execute())
        if len(records) == 0:
            if name is None:
                result = 'No vApps were found.'
            else:
                result = 'No vms were found.'
        else:
            for r in records:
                result.append(
                    to_dict(r,
                            resource_type=resource_type,
                            attributes=attributes))
        stdout(result, ctx, show_id=False)
    except Exception as e:
        stderr(e, ctx)
def cluster_resize(ctx, cluster_name, node_count, network_name, org_name,
                   vdc_name, disable_rollback, template_name,
                   template_revision):
    """Resize the cluster to contain the specified number of worker nodes.

    Clusters that use native Kubernetes provider can not be sized down
    (use 'vcd cse node delete' command to do so).
    """
    try:
        if (template_name and not template_revision) or \
                (not template_name and template_revision):
            raise Exception("Both --template-name (-t) and "
                            "--template-revision (-r) must be specified.")

        restore_session(ctx)
        client = ctx.obj['client']
        if not client.is_sysadmin() and org_name is None:
            org_name = ctx.obj['profiles'].get('org_in_use')
        cluster = Cluster(client)
        result = cluster.resize_cluster(network_name,
                                        cluster_name,
                                        node_count=node_count,
                                        org=org_name,
                                        vdc=vdc_name,
                                        rollback=not disable_rollback,
                                        template_name=template_name,
                                        template_revision=template_revision)
        stdout(result, ctx)
    except CseResponseError as e:
        minor_error_code_to_error_message = {
            MinorErrorCode.REQUEST_KEY_NETWORK_NAME_MISSING:
            'Missing option "-n" / "--network".',  # noqa: E501
            MinorErrorCode.REQUEST_KEY_NETWORK_NAME_INVALID:
            'Invalid or missing value for option "-n" / "--network".'  # noqa: E501
        }
        e.error_message = \
            minor_error_code_to_error_message.get(
                e.minor_error_code, e.error_message)
        stderr(e, ctx)
    except Exception as e:
        stderr(e, ctx)
def cluster_create(ctx, name, vdc, node_count, cpu, memory, network_name,
                   storage_profile, ssh_key_file, template_name,
                   template_revision, enable_nfs, disable_rollback, org_name):
    """Create a Kubernetes cluster."""
    try:
        if (template_name and not template_revision) or \
                (not template_name and template_revision):
            raise Exception("Both flags --template-name(-t) and "
                            "--template-revision (-r) must be specified.")

        restore_session(ctx)
        if vdc is None:
            vdc = ctx.obj['profiles'].get('vdc_in_use')
            if not vdc:
                raise Exception("Virtual datacenter context is not set. "
                                "Use either command 'vcd vdc use' or option "
                                "'--vdc' to set the vdc context.")
        if org_name is None:
            org_name = ctx.obj['profiles'].get('org_in_use')
        ssh_key = None
        if ssh_key_file is not None:
            ssh_key = ssh_key_file.read()

        client = ctx.obj['client']
        cluster = Cluster(client)
        result = cluster.create_cluster(vdc,
                                        network_name,
                                        name,
                                        node_count=node_count,
                                        cpu=cpu,
                                        memory=memory,
                                        storage_profile=storage_profile,
                                        ssh_key=ssh_key,
                                        template_name=template_name,
                                        template_revision=template_revision,
                                        enable_nfs=enable_nfs,
                                        rollback=not disable_rollback,
                                        org=org_name)
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#54
0
def acl(ctx):
    """Work with catalogs access control list in the current Organization.

\b
    Examples
        vcd catalog acl add my-catalog 'org:TestOrg1:Change'  \\
            'user:TestUser1:FullControl' 'org:TestOrg2'
            Add one or more access setting to the specified catalog.
            access-list is specified in the format
            '<subject-type>:<subject-name>:<access-level>'
            subject-type is one of 'org' ,'user'
            subject-name is either username or org name
            access-level is one of 'ReadOnly', 'Change', 'FullControl'
            'ReadOnly' by default. eg. 'org:TestOrg2'
\b
        vcd catalog acl remove my-catalog 'org:TestOrg1' 'user:TestUser1'
            Remove one or more acl from the specified catalog. access-list is
            specified in the format '<subject-type>:<subject-name>'
            subject-type is one of 'org' ,'user'
            subject-name is either username or org name
\b
        vcd catalog acl share my-catalog --access-level ReadOnly
            Share catalog access to all members of the current organization
\b
        vcd catalog acl unshare my-catalog
            Unshare  catalog access from  all members of the current
            organization
\b
        vcd catalog acl list my-catalog
            List acl of a catalog

\b
        vcd catalog acl info my-catalog
            Get details of catalog access control settings

    """
    if ctx.invoked_subcommand is not None:
        try:
            restore_session(ctx)
        except Exception as e:
            stderr(e, ctx)
示例#55
0
文件: vdc.py 项目: sompa/vcd-cli
def list_vdc(ctx):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        in_use_org_name = ctx.obj['profiles'].get('org_in_use')
        in_use_vdc = ctx.obj['profiles'].get('vdc_in_use')
        orgs = client.get_org_list()
        result = []
        for org_resouce in orgs:
            if org_resouce.get('name').lower() == in_use_org_name.lower():
                for link in get_links(org_resouce,
                                      media_type=EntityType.VDC.value):
                    result.append({
                        'name': link.name,
                        'org': org_resouce.get('name'),
                        'in_use': in_use_vdc == link.name
                    })
                break
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#56
0
def download(ctx, catalog_name, item_name, file_name, progress, overwrite):
    try:
        restore_session(ctx)
        save_as_name = item_name
        if file_name is not None:
            save_as_name = file_name
        if not overwrite and os.path.isfile(save_as_name):
            raise Exception('File exists.')
        client = ctx.obj['client']
        in_use_org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, in_use_org_href)
        cb = download_callback if progress else None
        bytes_written = org.download_catalog_item(catalog_name,
                                                  item_name,
                                                  save_as_name,
                                                  callback=cb,
                                                  task_callback=task_callback)
        result = {'file': save_as_name, 'size': bytes_written}
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#57
0
def use(ctx, name):
    try:
        restore_session(ctx, vdc_required=True)
        client = ctx.obj['client']
        in_use_org_name = ctx.obj['profiles'].get('org_in_use')
        in_use_vdc_name = ctx.obj['profiles'].get('vdc_in_use')
        vdc_href = ctx.obj['profiles'].get('vdc_href')
        vdc = VDC(client, href=vdc_href)
        vapp_resource = vdc.get_vapp(name)
        vapp = VApp(client, resource=vapp_resource)
        ctx.obj['profiles'].set('vapp_in_use', str(name))
        ctx.obj['profiles'].set('vapp_href', str(vapp.href))
        message = 'now using org: \'%s\', vdc: \'%s\', vApp: \'%s\'.' % \
                  (in_use_org_name, in_use_vdc_name, name)
        stdout({
            'org': in_use_org_name,
            'vdc': in_use_vdc_name,
            'vapp': name
        }, ctx, message)
    except Exception as e:
        stderr(e, ctx)
示例#58
0
def capture(ctx, name, catalog, template, customizable):
    try:
        restore_session(ctx, vdc_required=True)
        client = ctx.obj['client']
        in_use_org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, in_use_org_href)
        catalog_resource = org.get_catalog(catalog)
        vdc_href = ctx.obj['profiles'].get('vdc_href')
        vdc = VDC(client, href=vdc_href)
        vapp_resource = vdc.get_vapp(name)
        if template is None:
            template = vapp_resource.get('name')
        task = org.capture_vapp(
            catalog_resource,
            vapp_href=vapp_resource.get('href'),
            catalog_item_name=template,
            description='',
            customize_on_instantiate=customizable == 'customizable')
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#59
0
文件: vdc.py 项目: LEMNX/vcd-cli
def list_vdc(ctx):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        in_use_org_name = ctx.obj['profiles'].get('org_in_use')
        in_use_vdc = ctx.obj['profiles'].get('vdc_in_use')
        orgs = client.get_org_list()
        result = []
        for org in [o for o in orgs.Org if hasattr(orgs, 'Org')]:
            if org.get('name') == in_use_org_name:
                resource = client.get_resource(org.get('href'))
                for v in get_links(resource, media_type=EntityType.VDC.value):
                    result.append({
                        'name': v.name,
                        'org': in_use_org_name,
                        'in_use': in_use_vdc == v.name
                    })
                break
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)
示例#60
0
def list_users(ctx, org_name):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        if org_name is not None:
            org_href = client.get_org_by_name(org_name).get('href')
        else:
            org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, href=org_href)
        users = org.list_users()
        result = []
        for record in list(users):
            result.append(
                to_dict(record,
                        exclude=[
                            'org', 'orgName', 'deployedVMQuotaRank',
                            'storedVMQuotaRank'
                        ]))
        stdout(result, ctx)
    except Exception as e:
        stderr(e, ctx)