desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Create a Request object using environ.'
def run(self):
env = self.environ.get local = httputil.Host('', int(env('SERVER_PORT', 80)), env('SERVER_NAME', '')) remote = httputil.Host(env('REMOTE_ADDR', ''), int(env('REMOTE_PORT', (-1))), env('REMOTE_HOST', '')) scheme = env('wsgi.url_scheme') sproto = env('ACTUAL_SERVER_PROTOCOL', 'HTTP/1.1') (request,...
'Translate CGI-environ header names to HTTP header names.'
def translate_headers(self, environ):
for cgiName in environ: if (cgiName in self.headerNames): (yield (self.headerNames[cgiName], environ[cgiName])) elif (cgiName[:5] == 'HTTP_'): translatedHeader = cgiName[5:].replace('_', '-') (yield (translatedHeader, environ[cgiName]))
'WSGI application callable for the actual CherryPy application. You probably shouldn\'t call this; call self.__call__ instead, so that any WSGI middleware in self.pipeline can run first.'
def tail(self, environ, start_response):
return self.response_class(environ, start_response, self.cpapp)
'Config handler for the \'wsgi\' namespace.'
def namespace_handler(self, k, v):
if (k == 'pipeline'): self.pipeline.extend(v) elif (k == 'response_class'): self.response_class = v else: (name, arg) = k.split('.', 1) bucket = self.config.setdefault(name, {}) bucket[arg] = v
'Write data to file_path.'
@abc.abstractmethod def write(self, data, file_path, replace=False):
pass
'All TriggerDB that has a parameter.'
def _get_trigger_with_parameters(self):
return TriggerDB.objects((Q(parameters__exists=True) & Q(parameters__nin=[{}])))
'All rules that reference the supplied trigger_ref.'
def _get_rules_for_trigger(self, trigger_ref):
return Rule.get_all(**{'trigger': trigger_ref})
'Non-publishing ref_count update to a TriggerDB.'
def _update_trigger_ref_count(self, trigger_db, ref_count):
trigger_db.ref_count = ref_count Trigger.add_or_update(trigger_db, publish=False, dispatch_trigger=False)
'Will migrate all Triggers that should have ref_count to have the right ref_count.'
def migrate(self):
trigger_dbs = self._get_trigger_with_parameters() for trigger_db in trigger_dbs: trigger_ref = trigger_db.get_reference().ref rules = self._get_rules_for_trigger(trigger_ref=trigger_ref) ref_count = len(rules) print ('Updating Trigger %s to ref_count %s' % (trigger...
'Initialize a DebugInfoCollector object. :param include_logs: Include log files in generated archive. :type include_logs: ``bool`` :param include_configs: Include config files in generated archive. :type include_configs: ``bool`` :param include_content: Include pack contents in generated archive. :type include_content:...
def __init__(self, include_logs, include_configs, include_content, include_system_info, include_shell_commands=False, user_info=None, debug=False, config_file=None, output_path=None):
self.include_logs = include_logs self.include_configs = include_configs self.include_content = include_content self.include_system_info = include_system_info self.include_shell_commands = include_shell_commands self.user_info = user_info self.debug = debug self.output_path = output_path ...
'Run the specified steps. :param encrypt: If true, encrypt the archive file. :param encrypt: ``bool`` :param upload: If true, upload the resulting file. :param upload: ``bool`` :param existing_file: Path to an existing archive file. If not specified a new archive will be created. :param existing_file: ``str``'
def run(self, encrypt=False, upload=False, existing_file=None):
temp_files = [] try: if existing_file: working_file = existing_file else: working_file = self.create_archive() if ((not encrypt) and (not upload)): LOG.info(('Debug tarball successfully generated and can be reviewed at: ...
'Create an archive with debugging information. :return: Path to the generated archive. :rtype: ``str``'
def create_archive(self):
try: self._temp_dir_path = self.create_temp_directories() output_paths = {} for (key, path) in OUTPUT_PATHS.iteritems(): output_paths[key] = os.path.join(self._temp_dir_path, path) LOG.info('Collecting files...') if self.include_logs: self.collect_l...
'Encrypt archive with debugging information using our public key. :param archive_file_path: Path to the non-encrypted tarball file. :type archive_file_path: ``str`` :return: Path to the encrypted archive. :rtype: ``str``'
def encrypt_archive(self, archive_file_path):
try: assert archive_file_path.endswith('.tar.gz') LOG.info('Encrypting tarball...') gpg = gnupg.GPG(verbose=self.debug) import_result = gpg.import_keys(self.gpg_key) assert (import_result.count == 1) encrypted_archive_output_file_name = (os.path.basename(archive_fi...
'Upload the encrypted archive. :param archive_file_path: Path to the encrypted tarball file. :type archive_file_path: ``str``'
def upload_archive(self, archive_file_path):
try: assert archive_file_path.endswith('.asc') LOG.debug('Uploading tarball...') file_name = os.path.basename(archive_file_path) url = (self.s3_bucket_url + file_name) assert url.startswith('https://') with open(archive_file_path, 'rb') as fp: response ...
'Copy log files to the output path. :param output_path: Path where log files will be copied to. :type output_path: ``str``'
def collect_logs(self, output_path):
LOG.debug('Including log files') for file_path_glob in self.log_file_paths: log_file_list = get_full_file_list(file_path_glob=file_path_glob) copy_files(file_paths=log_file_list, destination=output_path)
'Copy config files to the output path. :param output_path: Path where config files will be copied to. :type output_path: ``str``'
def collect_config_files(self, output_path):
LOG.debug('Including config files') copy_files(file_paths=self.config_file_paths, destination=output_path) st2_config_path = os.path.join(output_path, self.st2_config_file_name) process_st2_config(config_path=st2_config_path) mistral_config_path = os.path.join(output_path, self.mistral_config_...
'Copy pack contents to the output path. :param output_path: Path where pack contents will be copied to. :type output_path: ``str``'
@staticmethod def collect_pack_content(output_path):
LOG.debug('Including content') packs_base_paths = get_packs_base_paths() for (index, packs_base_path) in enumerate(packs_base_paths, 1): dst = os.path.join(output_path, ('dir-%s' % index)) try: shutil.copytree(src=packs_base_path, dst=dst) except IOError: c...
'Collect and write system information to output path. :param output_path: Path where system information will be written to. :type output_path: ``str``'
def add_system_information(self, output_path):
LOG.debug('Including system info') system_information = yaml.safe_dump(self.get_system_information(), default_flow_style=False) with open(output_path, 'w') as fp: fp.write(system_information)
'Write user info to output path as YAML. :param output_path: Path where user info will be written. :type output_path: ``str``'
def add_user_info(self, output_path):
LOG.debug('Including user info') user_info = yaml.safe_dump(self.user_info, default_flow_style=False) with open(output_path, 'w') as fp: fp.write(user_info)
'Get output of the required shell command and redirect the output to output path. :param output_path: Directory where output files will be written :param output_path: ``str``'
def add_shell_command_output(self, output_path):
LOG.debug('Including the required shell commands output files') for cmd in self.shell_commands: output_file = os.path.join(output_path, ('%s.txt' % self.format_output_filename(cmd))) (exit_code, stdout, stderr) = run_command(cmd=cmd, shell=True, cwd=output_path) with op...
'Create tarball with the contents of temp_dir_path. Tarball will be written to self.output_path, if set. Otherwise it will be written to /tmp a name generated according to OUTPUT_FILENAME_TEMPLATE. :param temp_dir_path: Base directory to include in tarbal. :type temp_dir_path: ``str`` :return: Path to the created tarba...
def create_tarball(self, temp_dir_path):
LOG.info('Creating tarball...') if self.output_path: output_file_path = self.output_path else: date = date_utils.get_datetime_utc_now().strftime(DATE_FORMAT) values = {'hostname': socket.gethostname(), 'date': date} output_file_name = (OUTPUT_FILENAME_TEMPLATE % values) ...
'Creates a new temp directory and creates the directory structure as defined by DIRECTORY_STRUCTURE. :return: Path to temp directory. :rtype: ``str``'
@staticmethod def create_temp_directories():
temp_dir_path = tempfile.mkdtemp() for directory_name in DIRECTORY_STRUCTURE: full_path = os.path.join(temp_dir_path, directory_name) os.mkdir(full_path) return temp_dir_path
'Remove whitespace and special characters from a shell command. Used to create filename-safe representations of a shell command. :param cmd: Shell command. :type cmd: ``str`` :return: Formatted filename. :rtype: ``str``'
@staticmethod def format_output_filename(cmd):
return cmd.translate(None, ' !@#$%^&*()[]{};:,./<>?\\|`~=+"\'')
'Retrieve system information which is included in the report. :rtype: ``dict``'
@staticmethod def get_system_information():
system_information = {'hostname': socket.gethostname(), 'operating_system': {}, 'hardware': {'cpu': {}, 'memory': {}}, 'python': {}, 'stackstorm': {}, 'mistral': {}} system_information['operating_system']['system'] = platform.system() system_information['operating_system']['release'] = platform.release() ...
'Parse query string for the provided request. :rtype: ``dict``'
def _parse_query_params(self, request):
query_string = request.query_string query_params = dict(urlparse.parse_qsl(query_string)) return query_params
'Return a value for the provided query param and optionally cast it for boolean types. If the requested query parameter is not provided, default value is returned instead. :param request: Request object. :param param_name: Name of the param to retrieve the value for. :type param_name: ``str`` :param param_type: Type of...
def _get_query_param_value(self, request, param_name, param_type, default_value=None):
query_params = self._parse_query_params(request=request) value = query_params.get(param_name, default_value) if ((param_type == 'bool') and isinstance(value, six.string_types)): value = transform_to_bool(value) return value
'Return a value for mask_secrets which can be used in masking secret properties to be retruned by any API. The default value is as per the config however admin users have the ability to override by passing in a special query parameter ?show_secrets=True. :rtype: ``bool``'
def _get_mask_secrets(self, requester_user, show_secrets=None):
mask_secrets = cfg.CONF.api.mask_secrets if (show_secrets and rbac_utils.user_is_admin(user_db=requester_user)): mask_secrets = False return mask_secrets
'Create a new rule. Handles requests: POST /rules/'
def post(self, rule, requester_user):
permission_type = PermissionType.RULE_CREATE rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user, resource_api=rule, permission_type=permission_type) try: rule_db = RuleAPI.to_model(rule) LOG.debug('/rules/ POST verified RuleAPI and formulated RuleDB=%...
'Delete a rule. Handles requests: DELETE /rules/1'
def delete(self, rule_ref_or_id, requester_user):
rule_db = self._get_by_ref_or_id(ref_or_id=rule_ref_or_id) permission_type = PermissionType.RULE_DELETE rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=rule_db, permission_type=permission_type) LOG.debug('DELETE /rules/ lookup with id=%s found obje...
'List RuleType objects by id. Handle: GET /ruletypes/1'
def get_one(self, id):
ruletype_db = RuleTypesController.__get_by_id(id) ruletype_api = RuleTypeAPI.from_model(ruletype_db) return ruletype_api
'List all RuleType objects. Handles requests: GET /ruletypes/'
def get_all(self):
ruletype_dbs = RuleType.get_all() ruletype_apis = [RuleTypeAPI.from_model(runnertype_db) for runnertype_db in ruletype_dbs] return ruletype_apis
'remove the trailing and leading / so that the hook url and those coming from trigger parameters end up being the same.'
def _get_normalized_url(self, trigger):
return trigger['parameters']['url'].strip('/')
'List all distinct filters. Handles requests: GET /executions/views/filters[?types=action,rule] :param types: Comma delimited string of filter types to output. :type types: ``str``'
def get_all(self, types=None):
filters = {} for (name, field) in six.iteritems(SUPPORTED_FILTERS): if ((name not in IGNORE_FILTERS) and ((not types) or (name in types))): if (name not in FILTERS_WITH_VALID_NULL_VALUES): query = {field.replace('.', '__'): {'$ne': None}} else: que...
'Reduces the number of queries to be made to the DB by creating sets of Actions, Triggers and TriggerTypes.'
def _get_referenced_models(self, rules):
action_refs = set() trigger_refs = set() trigger_type_refs = set() for rule in rules: action_refs.add(rule['action']['ref']) trigger_refs.add(rule['trigger']['ref']) trigger_type_refs.add(rule['trigger']['type']) action_by_refs = {} trigger_by_refs = {} trigger_type_b...
'Returns all the entities for the supplied refs. model_persistence is the persistence object that will be used to get to the correct query method and the query_args function to return the ref specific query argument. This is such a weirdly specific method that it is likely better only in this context.'
def _get_entities(self, model_persistence, refs, query_args):
q = None for ref in refs: if (not q): q = Q(**query_args(ref)) else: q |= Q(**query_args(ref)) if q: return model_persistence._get_impl().model.objects(q) return []
'Retrieve configs for all the packs. Handles requests: GET /configs/'
def get_all(self, requester_user, sort=None, offset=0, limit=None, show_secrets=False, **raw_filters):
from_model_kwargs = {'mask_secrets': self._get_mask_secrets(requester_user, show_secrets=show_secrets)} return super(PackConfigsController, self)._get_all(sort=sort, offset=offset, limit=limit, from_model_kwargs=from_model_kwargs, raw_filters=raw_filters)
'Retrieve config for a particular pack. Handles requests: GET /configs/<pack_ref>'
def get_one(self, pack_ref, requester_user, show_secrets=False):
from_model_kwargs = {'mask_secrets': self._get_mask_secrets(requester_user, show_secrets=show_secrets)} try: instance = packs_service.get_pack_by_ref(pack_ref=pack_ref) except StackStormDBObjectNotFoundError: msg = ('Unable to identify resource with pack_ref "%s".' % pack_r...
'Create a new config for a pack. Handles requests: POST /configs/<pack_ref>'
def put(self, pack_uninstall_request, pack_ref, requester_user, show_secrets=False):
try: config_api = ConfigAPI(pack=pack_ref, values=vars(pack_uninstall_request)) config_api.validate(validate_against_schema=True) except jsonschema.ValidationError as e: raise ValueValidationException(str(e)) self._dump_config_to_disk(config_api) config_db = ConfigsRegistrar.save...
'Retrieve config schema for all the packs. Handles requests: GET /config_schema/'
def get_all(self, sort=None, offset=0, limit=None, **raw_filters):
return super(PackConfigSchemasController, self)._get_all(sort=sort, offset=offset, limit=limit, raw_filters=raw_filters)
'Retrieve config schema for a particular pack. Handles requests: GET /config_schema/<pack_ref>'
def get_one(self, pack_ref, requester_user):
packs_controller._get_one_by_ref_or_id(ref_or_id=pack_ref, requester_user=requester_user) return self._get_one_by_pack_ref(pack_ref=pack_ref)
':param liveaction: LiveActionAPI object. :type liveaction: :class:`LiveActionAPI`'
def _handle_schedule_execution(self, liveaction_api, requester_user, context_string=None, show_secrets=False):
if (not requester_user): requester_user = UserDB(cfg.CONF.system_user.user) action_ref = liveaction_api.action action_db = action_utils.get_action_by_ref(action_ref) if (not action_db): message = ('Action "%s" cannot be found.' % action_ref) LOG.warning(message) ...
'Retrieve result object for the provided action execution. :param id: Action execution ID. :type id: ``str`` :rtype: ``dict``'
def _get_result_object(self, id):
fields = ['result'] action_exec_db = self.access.impl.model.objects.filter(id=id).only(*fields).get() return action_exec_db.result
'Retrieve children for the provided action execution. :rtype: ``list``'
def get_one(self, id, requester_user, depth=(-1), result_fmt=None, show_secrets=False):
instance = self._get_by_id(resource_id=id) permission_type = PermissionType.EXECUTION_VIEW rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=instance, permission_type=permission_type) return self._get_children(id_=id, depth=depth, result_fmt=result_fmt, requester_user...
'Retrieve a particular attribute for the provided action execution. Handles requests: GET /executions/<id>/attribute/<attribute name> :rtype: ``dict``'
def get(self, id, attribute, requester_user):
fields = [attribute, 'action__pack', 'action__uid'] fields = self._validate_exclude_fields(fields) action_exec_db = self.access.impl.model.objects.filter(id=id).only(*fields).get() permission_type = PermissionType.EXECUTION_VIEW rbac_utils.assert_user_has_resource_db_permission(user_db=requester_use...
'Re-run the provided action execution optionally specifying override parameters. Handles requests: POST /executions/<id>/re_run'
def post(self, spec_api, id, requester_user, no_merge=False, show_secrets=False):
if ((spec_api.tasks or spec_api.reset) and spec_api.parameters): raise ValueError('Parameters override is not supported when re-running task(s) for a workflow.') if spec_api.parameters: assert isinstance(spec_api.parameters, dict) if spec_api.tasks: asse...
'List all executions. Handles requests: GET /executions[?exclude_attributes=result,trigger_instance] :param exclude_attributes: Comma delimited string of attributes to exclude from the object. :type exclude_attributes: ``str``'
def get_all(self, requester_user, exclude_attributes=None, sort=None, offset=0, limit=None, show_secrets=False, **raw_filters):
if exclude_attributes: exclude_fields = exclude_attributes.split(',') else: exclude_fields = None exclude_fields = self._validate_exclude_fields(exclude_fields=exclude_fields) query_options = None if (raw_filters.get('timestamp_lt', None) or raw_filters.get('sort_desc', None)): ...
'Retrieve a single execution. Handles requests: GET /executions/<id>[?exclude_attributes=result,trigger_instance] :param exclude_attributes: Comma delimited string of attributes to exclude from the object. :type exclude_attributes: ``str``'
def get_one(self, id, requester_user, exclude_attributes=None, show_secrets=False):
if exclude_attributes: exclude_fields = exclude_attributes.split(',') else: exclude_fields = None exclude_fields = self._validate_exclude_fields(exclude_fields=exclude_fields) from_model_kwargs = {'mask_secrets': self._get_mask_secrets(requester_user, show_secrets=show_secrets)} retu...
'Updates a single execution. Handles requests: PUT /executions/<id>'
def put(self, id, liveaction_api, requester_user, show_secrets=False):
if (not requester_user): requester_user = UserDB(cfg.CONF.system_user.user) from_model_kwargs = {'mask_secrets': self._get_mask_secrets(requester_user, show_secrets=show_secrets)} execution_api = self._get_one_by_id(id=id, requester_user=requester_user, from_model_kwargs=from_model_kwargs, permissio...
'Stops a single execution. Handles requests: DELETE /executions/<id>'
def delete(self, id, requester_user, show_secrets=False):
if (not requester_user): requester_user = UserDB(cfg.CONF.system_user.user) from_model_kwargs = {'mask_secrets': self._get_mask_secrets(requester_user, show_secrets=show_secrets)} execution_api = self._get_one_by_id(id=id, requester_user=requester_user, from_model_kwargs=from_model_kwargs, permissio...
':param exclude_fields: A list of object fields to exclude. :type exclude_fields: ``list``'
def _get_action_executions(self, exclude_fields=None, sort=None, offset=0, limit=None, query_options=None, raw_filters=None, from_model_kwargs=None):
if (limit is None): limit = self.default_limit limit = int(limit) LOG.debug('Retrieving all action executions with filters=%s', raw_filters) return super(ActionExecutionsController, self)._get_all(exclude_fields=exclude_fields, from_model_kwargs=from_model_kwargs, sort=sort, offse...
'List api keys. Handle: GET /apikeys/1'
def get_one(self, api_key_id_or_key, requester_user, show_secrets=None):
api_key_db = None try: api_key_db = ApiKey.get_by_key_or_id(api_key_id_or_key) except ApiKeyNotFoundError: msg = ('ApiKey matching %s for reference and id not found.' % api_key_id_or_key) LOG.exception(msg) abort(http_client.NOT_FOUND, msg) permiss...
'List all keys. Handles requests: GET /apikeys/'
def get_all(self, requester_user, show_secrets=None, limit=None, offset=0):
mask_secrets = self._get_mask_secrets(show_secrets=show_secrets, requester_user=requester_user) if (limit and (int(limit) > self.max_limit)): msg = ('Limit "%s" specified, maximum value is "%s"' % (limit, self.max_limit)) raise ValueError(msg) api_key_dbs = ApiKey.get_all(l...
'Create a new entry.'
def post(self, api_key_api, requester_user):
permission_type = PermissionType.API_KEY_CREATE rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user, resource_api=api_key_api, permission_type=permission_type) api_key_db = None api_key = None try: if (not getattr(api_key_api, 'user', None)): if requester_us...
'Delete the key value pair. Handles requests: DELETE /apikeys/1'
def delete(self, api_key_id_or_key, requester_user):
api_key_db = ApiKey.get_by_key_or_id(api_key_id_or_key) permission_type = PermissionType.API_KEY_DELETE rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=api_key_db, permission_type=permission_type) ApiKey.delete(api_key_db) extra = {'api_key_db': api_key_db} ...
'Create a new policy. Handles requests: POST /policies/'
def post(self, instance, requester_user):
permission_type = PermissionType.POLICY_CREATE rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user, resource_api=instance, permission_type=permission_type) op = 'POST /policies/' db_model = self.model.to_model(instance) LOG.debug('%s verified object: %s', op, db_mod...
'Delete a policy. Handles requests: POST /policies/1?_method=delete DELETE /policies/1 DELETE /policies/mypack.mypolicy'
def delete(self, ref_or_id, requester_user):
op = ('DELETE /policies/%s/' % ref_or_id) db_model = self._get_by_ref_or_id(ref_or_id=ref_or_id) LOG.debug('%s found object: %s', op, db_model) permission_type = PermissionType.POLICY_DELETE rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=db_model, p...
'Check if all listed indexes are healthy: they should be reachable, return valid JSON objects, and yield more than one result.'
def get(self):
(_, status) = packs_service.fetch_pack_index(allow_empty=True) health = {'indexes': {'count': len(status), 'valid': 0, 'invalid': 0, 'errors': {}, 'status': status}, 'packs': {'count': 0}} for index in status: if index['error']: error_count = (health['indexes']['errors'].get(index['error...
'Note: In this case "ref" is pack name and not StackStorm\'s ResourceReference.'
def _get_by_ref(self, ref, exclude_fields=None):
resource_db = self.access.query(ref=ref, exclude_fields=exclude_fields).first() return resource_db
'List merged action & runner parameters by action id. Handle: GET /actions/views/parameters/1'
@staticmethod def _get_one(action_id, requester_user):
action_db = LookupUtils._get_action_by_id(action_id) LOG.info('Found action: %s, runner: %s', action_db, action_db.runner_type['name']) permission_type = PermissionType.ACTION_VIEW rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=action_db, permission_typ...
'List action by id. Handle: GET /actions/views/overview/1'
def get_one(self, ref_or_id, requester_user):
resp = super(OverviewController, self)._get_one(ref_or_id, requester_user=requester_user, permission_type=PermissionType.ACTION_VIEW) action_api = ActionAPI(**resp.json) result = self._transform_action_api(action_api=action_api, requester_user=requester_user) resp.json = result return resp
'List all actions. Handles requests: GET /actions/views/overview'
def get_all(self, sort=None, offset=0, limit=None, requester_user=None, **raw_filters):
resp = super(OverviewController, self)._get_all(sort=sort, offset=offset, limit=limit, raw_filters=raw_filters) result = [] for item in resp.json: action_api = ActionAPI(**item) result.append(self._transform_action_api(action_api=action_api, requester_user=requester_user)) resp.json = re...
'Outputs the file associated with action entry_point Handles requests: GET /actions/views/entry_point/1'
def get_one(self, ref_or_id, requester_user):
LOG.info('GET /actions/views/entry_point with ref_or_id=%s', ref_or_id) action_db = self._get_by_ref_or_id(ref_or_id=ref_or_id) permission_type = PermissionType.ACTION_VIEW rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=action_db, permission_type=permissio...
'List all the available permission types. Handles requests: GET /rbac/permission_types'
def get_all(self, requester_user):
rbac_utils.assert_user_is_admin(user_db=requester_user) result = get_resource_permission_types_with_descriptions() return result
'List all the available permission types for a particular resource type. Handles requests: GET /rbac/permission_types/<resource type>'
def get_one(self, resource_type, requester_user):
rbac_utils.assert_user_is_admin(user_db=requester_user) all_permission_types = get_resource_permission_types_with_descriptions() permission_types = all_permission_types.get(resource_type, None) if (permission_types is None): raise exc.HTTPNotFound(('Invalid resource type: %s' % resource...
'Create a new triggertype. Handles requests: POST /triggertypes/'
def post(self, triggertype):
try: triggertype_db = TriggerTypeAPI.to_model(triggertype) triggertype_db = TriggerType.add_or_update(triggertype_db) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for triggertype data=%s.', triggertype) abort(http_client.BAD_REQUEST, str...
'Delete a triggertype. Handles requests: DELETE /triggertypes/1 DELETE /triggertypes/pack.name'
def delete(self, triggertype_ref_or_id):
LOG.info('DELETE /triggertypes/ with ref_or_id=%s', triggertype_ref_or_id) triggertype_db = self._get_by_ref_or_id(ref_or_id=triggertype_ref_or_id) triggertype_id = triggertype_db.id try: validate_not_part_of_system_pack(triggertype_db) except ValueValidationException as e: ...
'List trigger by id. Handle: GET /triggers/1'
def get_one(self, trigger_id):
trigger_db = TriggerController.__get_by_id(trigger_id) trigger_api = TriggerAPI.from_model(trigger_db) return trigger_api
'List all triggers. Handles requests: GET /triggers/'
def get_all(self):
trigger_dbs = Trigger.get_all() trigger_apis = [TriggerAPI.from_model(trigger_db) for trigger_db in trigger_dbs] return trigger_apis
'Create a new trigger. Handles requests: POST /triggers/'
def post(self, trigger):
try: trigger_db = TriggerService.create_trigger_db(trigger) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for trigger data=%s.', trigger) abort(http_client.BAD_REQUEST, str(e)) return extra = {'trigger': trigger_db} LOG.audit(('Tr...
'Delete a trigger. Handles requests: DELETE /triggers/1'
def delete(self, trigger_id):
LOG.info('DELETE /triggers/ with id=%s', trigger_id) trigger_db = TriggerController.__get_by_id(trigger_id) try: Trigger.delete(trigger_db) except Exception as e: LOG.exception('Database delete encountered exception during delete of id="%s". ', trigger_id...
'Re-send the provided trigger instance optionally specifying override parameters. Handles requests: POST /triggerinstance/<id>/re_emit POST /triggerinstance/<id>/re_send'
def post(self, trigger_instance_id):
existing_trigger_instance = self._get_one_by_id(id=trigger_instance_id, permission_type=None, requester_user=None) new_payload = copy.deepcopy(existing_trigger_instance.payload) new_payload['__context'] = {'original_id': trigger_instance_id} try: self.trigger_dispatcher.dispatch(existing_trigger...
'List triggerinstance by instance_id. Handle: GET /triggerinstances/1'
def get_one(self, instance_id):
return self._get_one_by_id(instance_id, permission_type=None, requester_user=None)
'List all triggerinstances. Handles requests: GET /triggerinstances/'
def get_all(self, sort=None, offset=0, limit=None, **raw_filters):
trigger_instances = self._get_trigger_instances(sort=sort, offset=offset, limit=limit, raw_filters=raw_filters) return trigger_instances
'Run a chatops command Handles requests: POST /actionalias/match'
def match(self, action_alias_match_api):
command = action_alias_match_api.command try: aliases_resp = super(ActionAliasController, self)._get_all() aliases = [ActionAliasAPI(**alias) for alias in aliases_resp.json] matches = match_command_to_alias(command, aliases) if (len(matches) > 1): raise ActionAliasAmb...
'Get available help strings for action aliases. Handles requests: GET /actionalias/help'
def help(self, filter, pack, limit, offset, **kwargs):
try: aliases_resp = super(ActionAliasController, self)._get_all(**kwargs) aliases = [ActionAliasAPI(**alias) for alias in aliases_resp.json] return generate_helpstring_result(aliases, filter, pack, int(limit), int(offset)) except TypeError as e: LOG.exception('Helpstring reque...
'Create a new ActionAlias. Handles requests: POST /actionalias/'
def post(self, action_alias, requester_user):
permission_type = PermissionType.ACTION_ALIAS_CREATE rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user, resource_api=action_alias, permission_type=permission_type) try: action_alias_db = ActionAliasAPI.to_model(action_alias) LOG.debug('/actionalias/ POST verifie...
'Update an action alias. Handles requests: PUT /actionalias/1'
def put(self, action_alias, ref_or_id, requester_user):
action_alias_db = self._get_by_ref_or_id(ref_or_id=ref_or_id) LOG.debug('PUT /actionalias/ lookup with id=%s found object: %s', ref_or_id, action_alias_db) permission_type = PermissionType.ACTION_ALIAS_MODIFY rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, ...
'Delete an action alias. Handles requests: DELETE /actionalias/1'
def delete(self, ref_or_id, requester_user):
action_alias_db = self._get_by_ref_or_id(ref_or_id=ref_or_id) LOG.debug('DELETE /actionalias/ lookup with id=%s found object: %s', ref_or_id, action_alias_db) permission_type = PermissionType.ACTION_ALIAS_DELETE rbac_utils.assert_user_has_resource_db_permission(user_db=requester_use...
'List key by name. Handle: GET /keys/key1'
def get_one(self, name, requester_user, scope=FULL_SYSTEM_SCOPE, user=None, decrypt=False):
if (not scope): scope = FULL_SYSTEM_SCOPE if user: scope = FULL_USER_SCOPE if (not requester_user): requester_user = UserDB(cfg.CONF.system_user.user) scope = get_datastore_full_scope(scope) self._validate_scope(scope=scope) is_admin = rbac_utils.user_is_admin(user_db=req...
'List all keys. Handles requests: GET /keys/'
def get_all(self, requester_user, prefix=None, scope=FULL_SYSTEM_SCOPE, user=None, decrypt=False, sort=None, offset=0, limit=None, **raw_filters):
if (not scope): scope = FULL_SYSTEM_SCOPE if user: scope = FULL_USER_SCOPE if (not requester_user): requester_user = UserDB(cfg.CONF.system_user.user) scope = get_datastore_full_scope(scope) is_all_scope = (scope == ALL_SCOPE) is_admin = rbac_utils.user_is_admin(user_db=r...
'Create a new entry or update an existing one.'
def put(self, kvp, name, requester_user, scope=FULL_SYSTEM_SCOPE):
if (not scope): scope = FULL_SYSTEM_SCOPE if (not requester_user): requester_user = UserDB(cfg.CONF.system_user.user) scope = getattr(kvp, 'scope', scope) scope = get_datastore_full_scope(scope) self._validate_scope(scope=scope) user = (getattr(kvp, 'user', requester_user.name) o...
'Delete the key value pair. Handles requests: DELETE /keys/1'
def delete(self, name, requester_user, scope=FULL_SYSTEM_SCOPE, user=None):
if (not scope): scope = FULL_SYSTEM_SCOPE if (not requester_user): requester_user = UserDB(cfg.CONF.system_user.user) scope = get_datastore_full_scope(scope) self._validate_scope(scope=scope) user = (user or requester_user.name) assert_user_is_admin_if_user_query_param_is_provide...
'Retrieve a coordination lock name for the provided datastore item name. :param name: Datastore item name (PK). :type name: ``str``'
def _get_lock_name_for_key(self, name, scope=FULL_SYSTEM_SCOPE):
lock_name = ('kvp-crud-%s.%s' % (scope, name)) return lock_name
'Validate that the provider user is either admin or requesting to decrypt value for themselves.'
def _validate_decrypt_query_parameter(self, decrypt, scope, is_admin, requester_user):
is_user_scope = ((scope == USER_SCOPE) or (scope == FULL_USER_SCOPE)) if (decrypt and ((not is_user_scope) and (not is_admin))): msg = 'Decrypt option requires administrator access' raise AccessDeniedError(message=msg, user_db=requester_user)
'Create a new action. Handles requests: POST /actions/'
def post(self, action, requester_user):
permission_type = PermissionType.ACTION_CREATE rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user, resource_api=action, permission_type=permission_type) try: validate_not_part_of_system_pack(action) action_validator.validate_action(action) except (ValidationError, ...
'Delete an action. Handles requests: POST /actions/1?_method=delete DELETE /actions/1 DELETE /actions/mypack.myaction'
def delete(self, ref_or_id, requester_user):
action_db = self._get_by_ref_or_id(ref_or_id=ref_or_id) action_id = action_db.id permission_type = PermissionType.ACTION_DELETE rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=action_db, permission_type=permission_type) try: validate_not_part_of_system_p...
'Method for handling action data files. This method performs two tasks: 1. Writes files to disk 2. Updates affected PackDB model'
def _handle_data_files(self, pack_ref, data_files):
written_file_paths = self._write_data_files_to_disk(pack_ref=pack_ref, data_files=data_files) self._update_pack_model(pack_ref=pack_ref, data_files=data_files, written_file_paths=written_file_paths) return written_file_paths
'Write files to disk.'
def _write_data_files_to_disk(self, pack_ref, data_files):
written_file_paths = [] for data_file in data_files: file_path = data_file['file_path'] content = data_file['content'] file_path = get_pack_resource_file_abs_path(pack_ref=pack_ref, resource_type='action', file_path=file_path) LOG.debug(('Writing data file "%s" to ...
'Update PackDB models (update files list).'
def _update_pack_model(self, pack_ref, data_files, written_file_paths):
file_paths = [] for file_path in written_file_paths: file_path = get_relative_path_to_pack(pack_ref=pack_ref, file_path=file_path) file_paths.append(file_path) pack_db = Pack.get_by_ref(pack_ref) pack_db.files = set(pack_db.files) pack_db.files.update(set(file_paths)) pack_db.fil...
'Write data file on disk.'
def _write_data_file(self, pack_ref, file_path, content):
pack_base_path = get_pack_base_path(pack_name=pack_ref) if (not os.path.isdir(pack_base_path)): raise ValueError(('Directory for pack "%s" doesn\'t exist' % pack_ref)) directory = os.path.dirname(file_path) if (not os.path.isdir(directory)): os.makedirs(directory) with...
'This method processes the file content and removes unicode BOM character if one is present. Note: If we don\'t do that, files view explodes with "UnicodeDecodeError: ... invalid start byte" because the json.dump doesn\'t know how to handle BOM character.'
def _process_file_content(self, content):
if content.startswith(codecs.BOM_UTF8): content = content[BOM_LEN:] return content
'Outputs the content of all the files inside the pack. Handles requests: GET /packs/views/files/<pack_ref_or_id>'
def get_one(self, ref_or_id, requester_user):
pack_db = self._get_by_ref_or_id(ref_or_id=ref_or_id) rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=pack_db, permission_type=PermissionType.PACK_VIEW) if (not pack_db): msg = ('Pack with ref_or_id "%s" does not exist' % ref_or_id) rai...
'Method which returns True if the following file content should be included in the response. Right now we exclude any file with UTF8 BOM character in it - those are most likely binary files such as icon, etc.'
def _include_file(self, file_path, content):
if (codecs.BOM_UTF8 in content[:1024]): return False if ('\x00' in content[:1024]): return False return True
'Outputs the content of a specific file in a pack. Handles requests: GET /packs/views/file/<pack_ref_or_id>/<file path>'
def get_one(self, ref_or_id, file_path, requester_user, if_none_match=None, if_modified_since=None):
pack_db = self._get_by_ref_or_id(ref_or_id=ref_or_id) if (not pack_db): msg = ('Pack with ref_or_id "%s" does not exist' % ref_or_id) raise StackStormDBObjectNotFoundError(msg) if (not file_path): raise ValueError('Missing file path') pack_ref = pack_db.re...
':param exclude_fields: A list of object fields to exclude. :type exclude_fields: ``list``'
def _get_all(self, exclude_fields=None, sort=None, offset=0, limit=None, query_options=None, from_model_kwargs=None, raw_filters=None):
raw_filters = (copy.deepcopy(raw_filters) or {}) exclude_fields = (exclude_fields or []) query_options = (query_options if query_options else self.query_options) sort = (sort.split(',') if sort else []) db_sort_values = [] for sort_key in sort: if sort_key.startswith('-'): di...
':param exclude_fields: A list of object fields to exclude. :type exclude_fields: ``list``'
def _get_one_by_id(self, id, requester_user, permission_type, exclude_fields=None, from_model_kwargs=None):
instance = self._get_by_id(resource_id=id, exclude_fields=exclude_fields) if permission_type: rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=instance, permission_type=permission_type) if (not instance): msg = ('Unable to identify resource wi...
':param exclude_fields: A list of object fields to exclude. :type exclude_fields: ``list``'
def _get_one_by_name_or_id(self, name_or_id, requester_user, permission_type, exclude_fields=None, from_model_kwargs=None):
instance = self._get_by_name_or_id(name_or_id=name_or_id, exclude_fields=exclude_fields) if permission_type: rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=instance, permission_type=permission_type) if (not instance): msg = ('Unable to identify ...
'Retrieve resource object by an id of a name.'
def _get_by_name_or_id(self, name_or_id, exclude_fields=None):
resource_db = self._get_by_id(resource_id=name_or_id, exclude_fields=exclude_fields) if (not resource_db): resource_db = self._get_by_name(resource_name=name_or_id, exclude_fields=exclude_fields) if (not resource_db): msg = ('Resource with a name or id "%s" not found'...
'Retrieve an item given scope and name. Only KeyValuePair now has concept of \'scope\'. :param scope: Scope the key belongs to. :type scope: ``str`` :param name: Name of the key. :type name: ``str``'
def _get_one_by_scope_and_name(self, scope, name, from_model_kwargs=None):
instance = self.access.get_by_scope_and_name(scope=scope, name=name) if (not instance): msg = ('KeyValuePair with name: %s and scope: %s not found in db.' % (name, scope)) raise StackStormDBObjectNotFoundError(msg) from_model_kwargs = (from_model_kwargs or {}) ...
'Validate that provided exclude fields are valid.'
def _validate_exclude_fields(self, exclude_fields):
if (not exclude_fields): return exclude_fields for field in exclude_fields: if (field not in self.valid_exclude_attributes): msg = ('Invalid or unsupported attribute specified: %s' % field) raise ValueError(msg) return exclude_fields