def run(self, args, **kwargs): if not args.ref_or_id: self.parser.error('too few arguments') action = self.get_resource(args.ref_or_id, **kwargs) if not action: raise resource.ResourceNotFoundError( 'Action "%s" cannot be found.' % args.ref_or_id) runner_mgr = self.app.client.managers['RunnerType'] runner = runner_mgr.get_by_name(action.runner_type, **kwargs) if not runner: raise resource.ResourceNotFoundError( 'Runner type "%s" for action "%s" cannot be found.' % (action.runner_type, action.name)) action_ref = '.'.join([action.pack, action.name]) action_parameters = self._get_action_parameters_from_args( action=action, runner=runner, args=args) execution = models.LiveAction() execution.action = action_ref execution.parameters = action_parameters action_exec_mgr = self.app.client.managers['LiveAction'] execution = action_exec_mgr.create(execution, **kwargs) execution = self._get_execution_result(execution=execution, action_exec_mgr=action_exec_mgr, args=args, **kwargs) return execution
def run(self, args, **kwargs): existing_execution = self.manager.get_by_id(args.id, **kwargs) if not existing_execution: raise resource.ResourceNotFoundError( 'Action execution with id "%s" cannot be found.' % (args.id)) action_mgr = self.app.client.managers['Action'] runner_mgr = self.app.client.managers['RunnerType'] action_exec_mgr = self.app.client.managers['LiveAction'] # TODO use action.ref when this attribute is added action_ref = existing_execution.action[ 'pack'] + '.' + existing_execution.action['name'] action = action_mgr.get_by_ref_or_id(action_ref) runner = runner_mgr.get_by_name(action.runner_type) action_parameters = self._get_action_parameters_from_args( action=action, runner=runner, args=args) # Create new execution object new_execution = models.LiveAction() new_execution.action = action_ref new_execution.parameters = existing_execution.parameters or {} # If user provides parameters merge and override with the ones from the # existing execution new_execution.parameters.update(action_parameters) execution = action_exec_mgr.create(new_execution, **kwargs) execution = self._get_execution_result(execution=execution, action_exec_mgr=action_exec_mgr, args=args, **kwargs) return execution
def run(self, args, **kwargs): schema = self.app.client.managers['ConfigSchema'].get_by_ref_or_id(args.name, **kwargs) if not schema: raise resource.ResourceNotFoundError("%s doesn't have config schema defined" % self.resource.get_display_name()) config = interactive.InteractiveForm(schema.attributes).initiate_dialog() message = '---\nDo you want to preview the config in an editor before saving?' description = 'Secrets would be shown in plain text.' preview_dialog = interactive.Question(message, {'default': 'y', 'description': description}) if preview_dialog.read() == 'y': contents = yaml.safe_dump(config, indent=4, default_flow_style=False) modified = editor.edit(contents=contents) config = yaml.safe_load(modified) message = '---\nDo you want me to save it?' save_dialog = interactive.Question(message, {'default': 'y'}) if save_dialog.read() == 'n': raise OperationFailureException('Interrupted') result = self.app.client.managers['Config'].update(Config(pack=args.name, values=config)) return result
def run(self, args, **kwargs): existing_execution = self.manager.get_by_id(args.id, **kwargs) if not existing_execution: raise resource.ResourceNotFoundError( 'Action execution with id "%s" cannot be found.' % (args.id)) action_mgr = self.app.client.managers['Action'] runner_mgr = self.app.client.managers['RunnerType'] action_exec_mgr = self.app.client.managers['LiveAction'] action_ref = existing_execution.action['ref'] action = action_mgr.get_by_ref_or_id(action_ref) runner = runner_mgr.get_by_name(action.runner_type) action_parameters = self._get_action_parameters_from_args( action=action, runner=runner, args=args) execution = action_exec_mgr.re_run(execution_id=args.id, parameters=action_parameters, tasks=args.tasks, no_reset=args.no_reset, **kwargs) execution = self._get_execution_result(execution=execution, action_exec_mgr=action_exec_mgr, args=args, **kwargs) return execution
def run(self, args, **kwargs): schema = self.app.client.managers["ConfigSchema"].get_by_ref_or_id( args.name, **kwargs ) if not schema: msg = "%s \"%s\" doesn't exist or doesn't have a config schema defined." raise resource.ResourceNotFoundError( msg % (self.resource.get_display_name(), args.name) ) config = interactive.InteractiveForm(schema.attributes).initiate_dialog() message = "---\nDo you want to preview the config in an editor before saving?" description = "Secrets will be shown in plain text." preview_dialog = interactive.Question( message, {"default": "y", "description": description} ) if preview_dialog.read() == "y": try: contents = yaml.safe_dump(config, indent=4, default_flow_style=False) modified = editor.edit(contents=contents) config = yaml.safe_load(modified) except editor.EditorError as e: print(six.text_type(e)) message = "---\nDo you want me to save it?" save_dialog = interactive.Question(message, {"default": "y"}) if save_dialog.read() == "n": raise OperationFailureException("Interrupted") config_item = Config(pack=args.name, values=config) result = self.app.client.managers["Config"].update(config_item, **kwargs) return result
def _print_help(self, args, **kwargs): # Print appropriate help message if the help option is given. action_mgr = self.app.client.managers['Action'] action_exec_mgr = self.app.client.managers['LiveAction'] if args.help: action_ref_or_id = getattr(args, 'ref_or_id', None) action_exec_id = getattr(args, 'id', None) if action_exec_id and not action_ref_or_id: action_exec = action_exec_mgr.get_by_id( action_exec_id, **kwargs) args.ref_or_id = action_exec.action if action_ref_or_id: try: action = action_mgr.get_by_ref_or_id( args.ref_or_id, **kwargs) if not action: raise resource.ResourceNotFoundError( 'Action %s not found', args.ref_or_id) runner_mgr = self.app.client.managers['RunnerType'] runner = runner_mgr.get_by_name(action.runner_type, **kwargs) parameters, required, optional, _ = self._get_params_types( runner, action) print('') print(textwrap.fill(action.description)) print('') if required: required = self._sort_parameters(parameters=parameters, names=required) print('Required Parameters:') [ self._print_param(name, parameters.get(name)) for name in required ] if optional: optional = self._sort_parameters(parameters=parameters, names=optional) print('Optional Parameters:') [ self._print_param(name, parameters.get(name)) for name in optional ] except resource.ResourceNotFoundError: print( ('Action "%s" is not found. ' % args.ref_or_id) + 'Do "st2 action list" to see list of available actions.' ) except Exception as e: print('ERROR: Unable to print help for action "%s". %s' % (args.ref_or_id, e)) else: self.parser.print_help() return True return False
def run(self, args, **kwargs): resource_id = getattr(args, self.pk_argument_name, None) instance = self.get_resource(resource_id, **kwargs) if not instance: raise resource.ResourceNotFoundError('KeyValuePair with id "%s" not found', resource_id) instance.id = resource_id # TODO: refactor and get rid of id self.manager.delete(instance, **kwargs)
def run(self, args, **kwargs): if not args.ref_or_id: self.parser.error('Missing action reference or id') action = self.get_resource(args.ref_or_id, **kwargs) if not action: raise resource.ResourceNotFoundError( 'Action "%s" cannot be found.' % (args.ref_or_id)) runner_mgr = self.app.client.managers['RunnerType'] runner = runner_mgr.get_by_name(action.runner_type, **kwargs) if not runner: raise resource.ResourceNotFoundError( 'Runner type "%s" for action "%s" cannot be found.' % (action.runner_type, action.name)) action_ref = '.'.join([action.pack, action.name]) action_parameters = self._get_action_parameters_from_args( action=action, runner=runner, args=args) execution = models.LiveAction() execution.action = action_ref execution.parameters = action_parameters execution.user = args.user if not args.trace_id and args.trace_tag: execution.context = { 'trace_context': { 'trace_tag': args.trace_tag } } if args.trace_id: execution.context = {'trace_context': {'id_': args.trace_id}} action_exec_mgr = self.app.client.managers['LiveAction'] execution = action_exec_mgr.create(execution, **kwargs) execution = self._get_execution_result(execution=execution, action_exec_mgr=action_exec_mgr, args=args, **kwargs) return execution
def run_and_print(self, args, **kwargs): try: instance = self.run(args, **kwargs) if not instance: raise resource.ResourceNotFoundError("No matching items found") self.print_output(instance, table.PropertyValueTable, attributes=['all'], json=args.json, yaml=args.yaml) except resource.ResourceNotFoundError: print("No matching items found") except Exception as e: message = e.message or str(e) print('ERROR: %s' % (message)) raise OperationFailureException(message)
def run(self, args, **kwargs): resource_id = getattr(args, self.pk_argument_name, None) scope = getattr(args, 'scope', DEFAULT_SCOPE) kwargs['params'] = {} kwargs['params']['scope'] = scope instance = self.get_resource(resource_id, **kwargs) if not instance: raise resource.ResourceNotFoundError( 'KeyValuePair with id "%s" not found', resource_id) instance.id = resource_id # TODO: refactor and get rid of id self.manager.delete(instance, **kwargs)
def run(self, args, **kwargs): resource_id = getattr(args, self.pk_argument_name, None) scope = getattr(args, "scope", DEFAULT_CUD_SCOPE) kwargs["params"] = {} kwargs["params"]["scope"] = scope kwargs["params"]["user"] = args.user instance = self.get_resource(resource_id, **kwargs) if not instance: raise resource.ResourceNotFoundError( 'KeyValuePair with id "%s" not found' % resource_id) instance.id = resource_id # TODO: refactor and get rid of id self.manager.delete(instance, **kwargs)
def run(self, args, **kwargs): if not args.ref_or_id: self.parser.error('too few arguments') action = self.get_resource(args.ref_or_id, **kwargs) if not action: raise resource.ResourceNotFoundError('Action "%s" cannot be found.' % args.ref_or_id) runner_mgr = self.app.client.managers['RunnerType'] runner = runner_mgr.get_by_name(action.runner_type, **kwargs) if not runner: raise resource.ResourceNotFoundError('Runner type "%s" for action "%s" cannot be found.' % (action.runner_type, action.name)) def read_file(file_path): if not os.path.exists(file_path): raise ValueError('File "%s" doesn\'t exist' % (file_path)) if not os.path.isfile(file_path): raise ValueError('"%s" is not a file' % (file_path)) with open(file_path, 'rb') as fp: content = fp.read() return content def transform_object(value): # Also support simple key1=val1,key2=val2 syntax if value.startswith('{'): # Assume it's JSON result = value = json.loads(value) else: pairs = value.split(',') result = {} for pair in pairs: split = pair.split('=', 1) if len(split) != 2: continue key, value = split result[key] = value return result transformer = { 'array': (lambda cs_x: [v.strip() for v in cs_x.split(',')]), 'boolean': (lambda x: ast.literal_eval(x.capitalize())), 'integer': int, 'number': float, 'object': transform_object, 'string': str } def normalize(name, value): if name in runner.runner_parameters: param = runner.runner_parameters[name] if 'type' in param and param['type'] in transformer: return transformer[param['type']](value) if name in action.parameters: param = action.parameters[name] if 'type' in param and param['type'] in transformer: return transformer[param['type']](value) return value action_ref = '.'.join([action.pack, action.name]) execution = models.ActionExecution() execution.action = action_ref execution.parameters = dict() for idx in range(len(args.parameters)): arg = args.parameters[idx] if '=' in arg: k, v = arg.split('=', 1) # Attribute for files are prefixed with "@" if k.startswith('@'): k = k[1:] is_file = True else: is_file = False try: if is_file: # Files are handled a bit differently since we ship the content # over the wire file_path = os.path.normpath(pjoin(os.getcwd(), v)) file_name = os.path.basename(file_path) content = read_file(file_path=file_path) execution.parameters['_file_name'] = file_name execution.parameters['file_content'] = content else: execution.parameters[k] = normalize(k, v) except Exception as e: # TODO: Move transformers in a separate module and handle # exceptions there if 'malformed string' in str(e): message = ('Invalid value for boolean parameter. ' 'Valid values are: true, false') raise ValueError(message) else: raise e else: execution.parameters['cmd'] = ' '.join(args.parameters[idx:]) break if 'file_content' in execution.parameters: if 'method' not in execution.parameters: # Default to POST if a method is not provided execution.parameters['method'] = 'POST' if 'file_name' not in execution.parameters: # File name not provided, use default file name execution.parameters['file_name'] = execution.parameters['_file_name'] del execution.parameters['_file_name'] action_exec_mgr = self.app.client.managers['ActionExecution'] execution = action_exec_mgr.create(execution, **kwargs) if not args.async: while execution.status == ACTIONEXEC_STATUS_SCHEDULED \ or execution.status == ACTIONEXEC_STATUS_RUNNING: time.sleep(1) if not args.json: sys.stdout.write('.') execution = action_exec_mgr.get_by_id(execution.id, **kwargs) sys.stdout.write('\n') if self._is_error_result(result=execution.result): execution.result = self._format_error_result(execution.result) return execution