def execute(self): """Execute the action command.""" args = self.arguments opts = self.options if not (TypeHelper.isKnownType(args[0])) and \ ParseHelper.getXmlType(args[0]) == None: self.error(Messages.Error.NO_SUCH_TYPE % args[0]) # scope = '%s:%s' % (ParseHelper.getXmlWrapperType(args[0]), args[2]) actionable_types = TypeHelper.get_actionable_types( expendNestedTypes=True, groupOptions=True) resource = self.get_object(args[0], args[1], self.resolve_base(opts), context_variants=actionable_types[args[0]]) if resource is None: self.error(Messages.Error.NO_SUCH_OBJECT % (args[0], args[1])) elif hasattr(resource, args[2]) and \ type(getattr(resource, args[2])) == types.MethodType: try: result = self.execute_method(resource, args[2], opts) except Exception, e: self.error(str(e)) if result.status.state == 'failed': self.error(Messages.Info.ACTION_STATUS % result.status.state)
def __add_resource_specific_arguments(self, obj, specific_options, line, key=None): gdt = TypeHelper.getDecoratorType obj_type = gdt(TypeHelper.to_singular(obj)) args = TypeHelper.get_actionable_types(expendNestedTypes=True) gom = MethodHelper.get_object_methods actions = [] method = self.__get_method_name_by_args(obj, line.split(' '), args, line) # collect resource args if yet not used if not method and obj_type and hasattr(brokers, obj_type): #add base resource actions actions = gom(getattr(brokers, obj_type), exceptions=self.complete_exceptions) if args.has_key(obj) and args[obj]: #add sub-resources actions self.__add_sub_resourse_actions(obj, args, line, actions) specific_options[obj if key == None else key] = actions
def get_object(self, typ, obj_id, base=None, opts={}, context_variants=[]): """Return an object by id or name.""" self.check_connection() connection = self.context.connection if base: options = self.get_options(method='get', resource=base, as_params_collection=True, context_variants=context_variants) else: options = self.get_options(method='get', resource=typ, as_params_collection=True, context_variants=context_variants) base = connection self.validate_options(opts, options) candidate = typ if typ is not None and isinstance(typ, type('')) \ else type(typ).__name__.lower() if hasattr(base, TypeHelper.to_plural(candidate)): coll = getattr(base, TypeHelper.to_plural(candidate)) else: err_str = Messages.Error.NO_SUCH_TYPE_OR_ARS_NOT_VALID if context_variants: err_str = err_str + (Messages.Info.POSSIBALE_ARGUMENTS_COMBINATIONS % str(context_variants)) self.error(err_str % candidate) if obj_id is not None: _, kwargs = self._get_query_params(opts) obj = self.__get_by_id(coll, obj_id, kwargs) if obj is not None: return obj obj = self.__get_by_name(coll, obj_id, kwargs) if obj is not None: return obj obj = self.__get_by_alias(coll, obj_id, kwargs) if obj is not None: return obj return None if 'id' in options: obj_id, kwargs = self._get_query_params(opts, query_arg='--id') if obj_id is not None: return self.__get_by_id(coll, obj_id, kwargs) if 'name' in options: obj_id, kwargs = self._get_query_params(opts, query_arg='--name') if obj_id is not None: return self.__get_by_name(coll, obj_id, kwargs) if 'alias' in options: obj_id, kwargs = self._get_query_params(opts, query_arg='--alias') if obj_id is not None: return self.__get_by_alias(coll, obj_id, kwargs) self.error(Messages.Error.NO_ID % 'show')
def resolve_base(self, options): """ Resolves a base object from a set of '--type-(identifier|name) value' options. """ collection_candidate = self.check_connection() parnet_candidate_locator = 0 base = None parnet_candidates = [ key for key in options.keys() if re.match(r"--(.+)-(identifier|name)$", key) ] parnet_candidates_permutations = list( itertools.permutations(parnet_candidates)) if parnet_candidates_permutations[0]: for combination in parnet_candidates_permutations: for item in combination: key = item val = options[key] parnet_candidate_locator += 1 typename = re.sub(r"--(.+)-(identifier|name)$", r"\1", key) coll = TypeHelper.to_plural(typename) if not (TypeHelper.isKnownType(typename) or TypeHelper.isKnownType(coll)): self.error(Messages.Error.NO_SUCH_TYPE % typename) if hasattr(collection_candidate, coll): coll_ins = getattr(collection_candidate, coll) if hasattr(coll_ins, 'get'): if not val: self.error(Messages.Error.INVALID_OPTION % key) if key.endswith('-identifier'): base = coll_ins.get(id=val) elif key.endswith('-name'): base = coll_ins.get(name=val) if not base: if len(combination) > parnet_candidate_locator: continue else: self.error(Messages.Error.NO_SUCH_OBJECT % (typename, val)) if len(parnet_candidates) == parnet_candidate_locator: return base else: collection_candidate = base self.error(Messages.Error.CANNOT_CONSTRUCT_COLLECTION_MEMBER_VIEW % str(parnet_candidates_permutations))
def __add_resource_specific_options(self, obj, specific_options, line, key=None): obj_coll_type = TypeHelper.getDecoratorType(TypeHelper.to_plural(obj)) if obj_coll_type: if hasattr(brokers, obj_coll_type): obj_coll = getattr(brokers, obj_coll_type) if obj_coll and hasattr(obj_coll, AddCmdShell.NAME): method_args = MethodHelper.get_documented_arguments(method_ref=getattr(obj_coll, AddCmdShell.NAME), as_params_collection=True, spilt_or=True) if method_args: specific_options[obj if key == None else key] = method_args
def __add_resource_specific_options(self, obj, specific_options, line, key=None): obj_type = TypeHelper.getDecoratorType(TypeHelper.to_singular(obj)) if obj_type and hasattr(brokers, obj_type): obj_typ_ref = getattr(brokers, obj_type) if obj_typ_ref and hasattr(obj_typ_ref, RemoveCmdShell.ALIAS): method_args = MethodHelper.get_documented_arguments( method_ref=getattr(obj_typ_ref, RemoveCmdShell.ALIAS), as_params_collection=True, spilt_or=True ) if method_args: specific_options[key if key is not None else obj] = method_args
def __add_resource_specific_options(self, obj, specific_options, line, key=None): obj_coll_type = TypeHelper.getDecoratorType(TypeHelper.to_plural(obj)) if obj_coll_type: if hasattr(brokers, obj_coll_type): obj_coll = getattr(brokers, obj_coll_type) if obj_coll and hasattr(obj_coll, ShowCmdShell.ALIAS): method_args = MethodHelper.get_documented_arguments(method_ref=getattr(obj_coll, ShowCmdShell.ALIAS), as_params_collection=True, spilt_or=True) if method_args: specific_options[obj if key == None else key] = method_args
def __add_resource_specific_options(self, obj, specific_options, line, key=None): typ = TypeHelper.getDecoratorType(obj) if typ: plur_obj = TypeHelper.to_plural(typ) if hasattr(brokers, plur_obj): method_args = MethodHelper.getMethodArgs( brokers, plur_obj, ListCmdShell.NAME, True, True, True) if method_args: specific_options[obj if key == None else key] = method_args
def __add_resource_specific_options(self, obj, specific_options, line, key=None): typ = TypeHelper.getDecoratorType(obj) if typ: plur_obj = TypeHelper.to_plural(typ) if hasattr(brokers, plur_obj): method_args = MethodHelper.getMethodArgs(brokers, plur_obj, ListCmdShell.NAME, True, True, True) if method_args: specific_options[obj if key == None else key] = method_args
def resolve_base(self, options): """ Resolves a base object from a set of parent identifier options. """ collection_candidate = self.check_connection() parnet_candidate_locator = 0 base = None parnet_candidates = [ key for key in options.keys() if OptionHelper.is_parent_id_option(key) ] parnet_candidates_permutations = list(itertools.permutations(parnet_candidates)) if parnet_candidates_permutations[0]: for combination in parnet_candidates_permutations: for item in combination: key = item val = options[key] parnet_candidate_locator += 1 typename = OptionHelper.get_parent_id_type(key) coll = TypeHelper.to_plural(typename) if not (TypeHelper.isKnownType(typename) or TypeHelper.isKnownType(coll)): self.error(Messages.Error.NO_SUCH_TYPE % typename) if hasattr(collection_candidate, coll): coll_ins = getattr(collection_candidate, coll) if hasattr(coll_ins, 'get'): if not val: self.error(Messages.Error.INVALID_OPTION % key) if key.endswith('-identifier'): base = coll_ins.get(id=val) elif key.endswith('-name'): base = coll_ins.get(name=val) if not base: if len(combination) > parnet_candidate_locator: continue else: self.error(Messages.Error.NO_SUCH_OBJECT % (typename, val)) if len(parnet_candidates) == parnet_candidate_locator: return base else: collection_candidate = base self.error(Messages.Error.CANNOT_CONSTRUCT_COLLECTION_MEMBER_VIEW % str(parnet_candidates_permutations))
def show_help(self): """Show help for "list".""" self.check_connection() args = self.arguments opts = self.options subst = {} types = self.get_plural_types(method="list") if not args or self.is_supported_type(types.keys(), args[0]): subst["types"] = self.format_map(types) statuses = self.get_statuses() subst["statuses"] = self.format_list(statuses) if len(args) == 1 and len(opts) == 1: helptext = self.helptext subst["types"] = self.format_map({args[0]: types[args[0]]}) subst["type"] = args[0] elif len(args) == 1 and len(opts) > 1: helptext = self.helptext1 params_list = self.get_options( method="list", resource=TypeHelper.to_singular(args[0]), sub_resource=self.resolve_base(opts), context_variants=types[args[0]], ) subst["options"] = self.format_list(params_list) subst["type"] = args[0] else: helptext = self.helptext helptext = self.format_help(helptext, subst) self.write(helptext)
def show_help(self): """Show help for "list".""" self.check_connection() args = self.arguments opts = self.options subst = {} types = self.get_plural_types(method='list') if not args or self.is_supported_type(types.keys(), args[0]): subst['types'] = self.format_map(types) statuses = self.get_statuses() subst['statuses'] = self.format_list(statuses) if len(args) == 1 and len(opts) == 1: helptext = self.helptext subst['types'] = self.format_map({args[0]: types[args[0]]}) subst['type'] = args[0] elif len(args) == 1 and len(opts) > 1: helptext = self.helptext1 params_list = self.get_options( method='list', resource=TypeHelper.to_singular(args[0]), sub_resource=self.resolve_base(opts), context_variants=types[args[0]]) subst['options'] = self.format_list(params_list) subst['type'] = args[0] else: helptext = self.helptext helptext = self.format_help(helptext, subst) self.write(helptext)
def execute(self): """Execute the "update" command.""" args = self.arguments opts = self.options typs = TypeHelper.get_types_containing_method( 'update', expendNestedTypes=True, groupOptions=True ) resource = self.get_object( args[0], args[1], self.resolve_base(opts), context_variants=typs[args[0]] ) if resource is None: self.error( Messages.Error.NO_SUCH_OBJECT % (args[0], args[1]) ) elif hasattr(resource, 'update'): obj = self.update_object_data(self.__create_set_superclass(resource), opts) result = self.execute_method(obj, 'update', opts) else: self.error( Messages.Error.OBJECT_IS_IMMUTABLE % (args[0], args[1]) ) self.context.formatter.format(self.context, result)
def execute(self): """Execute the "add" command.""" args = self.arguments opts = self.options base = self.resolve_base(opts) typ = TypeHelper.to_plural(args[0]) collection = None typs = self.get_singular_types(method='add', typ=args[0]) if base: if hasattr(base, typ): collection = getattr(base, typ) else: connection = self.check_connection() if hasattr(connection, typ): collection = getattr(connection, typ) if collection != None: result = self.execute_method(collection, 'add', opts) self.context.formatter.format(self.context, result) else: err_str = Messages.Error.CANNOT_CREATE if typs: err_str = err_str + \ (Messages.Info.POSSIBALE_ARGUMENTS_COMBINATIONS % str(typs)) self.error(err_str % (args[0], typ))
def execute(self): """Execute the "add" command.""" args = self.arguments opts = self.options base = self.resolve_base(opts) typ = TypeHelper.to_plural(args[0]) collection = None typs = self.get_singular_types(method='add', typ=args[0]) if base: if hasattr(base, typ): collection = getattr(base, typ) else: connection = self.check_connection() if hasattr(connection, typ): collection = getattr(connection, typ) if collection != None: result = self.execute_method(collection, 'add', opts) self.context.formatter.format(self.context, result) else: err_str = Messages.Error.CANNOT_CREATE if typs: err_str = err_str + \ (Messages.Info.POSSIBALE_ARGUMENTS_COMBINATIONS % str(typs)) self.error( err_str % (args[0], typ) )
def complete_update(self, text, line, begidx, endidx): args = TypeHelper.get_types_containing_method(UpdateCmdShell.NAME, expendNestedTypes=True) specific_options = self.get_resource_specific_options(args, line, callback=self.__add_resource_specific_options) return AutoCompletionHelper.complete(line, text, args, specific_options=specific_options)
def execute(self): """Execute "remove".""" args = self.arguments opts = self.options typs = TypeHelper.get_types_containing_method( RemoveCommand.aliases[0], expendNestedTypes=True, groupOptions=True ) resource = self.get_object( args[0], args[1], self.resolve_base(opts), context_variants=typs[args[0]] ) if resource is None: self.error( Messages.Error.NO_SUCH_OBJECT % (args[0], args[1]) ) elif hasattr(resource, RemoveCommand.aliases[0]): result = self.execute_method( resource, RemoveCommand.aliases[0], opts ) else: self.error( Messages.Error.OBJECT_IS_IMMUTABLE % (args[0], args[1]) ) if not result: self.write(Messages.Info.ACCEPTED) else: self.context.formatter.format(self.context, result)
def execute(self): """Execute "remove".""" args = self.arguments opts = self.options typs = TypeHelper.get_types_containing_method(RemoveCommand.aliases[0], expendNestedTypes=True, groupOptions=True) resource = self.get_object(args[0], args[1], self.resolve_base(opts), context_variants=typs[args[0]]) if resource is None: self.error(Messages.Error.NO_SUCH_OBJECT % (args[0], args[1])) elif hasattr(resource, RemoveCommand.aliases[0]): result = self.execute_method(resource, RemoveCommand.aliases[0], opts) else: self.error(Messages.Error.OBJECT_IS_IMMUTABLE % (args[0], args[1])) if not result: self.write(Messages.Info.ACCEPTED) else: self.context.formatter.format(self.context, result)
def __get_action_args(self, line): args = TypeHelper.get_actionable_types(expendNestedTypes=True) spl = line.rstrip().split(' ') gom = MethodHelper.get_object_methods gdt = TypeHelper.getDecoratorType if len(spl) >= 3: new_cons = '' obj = spl[1].strip() #top level resource in possibilities if args.has_key( obj) and args[obj] and args[obj].find('None') != -1: act = spl[3].strip() if len(spl) > 3 \ else spl[-1].strip() #possibilities refer only to the sub-resource else: for item in spl: if item.endswith('-identifier'): args[obj] = new_cons return args return args for cons in args[obj].split(', '): if cons == 'None': obj_type = gdt(obj) if not obj_type: continue actions = gom(getattr(brokers, obj_type), exceptions=self.complete_exceptions) if actions and act in actions: new_cons += 'None, ' else: tmp_spl = spl[:] tmp_spl.append(self.identifier_template % cons) base = self._resolve_base(tmp_spl[1:]) if base: obj_type = gdt(TypeHelper.to_singular(base)) if not obj_type: continue actions = gom(getattr(brokers, obj_type), exceptions=self.complete_exceptions) if actions and act in actions: new_cons += cons + ', ' args[obj] = new_cons[:len(new_cons) - 2] if len(new_cons) > 3 \ else '' return args
def __add_resource_specific_options(self, obj, specific_options, line, key=None): obj_type = TypeHelper.getDecoratorType(TypeHelper.to_singular(obj)) if obj_type and hasattr(brokers, obj_type): obj_typ_ref = getattr(brokers, obj_type) if obj_typ_ref and hasattr(obj_typ_ref, UpdateCmdShell.NAME): method_args = MethodHelper.get_documented_arguments( method_ref=getattr(obj_typ_ref, UpdateCmdShell.NAME), as_params_collection=True, spilt_or=True) if method_args: specific_options[ key if key is not None else obj] = method_args
def __get_action_args(self, line): args = TypeHelper.get_actionable_types(expendNestedTypes=True) spl = line.rstrip().split(' ') gom = MethodHelper.get_object_methods gdt = TypeHelper.getDecoratorType if len(spl) >= 3: new_cons = '' obj = spl[1].strip() #top level resource in possibilities if args.has_key(obj) and args[obj] and args[obj].find('None') != -1: act = spl[3].strip() if len(spl) > 3 \ else spl[-1].strip() #possibilities refer only to the sub-resource else: for item in spl: if item.endswith('-identifier'): args[obj] = new_cons return args return args for cons in args[obj].split(', '): if cons == 'None': obj_type = gdt(obj) if not obj_type: continue actions = gom(getattr(brokers, obj_type), exceptions=self.complete_exceptions) if actions and act in actions: new_cons += 'None, ' else: tmp_spl = spl[:] tmp_spl.append(self.identifier_template % cons) base = self._resolve_base(tmp_spl[1:]) if base: obj_type = gdt(TypeHelper.to_singular(base)) if not obj_type: continue actions = gom(getattr(brokers, obj_type), exceptions=self.complete_exceptions) if actions and act in actions: new_cons += cons + ', ' args[obj] = new_cons[:len(new_cons) - 2] if len(new_cons) > 3 \ else '' return args
def get_plural_types(self, method, typ=None, expendNestedTypes=True, groupOptions=True): """Return a list of plural types.""" typs = TypeHelper.get_types_by_method(True, method, expendNestedTypes, groupOptions) if typ: if typs.has_key(typ): return typs[typ] else: return [] else: return typs
def is_remove_argument(self, line, key): args = TypeHelper.get_types_containing_method(RemoveCmdShell.ALIAS, expendNestedTypes=True) if key in args: return True specific_options = self.get_resource_specific_options(args, line, callback=self.__add_resource_specific_options) for arg_key in specific_options.keys(): if key in specific_options[arg_key]: return True return False
def complete_list(self, text, line, begidx, endidx): args = TypeHelper.get_types_by_method(True, ListCmdShell.NAME, expendNestedTypes=True) specific_options = self.get_resource_specific_options(args, line, callback=self.__add_resource_specific_options) return AutoCompletionHelper.complete(line, text, args=args, common_options=ListCmdShell.OPTIONS, specific_options=specific_options)
def complete_update(self, text, line, begidx, endidx): args = TypeHelper.get_types_containing_method(UpdateCmdShell.NAME, expendNestedTypes=True) specific_options = self.get_resource_specific_options( args, line, callback=self.__add_resource_specific_options) return AutoCompletionHelper.complete(line, text, args, specific_options=specific_options)
def complete_show(self, text, line, begidx, endidx): args = TypeHelper.get_types_by_method(False, ShowCmdShell.ALIAS, expendNestedTypes=True) specific_options = self.get_resource_specific_options(args, line, callback=self.__add_resource_specific_options) return AutoCompletionHelper.complete(line=line, text=text, args=args, specific_options=specific_options)
def is_add_argument(self, line, key): args = TypeHelper.get_types_by_method(False, AddCmdShell.NAME, expendNestedTypes=True) if key in args: return True specific_options = self.get_resource_specific_options(args, line, callback=self.__add_resource_specific_options) for arg_key in specific_options.keys(): if key in specific_options[arg_key]: return True return False
def show_help(self): """Show help for "remove".""" self.check_connection() args = self.arguments opts = self.options subst = {} types = TypeHelper.get_types_containing_method( RemoveCommand.aliases[0], expendNestedTypes=True, groupOptions=True) if not args or self.is_supported_type(types.keys(), args[0]): subst['types'] = self.format_map(types) statuses = self.get_statuses() subst['statuses'] = self.format_list(statuses) if len(args) == 2: base = self.resolve_base(self.options) obj = self.get_object(args[0], args[1], base, context_variants=types[args[0]]) if obj is None: self.error(Messages.Error.NO_SUCH_OBJECT % (args[0], args[1])) helptext = self.helptext1 params_list = self.get_options(method=RemoveCommand.aliases[0], resource=obj, sub_resource=base, context_variants=types[args[0]]) subst['options'] = self.format_list(params_list) subst['type'] = args[0] elif len(args) == 1 and len(opts) == 2: helptext = self.helptext1 subst['type'] = args[0] options = self.get_options(method=RemoveCommand.aliases[0], resource=args[0], sub_resource=self.resolve_base( self.options), context_variants=types[args[0]]) subst['options'] = self.format_list(options) subst['type'] = args[0] elif len(args) == 1: helptext = self.helptext subst['type'] = args[0] subst['types'] = self.format_map({args[0]: types[args[0]]}) else: helptext = self.helptext helptext = self.format_help(helptext, subst) self.write(helptext)
def __add_resource_specific_options(self, obj, specific_options, line, key=None): obj_coll_type = TypeHelper.getDecoratorType(TypeHelper.to_plural(obj)) if obj_coll_type: if hasattr(brokers, obj_coll_type): obj_coll = getattr(brokers, obj_coll_type) if obj_coll and hasattr(obj_coll, ShowCmdShell.ALIAS): method_args = MethodHelper.get_documented_arguments( method_ref=getattr(obj_coll, ShowCmdShell.ALIAS), as_params_collection=True, spilt_or=True) if method_args: method_args = [ x for x in method_args if x not in ['id', 'name'] ] specific_options[obj if key == None else key] = method_args
def complete_show(self, text, line, begidx, endidx): args = TypeHelper.get_types_by_method(False, ShowCmdShell.ALIAS, expendNestedTypes=True) specific_options = self.get_resource_specific_options( args, line, callback=self.__add_resource_specific_options) return AutoCompletionHelper.complete(line=line, text=text, args=args, specific_options=specific_options)
def is_remove_argument(self, line, key): args = TypeHelper.get_types_containing_method(RemoveCmdShell.ALIAS, expendNestedTypes=True) if key in args: return True specific_options = self.get_resource_specific_options( args, line, callback=self.__add_resource_specific_options) for arg_key in specific_options.keys(): if key in specific_options[arg_key]: return True return False
def __add_resource_specific_options(self, obj, specific_options, line, key=None): obj_type = TypeHelper.getDecoratorType(TypeHelper.to_singular(obj)) gda = MethodHelper.get_documented_arguments gat = TypeHelper.get_actionable_types memeber = key if key is not None else obj method_args = [] action = None if obj_type and hasattr(brokers, obj_type): action = self.__get_method_name_by_args(obj, line.split(' '), gat(expendNestedTypes=True), line) if action: obj_typ_ref = getattr(brokers, obj_type) if obj_typ_ref and hasattr(obj_typ_ref, action): method_args = gda(method_ref=getattr(obj_typ_ref, action), as_params_collection=True, spilt_or=True) if method_args: specific_options[memeber] = method_args
def complete_list(self, text, line, begidx, endidx): args = TypeHelper.get_types_by_method(True, ListCmdShell.NAME, expendNestedTypes=True) specific_options = self.get_resource_specific_options( args, line, callback=self.__add_resource_specific_options) return AutoCompletionHelper.complete( line, text, args=args, common_options=ListCmdShell.OPTIONS, specific_options=specific_options)
def show_help(self): """Show help for "show".""" self.check_connection() args = self.arguments opts = self.options subst = {} types = self.get_singular_types(method='get') if not args or self.is_supported_type(types.keys(), args[0]): subst['types'] = self.format_map(types) statuses = self.get_statuses() subst['statuses'] = self.format_list(statuses) if len(args) == 1: helptext = self.helptext1 params_list = self.get_options( method='get', resource=TypeHelper.to_singular(args[0]), sub_resource=self.resolve_base(opts), context_variants=types[args[0]] ) subst['options'] = self.format_list(params_list) subst['type'] = args[0] elif len(args) == 2: helptext = self.helptext1 subst['type'] = args[0] subst['id'] = args[1] base = self.resolve_base(opts) obj = self.get_object(args[0], args[1], base) if obj is None: self.error( Messages.Error.NO_SUCH_OBJECT % (args[0], args[1]) ) params_list = self.get_options( method='get', resource=obj, sub_resource=base, context_variants=types[args[0]] ) subst['options'] = self.format_list(params_list) else: helptext = self.helptext helptext = self.format_help(helptext, subst) self.write(helptext)
def execute(self): """Execute the action command.""" args = self.arguments opts = self.options if not (TypeHelper.isKnownType(args[0])) and \ ParseHelper.getXmlType(args[0]) == None: self.error( Messages.Error.NO_SUCH_TYPE % args[0] ) # scope = '%s:%s' % (ParseHelper.getXmlWrapperType(args[0]), args[2]) actionable_types = TypeHelper.get_actionable_types( expendNestedTypes=True, groupOptions=True ) resource = self.get_object( args[0], args[1], self.resolve_base(opts), context_variants=actionable_types[args[0]] ) if resource is None: self.error( Messages.Error.NO_SUCH_OBJECT % (args[0], args[1]) ) elif hasattr(resource, args[2]) and \ type(getattr(resource, args[2])) == types.MethodType: try: result = self.execute_method(resource, args[2], opts) except Exception, e: self.error(str(e)) if result.status.state == 'failed': self.error( Messages.Info.ACTION_STATUS % result.status.state )
def __add_sub_resourse_actions(self, obj, args, line, actions): gdt = TypeHelper.getDecoratorType gom = MethodHelper.get_object_methods if obj in args.keys(): for cons in args[obj].split(', '): spl = line.strip().split(' ') if cons != 'None': spl.append(self.identifier_template % cons) base = self._resolve_base(spl[1:]) if base: obj_type = gdt(TypeHelper.to_singular(base)) actions.extend(gom(getattr(brokers, obj_type), exceptions=self.complete_exceptions))
def __add_resource_specific_options(self, obj, specific_options, line, key=None): obj_type = TypeHelper.getDecoratorType(TypeHelper.to_singular(obj)) gda = MethodHelper.get_documented_arguments gat = TypeHelper.get_actionable_types memeber = key if key is not None else obj method_args = [] action = None if obj_type and hasattr(brokers, obj_type): action = self.__get_method_name_by_args( obj, line.split(' '), gat(expendNestedTypes=True), line) if action: obj_typ_ref = getattr(brokers, obj_type) if obj_typ_ref and hasattr(obj_typ_ref, action): method_args = gda(method_ref=getattr(obj_typ_ref, action), as_params_collection=True, spilt_or=True) if method_args: specific_options[memeber] = method_args
def get_collection(self, typ, opts={}, base=None, context_variants=[]): """retrieves collection members""" self.check_connection() connection = self.context.connection query, kwargs = self._get_query_params(opts) if base is None: if hasattr(connection, typ): options = self.get_options( method='list', resource=TypeHelper.to_singular(typ), as_params_collection=True) if query and 'query' not in options: self.error(Messages.Error.NO_QUERY_ARGS) if kwargs and 'kwargs' not in options: self.error(Messages.Error.NO_KWARGS % 'list') if query and kwargs: return getattr(connection, typ).list(query=query, **kwargs) if query: return getattr(connection, typ).list(query=query) if kwargs: return getattr(connection, typ).list(**kwargs) return getattr(connection, typ).list() else: if hasattr(base, typ): options = self.get_options(method='list', resource=getattr(base, typ), as_params_collection=True) if query and 'query' not in options: self.error(Messages.Error.NO_QUERY_ARGS) if kwargs and 'kwargs' not in options: self.error(Messages.Error.NO_KWARGS % 'list') if query and kwargs: return getattr(base, typ).list(query=query, **kwargs) if query: return getattr(base, typ).list(query=query) if kwargs: return getattr(base, typ).list(**kwargs) return getattr(base, typ).list() err_str = Messages.Error.NO_SUCH_COLLECTION if context_variants: err_str = err_str + (Messages.Info.POSSIBALE_ARGUMENTS_COMBINATIONS % str(context_variants)) self.error(err_str % typ)
def __add_sub_resourse_actions(self, obj, args, line, actions): gdt = TypeHelper.getDecoratorType gom = MethodHelper.get_object_methods if obj in args.keys(): for cons in args[obj].split(', '): spl = line.strip().split(' ') if cons != 'None': spl.append(self.identifier_template % cons) base = self._resolve_base(spl[1:]) if base: obj_type = gdt(TypeHelper.to_singular(base)) actions.extend( gom(getattr(brokers, obj_type), exceptions=self.complete_exceptions))
def get_collection(self, typ, opts={}, base=None, context_variants=[]): """retrieves collection members""" self.check_connection() connection = self.context.connection query, kwargs = self._get_query_params(opts) if base is None: if hasattr(connection, typ): options = self.get_options(method='list', resource=TypeHelper.to_singular(typ), as_params_collection=True) if query and 'query' not in options: self.error(Messages.Error.NO_QUERY_ARGS) if kwargs and 'kwargs' not in options: self.error(Messages.Error.NO_KWARGS % 'list') if query and kwargs: return getattr(connection, typ).list(query=query, **kwargs) if query: return getattr(connection, typ).list(query=query) if kwargs: return getattr(connection, typ).list(**kwargs) return getattr(connection, typ).list() else: if hasattr(base, typ): options = self.get_options(method='list', resource=getattr(base, typ), as_params_collection=True) if query and 'query' not in options: self.error(Messages.Error.NO_QUERY_ARGS) if kwargs and 'kwargs' not in options: self.error(Messages.Error.NO_KWARGS % 'list') if query and kwargs: return getattr(base, typ).list(query=query, **kwargs) if query: return getattr(base, typ).list(query=query) if kwargs: return getattr(base, typ).list(**kwargs) return getattr(base, typ).list() err_str = Messages.Error.NO_SUCH_COLLECTION if context_variants: err_str = err_str + (Messages.Info.POSSIBALE_ARGUMENTS_COMBINATIONS % str(context_variants)) self.error(err_str % typ)
def __expend_nested_type(type_name, module, method, expended_types): """Recursive method's args types resolution""" getMethodArgs = MethodHelper.getMethodArgs expend_nested_type = MethodHelper.__expend_nested_type from ovirtcli.utils.typehelper import TypeHelper typ = TypeHelper.getDecoratorType(type_name) if typ: expended_types_tmp = getMethodArgs(module, typ, method, drop_self=True) if len(expended_types_tmp) > 1: for item in expended_types_tmp: if item != type_name: expend_nested_type(item, module, method, expended_types) elif len(expended_types_tmp) > 0: expended_types.append(expended_types_tmp[0]) else: expended_types.append(type_name) return expended_types
def _resolve_base(self, args): """ Resolves a base object from a set of '--parent-type-identifier' or '--parent-type-name' options. """ parent_candidates = [item for item in args if OptionHelper.is_parent_id_option(item)] parent_candidates_permutations = list(itertools.permutations(parent_candidates)) if parent_candidates_permutations[0]: for combination in parent_candidates_permutations: candidates = [OptionHelper.get_parent_id_type(item) for item in combination if OptionHelper.is_parent_id_option(item)] candidate = (''.join(candidates) + args[0]).lower() dt = TypeHelper.getDecoratorType(candidate) if dt: return dt return None
def _resolve_base(self, args): """resolves a base object from a set of '--type-identifier value' options.""" PARENT_IDENTIFIER = '-identifier' parnet_candidates = [ item for item in args if item.endswith(PARENT_IDENTIFIER) ] parnet_candidates_permutations = list( itertools.permutations(parnet_candidates)) if parnet_candidates_permutations[0]: for combination in parnet_candidates_permutations: candidates = [ item[2:-11] for item in combination if item.endswith(PARENT_IDENTIFIER) ] candidate = (''.join(candidates) + args[0]).lower() dt = TypeHelper.getDecoratorType(candidate) if dt: return dt return None
def _resolve_base(self, args): """ Resolves a base object from a set of '--parent-type-identifier' or '--parent-type-name' options. """ parent_candidates = [ item for item in args if OptionHelper.is_parent_id_option(item) ] parent_candidates_permutations = list( itertools.permutations(parent_candidates)) if parent_candidates_permutations[0]: for combination in parent_candidates_permutations: candidates = [ OptionHelper.get_parent_id_type(item) for item in combination if OptionHelper.is_parent_id_option(item) ] candidate = (''.join(candidates) + args[0]).lower() dt = TypeHelper.getDecoratorType(candidate) if dt: return dt return None
def show_help(self): """Show help for the action command.""" args = self.arguments opts = self.options types = TypeHelper.get_actionable_types(expendNestedTypes=True, groupOptions=True) subst = {} if not args or self.is_supported_type(types.keys(), args[0]): if len(args) == 2 and len(opts) == 2: helptext = self.helptext1 subst['type'] = args[0] subst['id'] = args[1] base = self.resolve_base(self.options) obj = self.get_object(args[0], args[1], base, context_variants=types[args[0]]) if obj is None: self.error(Messages.Error.NO_SUCH_OBJECT % (args[1], args[1])) actions = self._get_action_methods(obj) subst['actions'] = self.format_list(actions) if len(args) == 3 and len(opts) == 2: helptext = self.helptext1 subst['type'] = args[0] subst['id'] = args[1] subst['action'] = args[0] base = self.resolve_base(self.options) obj = self.get_object(args[1], args[2], base, context_variants=types[args[0]]) if obj is None: self.error(Messages.Error.NO_SUCH_OBJECT % (args[0], args[1])) actions = self._get_action_methods(obj) if args[0] not in actions: self.error(Messages.Error.NO_SUCH_ACTION % args[2]) options = self.get_options(method=args[0], resource=obj, context_variants=types[args[0]]) subst['actions'] = self.format_list(actions) subst['options'] = self.format_list(options, bullet='', sort=False) elif len(args) == 1: helptext = self.helptext0 subst['types'] = self.format_map({args[0]: types[args[0]]}) subst['type'] = args[0] elif len(args) == 2: helptext = self.helptext1 subst['type'] = args[0] subst['id'] = args[1] base = self.resolve_base(opts) obj = self.get_object(args[0], args[1], base, context_variants=types[args[0]]) if obj is None: self.error(Messages.Error.NO_SUCH_OBJECT % (args[0], args[1])) actions = self._get_action_methods(obj) subst['actions'] = self.format_list(actions) elif len(args) == 3: helptext = self.helptext1 subst['type'] = args[0] subst['id'] = args[1] subst['action'] = args[2] base = self.resolve_base(self.options) obj = self.get_object(args[0], args[1], base, context_variants=types[args[0]]) if obj is None: self.error(Messages.Error.NO_SUCH_OBJECT % (args[0], args[1])) actions = self._get_action_methods(obj) if args[2] not in actions: self.error(Messages.Error.NO_SUCH_ACTION % args[2]) options = self.get_options(method=args[2], resource=obj, sub_resource=base, context_variants=types[args[0]]) subst['actions'] = self.format_list(actions) subst['options'] = self.format_list(options, bullet='', sort=False) else: helptext = self.helptext0 subst['types'] = self.format_map(types) # scope = '%s:%s' % (type(obj).__name__, args[2]) statuses = self.get_statuses() subst['statuses'] = self.format_list(statuses) helptext = self.format_help(helptext, subst) self.write(helptext)
def get_options(self, method, resource, sub_resource=None, as_params_collection=False, context_variants=[]): """Return a list of options for typ/action.""" method_ref = None connection = self.check_connection() if isinstance(resource, type('')): if not sub_resource: if resource and hasattr(connection, TypeHelper.to_plural(resource)) and \ type(getattr(connection, TypeHelper.to_plural(resource))).__dict__.has_key(method): method_ref = getattr( getattr(connection, TypeHelper.to_plural(resource)), method) else: if hasattr(sub_resource, TypeHelper.to_plural(resource)) and \ type(getattr(sub_resource, TypeHelper.to_plural(resource))).__dict__.has_key(method): method_ref = getattr( getattr(sub_resource, TypeHelper.to_plural(resource)), method) elif hasattr(sub_resource, TypeHelper.to_plural(resource)) and \ hasattr(brokers, TypeHelper.to_singular(type(getattr(sub_resource, TypeHelper.to_plural(resource))).__name__)) and \ hasattr(getattr(brokers, TypeHelper.to_singular(type(getattr(sub_resource, TypeHelper.to_plural(resource))).__name__)), method): method_ref = getattr( getattr( brokers, TypeHelper.to_singular( type( getattr(sub_resource, TypeHelper.to_plural( resource))).__name__)), method) if not method_ref: err_str = Messages.Error.NO_SUCH_CONTEXT if context_variants: err_str = err_str + ( Messages.Info.POSSIBALE_ARGUMENTS_COMBINATIONS % str(context_variants)) self.error(err_str % resource) elif isinstance(resource, brokers.Base): if hasattr(resource, method): method_ref = getattr(resource, method) elif hasattr(brokers, TypeHelper.to_plural(type(resource).__name__)) and \ hasattr(getattr(brokers, TypeHelper.to_plural(type(resource).__name__)), method): method_ref = getattr( getattr(brokers, TypeHelper.to_plural(type(resource).__name__)), method) return MethodHelper.get_arguments_documentation( method_ref, as_params_collection)
def get_options(self, method, resource, sub_resource=None, as_params_collection=False, context_variants=[]): """Return a list of options for typ/action.""" method_ref = None connection = self.check_connection() if isinstance(resource, type('')): if not sub_resource: if resource and hasattr(connection, TypeHelper.to_plural(resource)) and \ type(getattr(connection, TypeHelper.to_plural(resource))).__dict__.has_key(method): method_ref = getattr(getattr(connection, TypeHelper.to_plural(resource)), method) else: if hasattr(sub_resource, TypeHelper.to_plural(resource)) and \ type(getattr(sub_resource, TypeHelper.to_plural(resource))).__dict__.has_key(method): method_ref = getattr(getattr(sub_resource, TypeHelper.to_plural(resource)), method) elif hasattr(sub_resource, TypeHelper.to_plural(resource)) and \ hasattr(brokers, TypeHelper.to_singular(type(getattr(sub_resource, TypeHelper.to_plural(resource))).__name__)) and \ hasattr(getattr(brokers, TypeHelper.to_singular(type(getattr(sub_resource, TypeHelper.to_plural(resource))).__name__)), method): method_ref = getattr(getattr(brokers, TypeHelper.to_singular(type(getattr(sub_resource, TypeHelper.to_plural(resource))).__name__)), method) if not method_ref: err_str = Messages.Error.NO_SUCH_CONTEXT if context_variants: err_str = err_str + (Messages.Info.POSSIBALE_ARGUMENTS_COMBINATIONS % str(context_variants)) self.error(err_str % resource) elif isinstance(resource, brokers.Base): if hasattr(resource, method): method_ref = getattr(resource, method) elif hasattr(brokers, TypeHelper.to_plural(type(resource).__name__)) and \ hasattr(getattr(brokers, TypeHelper.to_plural(type(resource).__name__)), method): method_ref = getattr(getattr(brokers, TypeHelper.to_plural(type(resource).__name__)), method) return MethodHelper.get_arguments_documentation(method_ref, as_params_collection)
def resolve_base(self, options): """ Resolves a base object from a set of parent identifier options. """ # Initially the base is the connection: connection = self.check_connection() base = connection # Find all the options that are parent identifiers, and sort them # so that the process will be always the same regardless of the # order of the options dictionary: identifiers = [ key for key in options.keys() if OptionHelper.is_parent_id_option(key) ] identifiers.sort() # Calculate the set of permutations of all the parent identifiers, as # we are going to try each permutation till we find one that results # in a valid base: permutations = list(itertools.permutations(identifiers)) for permutation in permutations: # Restart the search from the connection for each permutation: base = connection for item in permutation: # Get the name and value of the current parent identifier: key = item value = options[key] # Calculate the type and collection names: type_name = OptionHelper.get_parent_id_type(key) collection_name = TypeHelper.to_plural(type_name) if not (TypeHelper.isKnownType(type_name) or TypeHelper.isKnownType(collection_name)): self.error(Messages.Error.NO_SUCH_TYPE % type_name) # Try to extract the next base from the current one: if hasattr(base, collection_name): collection = getattr(base, collection_name) if hasattr(collection, 'get'): if not value: self.error(Messages.Error.INVALID_OPTION % key) if key.endswith('-identifier'): base = collection.get(id=value) elif key.endswith('-name'): base = collection.get(name=value) else: base = None else: base = None else: base = None # If we haven't been able to find a valid base for the current # parent identifier, then we should discard this permutation: if base is None: break # If we already found a valid base, then we should discard the # rest of the permutations, i.e., the first valid permutation is # the winner: if base != None: break # Generate an error message if no permutation results in a valid base: if base is None: self.error(Messages.Error.CANNOT_CONSTRUCT_COLLECTION_MEMBER_VIEW % str(permutations)) # The connection is the starting point for the search, so if the # result is the connection we can conclude that there is no # base: if base == connection: base = None return base
def get_object(self, typ, obj_id, base=None, opts={}, context_variants=[]): """Return an object by id or name.""" self.check_connection() connection = self.context.connection if base: options = self.get_options(method='get', resource=base, as_params_collection=True, context_variants=context_variants) else: options = self.get_options(method='get', resource=typ, as_params_collection=True, context_variants=context_variants) base = connection self.validate_options(opts, options) candidate = typ if typ is not None and isinstance(typ, type('')) \ else type(typ).__name__.lower() if hasattr(base, TypeHelper.to_plural(candidate)): coll = getattr(base, TypeHelper.to_plural(candidate)) else: err_str = Messages.Error.NO_SUCH_TYPE_OR_ARS_NOT_VALID if context_variants: err_str = err_str + ( Messages.Info.POSSIBALE_ARGUMENTS_COMBINATIONS % str(context_variants)) self.error(err_str % candidate) if obj_id is not None: _, kwargs = self._get_query_params(opts) if 'id' in options: obj = self.__get_by_id(coll, obj_id, kwargs) if obj is not None: return obj if 'name' in options: obj = self.__get_by_name(coll, obj_id, kwargs) if obj is not None: return obj if 'alias' in options: obj = self.__get_by_alias(coll, obj_id, kwargs) if obj is not None: return obj return None if 'id' in options: obj_id, kwargs = self._get_query_params(opts, query_arg='--id') if obj_id is not None: return self.__get_by_id(coll, obj_id, kwargs) if 'name' in options: obj_id, kwargs = self._get_query_params(opts, query_arg='--name') if obj_id is not None: return self.__get_by_name(coll, obj_id, kwargs) if 'alias' in options: obj_id, kwargs = self._get_query_params(opts, query_arg='--alias') if obj_id is not None: return self.__get_by_alias(coll, obj_id, kwargs) self.error(Messages.Error.NO_ID % 'show')
def show_help(self): """Show help for the action command.""" args = self.arguments opts = self.options types = TypeHelper.get_actionable_types( expendNestedTypes=True, groupOptions=True ) subst = {} if not args or self.is_supported_type(types.keys(), args[0]): if len(args) == 2 and len(opts) == 2: helptext = self.helptext1 subst['type'] = args[0] subst['id'] = args[1] base = self.resolve_base(self.options) obj = self.get_object( args[0], args[1], base, context_variants=types[args[0]] ) if obj is None: self.error( Messages.Error.NO_SUCH_OBJECT % (args[1], args[1]) ) actions = self._get_action_methods(obj) subst['actions'] = self.format_list(actions) if len(args) == 3 and len(opts) == 2: helptext = self.helptext1 subst['type'] = args[0] subst['id'] = args[1] subst['action'] = args[0] base = self.resolve_base(self.options) obj = self.get_object( args[1], args[2], base, context_variants=types[args[0]] ) if obj is None: self.error( Messages.Error.NO_SUCH_OBJECT % (args[0], args[1]) ) actions = self._get_action_methods(obj) if args[0] not in actions: self.error( Messages.Error.NO_SUCH_ACTION % args[2] ) options = self.get_options( method=args[0], resource=obj, context_variants=types[args[0]] ) subst['actions'] = self.format_list(actions) subst['options'] = self.format_list(options, bullet='', sort=False) elif len(args) == 1: helptext = self.helptext0 subst['types'] = self.format_map({args[0]:types[args[0]]}) subst['type'] = args[0] elif len(args) == 2: helptext = self.helptext1 subst['type'] = args[0] subst['id'] = args[1] base = self.resolve_base(opts) obj = self.get_object( args[0], args[1], base, context_variants=types[args[0]] ) if obj is None: self.error( Messages.Error.NO_SUCH_OBJECT % (args[0], args[1]) ) actions = self._get_action_methods(obj) subst['actions'] = self.format_list(actions) elif len(args) == 3: helptext = self.helptext1 subst['type'] = args[0] subst['id'] = args[1] subst['action'] = args[2] base = self.resolve_base(self.options) obj = self.get_object( args[0], args[1], base, context_variants=types[args[0]] ) if obj is None: self.error( Messages.Error.NO_SUCH_OBJECT % (args[0], args[1]) ) actions = self._get_action_methods(obj) if args[2] not in actions: self.error(Messages.Error.NO_SUCH_ACTION % args[2]) options = self.get_options( method=args[2], resource=obj, sub_resource=base, context_variants=types[args[0]] ) subst['actions'] = self.format_list(actions) subst['options'] = self.format_list(options, bullet='', sort=False) else: helptext = self.helptext0 subst['types'] = self.format_map(types) # scope = '%s:%s' % (type(obj).__name__, args[2]) statuses = self.get_statuses() subst['statuses'] = self.format_list(statuses) helptext = self.format_help(helptext, subst) self.write(helptext)
def show_help(self): """Show help for "update".""" self.check_connection() args = self.arguments opts = self.options subst = {} types = TypeHelper.get_types_containing_method( 'update', expendNestedTypes=True, groupOptions=True ) subst['types'] = self.format_map(types) statuses = self.get_statuses() subst['statuses'] = self.format_list(statuses) if len(args) > 0 and self.is_supported_type(types.keys(), args[0]): if len(args) == 2: base = self.resolve_base(self.options) obj = self.get_object( args[0], args[1], base, context_variants=types[args[0]] ) if obj is None: self.error( Messages.Error.NO_SUCH_OBJECT % (args[0], args[1]) ) helptext = self.helptext1 params_list = self.get_options( method='update', resource=obj, sub_resource=base, context_variants=types[args[0]] ) subst['options'] = self.format_list(params_list) subst['type'] = args[0] elif len(args) == 1 and len(opts) == 2: helptext = self.helptext1 subst['type'] = args[0] options = self.get_options( method='update', resource=args[0], sub_resource=self.resolve_base(self.options), context_variants=types[args[0]] ) subst['options'] = self.format_list(options) subst['type'] = args[0] elif len(args) == 1: helptext = self.helptext subst['type'] = args[0] subst['types'] = self.format_map({args[0]:types[args[0]]}) else: helptext = self.helptext else: helptext = self.helptext helptext = self.format_help(helptext, subst) self.write(helptext)