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)
def list_catalogs_or_items(ctx, catalog_name): try: client = ctx.obj['client'] if catalog_name is None: org_name = ctx.obj['profiles'].get('org') in_use_org_href = ctx.obj['profiles'].get('org_href') org = Org(client, in_use_org_href, org_name == 'System') result = org.list_catalogs() else: result = [] resource_type = \ 'adminCatalogItem' if is_admin(ctx) else 'catalogItem' q = client.get_typed_query(resource_type, query_result_format=QueryResultFormat. ID_RECORDS, qfilter='catalogName==%s' % 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)
def list_vapps(ctx, name): try: client = ctx.obj['client'] result = [] if name is None: resource_type = 'adminVApp' if is_sysadmin(ctx) else 'vApp' qfilter = None attributes = None else: resource_type = 'adminVm' if is_sysadmin(ctx) else 'vm' qfilter = 'containerName==%s' % name attributes = [ 'name', 'containerName', 'ipAddress', 'status', 'memoryMB', 'numberOfCpus' ] q = client.get_typed_query( resource_type, query_result_format=QueryResultFormat.ID_RECORDS, qfilter=qfilter) 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, attributes=attributes)) stdout(result, ctx, show_id=False) except Exception as e: stderr(e, ctx)
def list_roles(self, name_filter=None): """Retrieve the list of roles in the current Org. :param name_filter: (tuple): (name ,'role name') Filter roles by 'role name' :return: (list): (RoleRecord) List of roles """ if self.resource is None: self.resource = self.client.get_resource(self.href) org_filter = None resource_type = 'role' if self.client.is_sysadmin(): resource_type = 'adminRole' org_filter = 'org==%s' % self.resource.get('href') query = self.client.get_typed_query( resource_type, query_result_format=QueryResultFormat.RECORDS, equality_filter=name_filter, qfilter=org_filter) result = [] for r in list(query.execute()): result.append( to_dict( r, resource_type=resource_type, exclude=['org', 'orgName'])) return result
def search(ctx, resource_type, query_filter): """Search for resources in vCloud Director. \b Description Search for resources of the provided type. Resource type is not case sensitive. When invoked without a resource type, list the available types to search for. Admin types are only allowed when the user is the system administrator. \b Filters can be applied to the search. \b Examples vcd search lists available resource types. \b vcd search task Search for all tasks in current organization. \b vcd search task --filter 'status==running' Search for running tasks in current organization. \b vcd search admintask --filter 'status==running' Search for running tasks in all organizations, system administrator only. \b vcd search task --filter 'id==ffb96443-d7f3-4200-825d-0f297388ebc0' Search for a task by id \b vcd search vapp Search for vApps. \b vcd search vapp -f 'metadata:cse.node.type==STRING:master' Search for vApps by metadata. \b vcd search vm Search for virtual machines. """ # NOQA try: if resource_type is None: click.secho(ctx.get_help()) click.echo('\nAvailable resource types:') click.echo(tabulate(tabulate_names(RESOURCE_TYPES, 4))) return restore_session(ctx) client = ctx.obj['client'] result = [] resource_type_cc = to_camel_case(resource_type, RESOURCE_TYPES) q = client.get_typed_query(resource_type_cc, query_result_format=QueryResultFormat. ID_RECORDS, qfilter=query_filter) 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_cc)) stdout(result, ctx, show_id=True) except Exception as e: stderr(e, ctx)
def list_roles(self, name_filter=None): """Retrieve the list of roles in the current Org. :param name_filter: (tuple): (name ,'role name') Filter roles by 'role name' :return: (list): (RoleRecord) List of roles """ if self.resource is None: self.resource = self.client.get_resource(self.href) org_filter = None resource_type = 'role' if self.client.is_sysadmin(): resource_type = 'adminRole' org_filter = 'org==%s' % self.resource.get('href') query = self.client.get_typed_query( resource_type, query_result_format=QueryResultFormat.RECORDS, equality_filter=name_filter, qfilter=org_filter) result = [] for r in list(query.execute()): result.append( to_dict(r, resource_type=resource_type, exclude=['org', 'orgName'])) return result
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)
def create_user_name_to_id_dict(client: Client, users_set: set, org_href): """Get a dictionary of users to user ids from a list of user names. :param Client client: current client :param set users_set: set of user names :param str org_href: href of the org to search in :return: dict of user name keys and user id values :rtype: dict :raise Exception is not all id's are found for users """ own_users_set = users_set.copy() org = vcd_org.Org(client, org_href) org_users = org.list_users() user_name_to_id_dict = {} for user_str_elem in org_users: curr_user_dict = vcd_utils.to_dict(user_str_elem, exclude=[]) curr_user_name = curr_user_dict['name'] if curr_user_name in own_users_set: user_id = extract_id_from_href(curr_user_dict['href']) user_name_to_id_dict[ curr_user_name] = shared_constants.USER_URN_PREFIX + user_id # noqa: E501 own_users_set.remove(curr_user_name) # Stop searching if all needed names and ids found if len(own_users_set) == 0: break if len(own_users_set) > 0: raise Exception(f"No user ids found for: {list(own_users_set)}") return user_name_to_id_dict
def info(ctx, right_name): try: client = ctx.obj['client'] org = Org(client, href=ctx.obj['profiles'].get('org_href')) right_resource = org.get_right_resource(right_name) stdout(to_dict(right_resource), ctx) except Exception as e: stderr(e, ctx)
def info(ctx): try: client = ctx.obj['client'] amqp = AmqpService(client) settings = amqp.get_settings() stdout(to_dict(settings), ctx) except Exception as e: stderr(e, ctx)
def info(ctx, right_name): try: restore_session(ctx) client = ctx.obj['client'] org = Org(client, href=ctx.obj['profiles'].get('org_href')) right_resource = org.get_right_resource(right_name) stdout(to_dict(right_resource), ctx) except Exception as e: stderr(e, ctx)
def info(ctx): try: restore_session(ctx) client = ctx.obj['client'] amqp = AmqpService(client) settings = amqp.get_settings() stdout(to_dict(settings), ctx) except Exception as e: stderr(e, ctx)
def list_extensions(self): """Return the API extensions defined in the system. :return: (dict): list with the API extensions defined in the system. """ query = self.client.get_typed_query( self.TYPE_NAME, query_result_format=QueryResultFormat.ID_RECORDS) return [to_dict(r, self.ATTRIBUTES) for r in query.execute()]
def info(ctx, catalog_name, item_name): try: client = ctx.obj['client'] org_name = ctx.obj['profiles'].get('org') in_use_org_href = ctx.obj['profiles'].get('org_href') org = Org(client, in_use_org_href, org_name == 'System') if item_name is None: catalog = org.get_catalog(catalog_name) result = to_dict(catalog) 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)
def get_extension(self, name): """Return the info about an API extension. :param name: (str): The name of the extension service. :return: (dict): dictionary with the information about the extension. """ ext = self.client.get_typed_query( self.TYPE_NAME, equality_filter=('name', name), query_result_format=QueryResultFormat.ID_RECORDS).find_unique() return to_dict(ext, self.ATTRIBUTES)
def list_extensions(self): """Fetch the API extensions defined in the system. :return: all the API extensions defined in the system. :rtype: dict """ query = self.client.get_typed_query( ResourceType.ADMIN_SERVICE, query_result_format=QueryResultFormat.ID_RECORDS) return [to_dict(r, self.ATTRIBUTES) for r in query.execute()]
def get_vm_dict(self, vapp_name, vm_name): q = self.client.get_typed_query('vm', QueryResultFormat.ID_RECORDS, qfilter='containerName==' + vapp_name) vms = list(q.execute()) for vm in vms: vm_dict = to_dict(vm) if vm_dict['name'] == vm_name: second_dict = self.vm_to_dict(vapp_name, vm_name) return dict(vm_dict, **second_dict) return None
def list_nsxt(ctx): try: restore_session(ctx) client = ctx.obj['client'] platform = Platform(client) query = platform.list_nsxt_managers() result = [] for record in list(query): result.append(to_dict(record, exclude=['href'])) stdout(result, ctx) except Exception as e: stderr(e, ctx)
def list_vapps(ctx, name, filter): try: restore_session(ctx, vdc_required=True) client = ctx.obj['client'] result = [] records = [] if name is None: if is_sysadmin(ctx): resource_type = ResourceType.ADMIN_VAPP.value else: resource_type = ResourceType.VAPP.value name = None attributes = None else: if name is not None: if is_sysadmin(ctx): resource_type = ResourceType.ADMIN_VM.value else: resource_type = ResourceType.VM.value if filter is None: filter = 'containerName==' + name attributes = [ 'name', 'containerName', 'ipAddress', 'status', 'memoryMB', 'numberOfCpus' ] else: filter = 'name==' + name + ';' + filter resource_type = ResourceType.ADMIN_VAPP.value attributes = [ 'isDeployed', 'isEnabled', 'memoryAllocationMB', 'name', 'numberOfCpus', 'numberOfVMs', 'ownerName', 'status', 'storageKB', 'vdcName' ] vdc_href = ctx.obj['profiles'].get('vdc_href') vdc = VDC(client, href=vdc_href) records = vdc.list_vapp_details(resource_type, filter) 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 __process_vapp(self, org_name, vdc_name, vapp_name, vdc, vapp): res = [] # VApp details resource_type = vcd.ResourceType.VAPP.value vapp_list = vdc.list_vapp_details(resource_type, 'name==' + vapp_name) rec = to_dict(vapp_list[0]) rec["orgName"] = org_name logging.debug("new vapp name={}".format(rec["name"])) res.append( self.new_record( 'vapp', { "created": rec["creationDate"], "name": rec["name"], "id": rec["name"], # TODO: should be smth. better "cluster": rec["vdcName"], "project": rec["vdcName"], "cpus": int(rec.get("numberOfCpus") or 0), "memory": int(rec.get("memoryAllocationMB") or 0), "storage": int(rec.get("storageKB") or 0) // 1024, "os": "VMWare VApp", "os_family": None, "status": rec["status"], "is_on": (vapp.is_powered_on() and 1 or 0), "owner": rec["ownerName"] }, rec)) # process VMs resource_type = vcd.ResourceType.VM.value try: vm_list = vdc.list_vapp_details(resource_type, 'containerName==' + vapp_name) except: logging.error( "failed to get VM list for vapp={}".format(vapp_name)) return [res] with concurrent.futures.ThreadPoolExecutor( max_workers=self.options["tasks"] or 1) as executor: futures = [] for vm_def in vm_list: futures.append( executor.submit(self.__process_vmlist_vm, org_name, vdc_name, vapp_name, vdc, vapp, vm_def, resource_type)) for future in concurrent.futures.as_completed(futures): res.append(future.result()) return res
def list_rights_of_org(self): """Retrieves the list of rights associated with the Organization. :return: (list): (RightReference) List of rights """ org_admin_resource = self.client.get_resource(self.href_admin) rights = [] if hasattr(org_admin_resource, 'RightReferences') and \ hasattr(org_admin_resource.RightReferences, 'RightReference'): for rightReference in \ org_admin_resource.RightReferences.RightReference: rights.append(to_dict(rightReference, exclude=['type'])) return rights
def list_roles(self): """ Retrieve the list of role in the current Org :return: List of roles in the current Org """ # NOQA roles_query, resource_type = self.get_roles_query() result = [] for r in list(roles_query.execute()): result.append( to_dict(r, resource_type=resource_type, exclude=['org', 'orgName', 'href'])) return result
def info(ctx, catalog_name, item_name): try: 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) access_control_settings = access_settings_to_dict( org.get_catalog_access_settings(catalog_name)) result.update(access_control_settings) 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)
def get_extension(self, name, namespace=None): """Return the info about an API extension. :param name: (str): The name of the extension service. :param namespace: (str): The namespace of the extension service. If None, it will use the value defined by the `name` parameter. :return: (dict): dictionary with the information about the extension. """ ext = self.client.get_typed_query( self.TYPE_NAME, qfilter='name==%s;namespace==%s' % (name, namespace if namespace else name), query_result_format=QueryResultFormat.ID_RECORDS).find_unique() return to_dict(ext, self.ATTRIBUTES)
def list_tasks(ctx, status): try: client = ctx.obj['client'] task_obj = Task(client) records = task_obj.list_tasks(filter_status_list=status) result = [] for r in records: result.append( to_dict(r, attributes=[ 'name', 'status', 'objectName', 'ownerName', 'orgName', 'startDate', 'serviceNamespace', 'id' ])) stdout(result, ctx, show_id=True) except Exception as e: stderr(e, ctx)
def list_extensions(self): """Fetch the API extension services defined in the system. :return: all the registered API extension services in the system. :rtype: list """ try: records = self.client.get_typed_query( ResourceType.ADMIN_SERVICE.value, query_result_format=QueryResultFormat.ID_RECORDS).execute() except OperationNotSupportedException: msg = 'User doesn\'t have permission to view extensions.' raise OperationNotSupportedException(msg) return [to_dict(r, self.ATTRIBUTES) for r in records]
def list_catalogs(self): if self.is_admin: resource_type = 'adminCatalog' else: resource_type = 'catalog' result = [] q = self.client.get_typed_query( resource_type, query_result_format=QueryResultFormat.ID_RECORDS) records = list(q.execute()) if len(records) > 0: for r in records: result.append( to_dict(r, resource_type=resource_type, exclude=['owner', 'org'])) return result
def list_extensions(self): """Fetch the API extension services defined in the system. :return: all the registered API extension services in the system. :rtype: list """ try: records = self.client.get_typed_query( ResourceType.ADMIN_SERVICE.value, query_result_format=QueryResultFormat.ID_RECORDS).execute() except OperationNotSupportedException as e: msg = 'User doesn\'t have permission to view extensions.' raise OperationNotSupportedException(msg) return [to_dict(r, self.ATTRIBUTES) for r in records]
def list_vapps(ctx): try: client = ctx.obj['client'] result = [] resource_type = 'adminVApp' if is_admin(ctx) else 'vApp' q = client.get_typed_query( resource_type, query_result_format=QueryResultFormat.ID_RECORDS) 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, show_id=False) except Exception as e: stderr(e, ctx)
def __process_vdc(self, org_name, vdc_name, vdc): res = [] vdc.get_resource() rec = self.__to_dict(vdc.resource) # get more info query_filter = ('name', vdc_name) query = self.client.get_typed_query( ResourceType.ORG_VDC.value, query_result_format=QueryResultFormat.RECORDS, equality_filter=query_filter) result = list(query.execute()) if len(result) == 1: rec_detail = to_dict(result[0]) rec = {**rec_detail, **rec} else: logging.warning( "Failed to fetch ORG_VDC reconrd for vdc name ={}".format( vdc_name)) logging.debug("new vdc name={}".format(vdc_name)) res.append( self.new_record( 'vdc', { "name": vdc_name, "cluster": org_name, "description": rec.get("description"), }, rec)) res_list = vdc.list_resources(vcd.EntityType.VAPP) for vapp_def in res_list: vapp_name = vapp_def["name"] try: vapp_res = vdc.get_vapp(vapp_name) vapp = vcdVApp(self.client, resource=vapp_res) res.extend( self.__process_vapp(org_name, vdc_name, vapp_name, vdc, vapp)) except Exception as e: logging.exception( "Exception while processing VApp = {}".format(vapp_name)) pass if TEST: break return res
def list_catalogs(self): if self.client.is_sysadmin(): resource_type = 'adminCatalog' else: resource_type = 'catalog' result = [] q = self.client.get_typed_query( resource_type, query_result_format=QueryResultFormat.ID_RECORDS) records = list(q.execute()) if len(records) > 0: for r in records: result.append( to_dict( r, resource_type=resource_type, exclude=['owner', 'org'])) return result
def list_tasks(ctx, status): try: restore_session(ctx) client = ctx.obj['client'] task_obj = Task(client) records = task_obj.list_tasks(filter_status_list=status) result = [] for r in records: result.append( to_dict( r, attributes=[ 'name', 'status', 'objectName', 'ownerName', 'orgName', 'startDate', 'serviceNamespace', 'id' ])) stdout(result, ctx, show_id=True) except Exception as e: stderr(e, ctx)
def get_extension(self, name, namespace=None): """Fetch info about a particular API extension service. :param str name: the name of the extension service whose info we want to retrieve. :param str namespace: the namespace of the extension service. :return: information about the extension service. :rtype: dict :raises MissingRecordException: if a service with the given name and namespace couldn't be found. :raise MultipleRecordsException: if more than one service with the given name and namespace are found. """ ext_record = self._get_extension_record(name, namespace) return to_dict(ext_record, self.ATTRIBUTES)
def get_org_user_names(client: vcd_client.Client, org_name): """Get a set of user names in an org. :param vcd_client.Client client: current client :param str org_name: org name to search for users :return: set of user names :rtype: set """ org_href = client.get_org_by_name(org_name).get('href') org = vcd_org.Org(client, org_href) str_elem_users: list = org.list_users() user_names: set = set() for user_str_elem in str_elem_users: curr_user_dict = to_dict(user_str_elem, exclude=[]) user_name = curr_user_dict['name'] user_names.add(user_name) return user_names
def list_users(self): org_name = self.params.get('org_name') response = dict() org_details = dict() response['users'] = list() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) org_user_list = org.list_users() resource_type = ResourceType.USER.value if self.client.is_sysadmin(): resource_type = ResourceType.ADMIN_USER.value for org_user in org_user_list: response['users'].append( to_dict(org_user, resource_type=resource_type, exclude=[])) return response
def list_users(ctx, org_name): try: 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)
def __process_vm(self, org_name, vdc_name, vapp_name, vm_name, vdc, vapp, vm): # VM details vm.get_resource() rec = to_dict(vm.resource) rec_detail = vm_to_dict(vm.resource) rec = {**rec, **rec_detail} # special handling for disks for disk in vm.resource.VmSpecSection.DiskSection.DiskSettings: rec_disk = self.__to_dict(disk) rec_disk["id"] = str(disk["DiskId"]) rec_disk_key = "disk-" + rec_disk["id"] rec[rec_disk_key] = {**rec[rec_disk_key], **rec_disk} rec["orgName"] = org_name rec["vdcName"] = vdc_name rec["vappName"] = vapp_name rec["vapp"] = vapp_name return rec
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)
def list_rights_available_in_system(self, name_filter=None): """Retrieves the list of all rights available in the System. :param name_filter: (tuple): (name ,'right name') Filter the rights by 'right name' :return: (list): (RightRecord) List of rights """ if self.resource is None: self.resource = self.client.get_resource(self.href) resource_type = 'right' query = self.client.get_typed_query( resource_type, query_result_format=QueryResultFormat.RECORDS, equality_filter=name_filter) records = list(query.execute()) result = [] if len(records) > 0: for r in records: result.append( to_dict(r, resource_type=resource_type, exclude=[])) return result
# Ensure user exists on the org. try: user_resource = org.get_user(cfg.user['name']) print("User already exists: {0}".format(cfg.user['name'])) except Exception: print("User does not exist, creating: {0}".format(cfg.user['name'])) role_record = org.get_role_record(cfg.user['role']) user_resource = org.create_user(user_name=cfg.user['name'], password=cfg.user['password'], role_href=role_record.get('href')) print("User now exists: {0}".format(user_resource.get('name'))) # Ensure the user is enabled. We could also do so when creating the user # but this approach will also fix an existing user who is disabled. user_dict = to_dict(user_resource) if user_dict.get('IsEnabled') == 'true': print("User is enabled: {0}".format(user_dict.get('name'))) else: print("User is not enabled, enabling...") org.update_user(user_name=user_dict.get('name'), is_enabled=True) print("User is now enabled: {0}".format(user_dict.get('name'))) # Ensure VDC exists. If we create it reload the org as it affects # org resource contents and future calls might fail otherwise. try: vdc_resource = org.get_vdc(cfg.vdc['vdc_name']) vdc = VDC(client, resource=vdc_resource) print("VDC already exists: {0}".format(vdc.name)) except Exception: print("VDC does not exist, creating: {0}".format(cfg.vdc['vdc_name']))
def stdout(obj, ctx=None, alt_text=None, show_id=False, sort_headers=True): global last_message last_message = '' o = obj if ctx is not None and \ 'json_output' in ctx.find_root().params and \ ctx.find_root().params['json_output']: if isinstance(obj, str): o = {'message': obj} text = json.dumps(o, sort_keys=True, indent=4, separators=(',', ': ')) if sys.version_info[0] < 3: text = str(text, 'utf-8') if ctx.find_root().params['is_colorized']: click.echo( highlight(text, lexers.JsonLexer(), formatters.TerminalFormatter())) else: click.echo(text) else: if alt_text is not None: text = alt_text elif isinstance(obj, str): text = o else: if 'task_href' in obj: obj = ctx.obj['client'].get_resource(obj.get('task_href')) if isinstance(obj, ObjectifiedElement): if obj.tag == '{' + NSMAP['vcloud'] + '}Task': if ctx is not None and \ 'no_wait' in ctx.find_root().params and \ ctx.find_root().params['no_wait']: text = as_prop_value_list(obj, show_id=show_id) else: client = ctx.obj['client'] task = client.get_task_monitor().wait_for_status( task=obj, timeout=60, poll_frequency=5, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED ], callback=task_callback) if task.get('status') == TaskStatus.ERROR.value: text = 'task: %s, result: %s, message: %s' % \ (extract_id(task.get('id')), task.get('status'), task.Error.get('message')) # TODO(should return != 0) else: text = 'task: %s, %s, result: %s' % \ (extract_id(task.get('id')), task.get('operation'), task.get('status')) elif ctx.command.name == 'list' and \ isinstance(obj, collections.Iterable): text = as_table(obj) elif ctx.command.name == 'info': text = as_table( [{ 'property': k, 'value': v } for k, v in sorted(to_dict(obj).items())], show_id=show_id) else: text = as_table(to_dict(obj), show_id=show_id) elif not isinstance(obj, list): obj1 = {} for k, v in obj.items(): if type(v) in [list, tuple]: value = ''.join('%s\n' % x for x in v) elif type(v) is dict: value = ''.join( '%s: %s\n' % (x, y) for x, y in v.items()) else: value = v obj1[k] = value text = as_prop_value_list(obj1, show_id=show_id) else: text = as_table( obj, show_id=show_id, sort_headers=sort_headers) click.echo('\x1b[2K\r' + text)
def search(ctx, resource_type, query_filter): """Search for resources in vCloud Director. \b Description Search for resources of the provided type. Resource type is not case sensitive. When invoked without a resource type, list the available types to search for. Admin types are only allowed when the user is the system administrator. \b Filters can be applied to the search. \b Examples vcd search lists available resource types. \b vcd search task Search for all tasks in current organization. \b vcd search task --filter 'status==running' Search for running tasks in current organization. \b vcd search admintask --filter 'status==running' Search for running tasks in all organizations, system administrator only. \b vcd search task --filter 'id==ffb96443-d7f3-4200-825d-0f297388ebc0' Search for a task by id \b vcd search vapp Search for vApps. \b vcd search vapp -f 'metadata:cse.node.type==STRING:master' Search for vApps by metadata. \b vcd search vapp -f \\ 'metadata:vapp.origin.name==STRING:photon-custom-hw11-2.0-304b817.ova' Search for vApps instantiated from template \b vcd search vapp -f \\ 'numberOfCpus=gt=4;memoryAllocationMB=gt=10000;storageKB=gt=10000000' Search for resource intensive vApps \b vcd search vm Search for virtual machines. """ try: if resource_type is None: click.secho(ctx.get_help()) click.echo('\nAvailable resource types:') click.echo(tabulate(tabulate_names(RESOURCE_TYPES, 4))) return restore_session(ctx) client = ctx.obj['client'] result = [] resource_type_cc = to_camel_case(resource_type, RESOURCE_TYPES) q = client.get_typed_query( resource_type_cc, query_result_format=QueryResultFormat.ID_RECORDS, qfilter=query_filter) 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_cc)) stdout(result, ctx, show_id=True) except Exception as e: stderr(e, ctx)