예제 #1
0
파일: action_db.py 프로젝트: st2sandbox/st2
def get_runnertype_by_name(runnertype_name):
    """
    Get an runnertype by name.
    On error, raise ST2ObjectNotFoundError.
    """
    try:
        runnertypes = RunnerType.query(name=runnertype_name)
    except (ValueError, ValidationError) as e:
        LOG.error(
            'Database lookup for name="%s" resulted in exception: %s',
            runnertype_name,
            e,
        )
        raise StackStormDBObjectNotFoundError(
            'Unable to find runnertype with name="%s"' % runnertype_name
        )

    if not runnertypes:
        raise StackStormDBObjectNotFoundError(
            'Unable to find RunnerType with name="%s"' % runnertype_name
        )

    if len(runnertypes) > 1:
        LOG.warning(
            "More than one RunnerType returned from DB lookup by name. "
            "Result list is: %s",
            runnertypes,
        )

    return runnertypes[0]
예제 #2
0
    def get_one(self, ref_or_id, file_path, requester_user, **kwargs):
        """
            Outputs the content of a specific file in a pack.

            Handles requests:
                GET /packs/views/file/<pack_ref_or_id>/<file path>
        """
        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.ref

        # Note: Until list filtering is in place we don't require RBAC check for icon file
        permission_type = PermissionType.PACK_VIEW
        if file_path not in WHITELISTED_FILE_PATHS:
            rbac_utils.assert_user_has_resource_db_permission(
                user_db=requester_user,
                resource_db=pack_db,
                permission_type=permission_type)

        normalized_file_path = get_pack_file_abs_path(pack_ref=pack_ref,
                                                      file_path=file_path)
        if not normalized_file_path or not os.path.isfile(
                normalized_file_path):
            # Ignore references to files which don't exist on disk
            raise StackStormDBObjectNotFoundError('File "%s" not found' %
                                                  (file_path))

        file_size, file_mtime = self._get_file_stats(
            file_path=normalized_file_path)

        response = Response()

        if not self._is_file_changed(file_mtime, **kwargs):
            response.status = http_client.NOT_MODIFIED
        else:
            if file_size is not None and file_size > MAX_FILE_SIZE:
                msg = ('File %s exceeds maximum allowed file size (%s bytes)' %
                       (file_path, MAX_FILE_SIZE))
                raise ValueError(msg)

            content_type = mimetypes.guess_type(normalized_file_path)[0] or \
                'application/octet-stream'

            response.headers['Content-Type'] = content_type
            response.body = self._get_file_content(
                file_path=normalized_file_path)

        response.headers['Last-Modified'] = format_date_time(file_mtime)
        response.headers['ETag'] = repr(file_mtime)

        return response
예제 #3
0
    def get_one(self, group_id, requester_user):
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_is_admin(user_db=requester_user)

        coordinator = coordination.get_coordinator()

        if not isinstance(group_id, six.binary_type):
            group_id = group_id.encode('utf-8')

        try:
            member_ids = list(coordinator.get_members(group_id).get())
        except GroupNotCreated:
            msg = ('Group with ID "%s" not found.' % (group_id.decode('utf-8')))
            raise StackStormDBObjectNotFoundError(msg)

        result = {
            'members': []
        }

        for member_id in member_ids:
            capabilities = coordinator.get_member_capabilities(group_id, member_id).get()
            item = {
                'group_id': group_id.decode('utf-8'),
                'member_id': member_id.decode('utf-8'),
                'capabilities': capabilities
            }
            result['members'].append(item)

        return result
예제 #4
0
파일: packviews.py 프로젝트: joshgre/st2
    def get_one(self, name_or_id, *file_path_components):
        """
            Outputs the content of all the files inside the pack.

            Handles requests:
                GET /packs/views/files/<pack_name>/<file path>
        """
        pack_db = self._get_by_name_or_id(name_or_id=name_or_id)

        if not file_path_components:
            raise ValueError('Missing file path')

        file_path = os.path.join(*file_path_components)
        pack_name = pack_db.name

        normalized_file_path = get_pack_file_abs_path(pack_name=pack_name,
                                                      file_path=file_path)

        if not normalized_file_path or not os.path.isfile(
                normalized_file_path):
            # Ignore references to files which don't exist on disk
            raise StackStormDBObjectNotFoundError('File "%s" not found' %
                                                  (file_path))

        content = self._get_file_content(file_path=normalized_file_path)
        return content
예제 #5
0
    def get(self, *args, **kwargs):
        exclude_fields = kwargs.pop('exclude_fields', None)
        raise_exception = kwargs.pop('raise_exception', False)
        only_fields = kwargs.pop('only_fields', None)

        args = self._process_arg_filters(args)

        instances = self.model.objects(*args, **kwargs)

        if exclude_fields:
            instances = instances.exclude(*exclude_fields)

        if only_fields:
            try:
                instances = instances.only(*only_fields)
            except mongoengine.errors.LookUpError as e:
                msg = (
                    'Invalid or unsupported include attribute specified: %s' %
                    str(e))
                raise ValueError(msg)

        instance = instances[0] if instances else None
        log_query_and_profile_data_for_queryset(queryset=instances)

        if not instance and raise_exception:
            msg = 'Unable to find the %s instance. %s' % (self.model.__name__,
                                                          kwargs)
            raise StackStormDBObjectNotFoundError(msg)

        return instance
예제 #6
0
    def _get_by_ref_or_id(self, ref_or_id, exclude_fields=None, include_fields=None):
        """
        Retrieve resource object by an id of a reference.

        Note: This method throws StackStormDBObjectNotFoundError exception if the object is not
        found in the database.
        """

        if exclude_fields and include_fields:
            msg = ('exclude_fields and include_fields arguments are mutually exclusive. '
                   'You need to provide either one or another, but not both.')
            raise ValueError(msg)

        if ResourceReference.is_resource_reference(ref_or_id):
            # references always contain a dot and id's can't contain it
            is_reference = True
        else:
            is_reference = False

        if is_reference:
            resource_db = self._get_by_ref(resource_ref=ref_or_id, exclude_fields=exclude_fields,
                                          include_fields=include_fields)
        else:
            resource_db = self._get_by_id(resource_id=ref_or_id, exclude_fields=exclude_fields,
                                          include_fields=include_fields)

        if not resource_db:
            msg = 'Resource with a reference or id "%s" not found' % (ref_or_id)
            raise StackStormDBObjectNotFoundError(msg)

        return resource_db
    def get_one(self, ref_or_id, requester_user):
        """
            Outputs the file associated with action entry_point

            Handles requests:
                GET /actions/views/entry_point/1
        """
        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=permission_type)

        pack = getattr(action_db, 'pack', None)
        entry_point = getattr(action_db, 'entry_point', None)

        abs_path = utils.get_entry_point_abs_path(pack, entry_point)

        if not abs_path:
            raise StackStormDBObjectNotFoundError(
                'Action ref_or_id=%s has no entry_point to output' % ref_or_id)

        with open(abs_path) as file:
            content = file.read()

        return content
예제 #8
0
def create_trigger_instance(trigger,
                            payload,
                            occurrence_time,
                            raise_on_no_trigger=False):
    """
    This creates a trigger instance object given trigger and payload.
    Trigger can be just a string reference (pack.name) or a ``dict`` containing 'id' or
    'uid' or type' and 'parameters' keys.

    :param trigger: Trigger reference or dictionary with trigger query filters.
    :type trigger: ``str`` or ``dict``

    :param payload: Trigger payload.
    :type payload: ``dict``
    """
    trigger_db = get_trigger_db_by_ref_or_dict(trigger=trigger)

    if not trigger_db:
        LOG.debug("No trigger in db for %s", trigger)
        if raise_on_no_trigger:
            raise StackStormDBObjectNotFoundError("Trigger not found for %s" %
                                                  trigger)
        return None

    trigger_ref = trigger_db.get_reference().ref

    trigger_instance = TriggerInstanceDB()
    trigger_instance.trigger = trigger_ref
    trigger_instance.payload = payload
    trigger_instance.occurrence_time = occurrence_time
    trigger_instance.status = TRIGGER_INSTANCE_PENDING
    return TriggerInstance.add_or_update(trigger_instance)
    def _schedule_execution(self, action_alias_db, params, notify, context, requester_user,
                            show_secrets):
        action_ref = action_alias_db.action_ref
        action_db = action_utils.get_action_by_ref(action_ref)

        if not action_db:
            raise StackStormDBObjectNotFoundError('Action with ref "%s" not found ' % (action_ref))

        assert_user_has_resource_db_permission(user_db=requester_user, resource_db=action_db,
                                               permission_type=PermissionType.ACTION_EXECUTE)

        try:
            # prior to shipping off the params cast them to the right type.
            params = action_param_utils.cast_params(action_ref=action_alias_db.action_ref,
                                                    params=params,
                                                    cast_overrides=CAST_OVERRIDES)
            if not context:
                context = {
                    'action_alias_ref': reference.get_ref_from_model(action_alias_db),
                    'user': get_system_username()
                }
            liveaction = LiveActionDB(action=action_alias_db.action_ref, context=context,
                                      parameters=params, notify=notify)
            _, action_execution_db = action_service.request(liveaction)
            mask_secrets = self._get_mask_secrets(requester_user, show_secrets=show_secrets)
            return ActionExecutionAPI.from_model(action_execution_db, mask_secrets=mask_secrets)
        except ValueError as e:
            LOG.exception('Unable to execute action.')
            abort(http_client.BAD_REQUEST, str(e))
        except jsonschema.ValidationError as e:
            LOG.exception('Unable to execute action. Parameter validation failed.')
            abort(http_client.BAD_REQUEST, str(e))
        except Exception as e:
            LOG.exception('Unable to execute action. Unexpected error encountered.')
            abort(http_client.INTERNAL_SERVER_ERROR, str(e))
예제 #10
0
    def _get_by_ref_or_id(self, ref_or_id, exclude_fields=None):
        """
        Retrieve resource object by an id of a reference.

        Note: This method throws StackStormDBObjectNotFoundError exception if the object is not
        found in the database.
        """

        if ResourceReference.is_resource_reference(ref_or_id):
            # references always contain a dot and id's can't contain it
            is_reference = True
        else:
            is_reference = False

        if is_reference:
            resource_db = self._get_by_ref(resource_ref=ref_or_id,
                                           exclude_fields=exclude_fields)
        else:
            resource_db = self._get_by_id(resource_id=ref_or_id,
                                          exclude_fields=exclude_fields)

        if not resource_db:
            msg = 'Resource with a reference or id "%s" not found' % (
                ref_or_id)
            raise StackStormDBObjectNotFoundError(msg)

        return resource_db
예제 #11
0
파일: utils.py 프로젝트: yuemanxilou/st2
def create_trigger_instance(trigger,
                            payload,
                            occurrence_time,
                            raise_on_no_trigger=False):
    """
    This creates a trigger instance object given trigger and payload.
    Trigger can be just a string reference (pack.name) or a ``dict`` containing 'id' or
    'uid' or type' and 'parameters' keys.

    :param trigger: Trigger reference or dictionary with trigger query filters.
    :type trigger: ``str`` or ``dict``

    :param payload: Trigger payload.
    :type payload: ``dict``
    """
    # TODO: This is nasty, this should take a unique reference and not a dict
    if isinstance(trigger, six.string_types):
        trigger_db = TriggerService.get_trigger_db_by_ref(trigger)
    else:
        # If id / uid is available we try to look up Trigger by id. This way we can avoid bug in
        # pymongo / mongoengine related to "parameters" dictionary lookups
        trigger_id = trigger.get('id', None)
        trigger_uid = trigger.get('uid', None)

        # TODO: Remove parameters dictionary look up when we can confirm each trigger dictionary
        # passed to this method always contains id or uid
        if trigger_id:
            LOG.debug('Looking up TriggerDB by id: %s', trigger_id)
            trigger_db = TriggerService.get_trigger_db_by_id(id=trigger_id)
        elif trigger_uid:
            LOG.debug('Looking up TriggerDB by uid: %s', trigger_uid)
            trigger_db = TriggerService.get_trigger_db_by_uid(uid=trigger_uid)
        else:
            # Last resort - look it up by parameters
            trigger_type = trigger.get('type', None)
            parameters = trigger.get('parameters', {})

            LOG.debug(
                'Looking up TriggerDB by type and parameters: type=%s, parameters=%s',
                trigger_type, parameters)
            trigger_db = TriggerService.get_trigger_db_given_type_and_params(
                type=trigger_type, parameters=parameters)

    if trigger_db is None:
        LOG.debug('No trigger in db for %s', trigger)
        if raise_on_no_trigger:
            raise StackStormDBObjectNotFoundError('Trigger not found for %s',
                                                  trigger)
        return None

    trigger_ref = trigger_db.get_reference().ref

    trigger_instance = TriggerInstanceDB()
    trigger_instance.trigger = trigger_ref
    trigger_instance.payload = payload
    trigger_instance.occurrence_time = occurrence_time
    trigger_instance.status = TRIGGER_INSTANCE_PENDING
    return TriggerInstance.add_or_update(trigger_instance)
예제 #12
0
파일: trace.py 프로젝트: st2sandbox/st2
def get_trace_db_by_live_action(liveaction):
    """
    Given a liveaction does the best attempt to return a TraceDB.
    1. From trace_context in liveaction.context
    2. From parent in liveaction.context
    3. From action_execution associated with provided liveaction
    4. Creates a new TraceDB (which calling method is on the hook to persist).

    :param liveaction: liveaction from which to figure out a TraceDB.
    :type liveaction: ``LiveActionDB``

    :returns: (boolean, TraceDB) if the TraceDB was created(but not saved to DB) or
               retrieved from the DB and the TraceDB itself.
    :rtype: ``tuple``
    """
    trace_db = None
    created = False
    # 1. Try to get trace_db from liveaction context.
    #    via trigger_instance + rule or via user specified trace_context
    trace_context = liveaction.context.get(TRACE_CONTEXT, None)
    if trace_context:
        trace_context = _get_valid_trace_context(trace_context)
        trace_db = get_trace(trace_context=trace_context,
                             ignore_trace_tag=True)
        # found a trace_context but no trace_db. This implies a user supplied
        # trace_tag so create a new trace_db
        if not trace_db:
            trace_db = TraceDB(trace_tag=trace_context.trace_tag)
            created = True
        return (created, trace_db)
    # 2. If not found then check if parent context contains an execution_id.
    #    This cover case for child execution of a workflow.
    parent_context = executions.get_parent_context(liveaction_db=liveaction)
    if not trace_context and parent_context:
        parent_execution_id = parent_context.get("execution_id", None)
        if parent_execution_id:
            # go straight to a trace_db. If there is a parent execution then that must
            # be associated with a Trace.
            trace_db = get_trace_db_by_action_execution(
                action_execution_id=parent_execution_id)
            if not trace_db:
                raise StackStormDBObjectNotFoundError(
                    "No trace found for execution %s" % parent_execution_id)
            return (created, trace_db)
    # 3. Check if the action_execution associated with liveaction leads to a trace_db
    execution = ActionExecution.get(liveaction__id=str(liveaction.id))
    if execution:
        trace_db = get_trace_db_by_action_execution(action_execution=execution)
    # 4. No trace_db found, therefore create one. This typically happens
    #    when execution is run by hand.
    if not trace_db:
        trace_db = TraceDB(trace_tag="execution-%s" % str(liveaction.id))
        created = True
    return (created, trace_db)
예제 #13
0
    def _get_by_ref_or_id(self, ref_or_id):
        if PolicyTypeReference.is_reference(ref_or_id):
            resource_db = self._get_by_ref(resource_ref=ref_or_id)
        else:
            resource_db = self._get_by_id(resource_id=ref_or_id)

        if not resource_db:
            msg = 'PolicyType with a reference of id "%s" not found.' % (ref_or_id)
            raise StackStormDBObjectNotFoundError(msg)

        return resource_db
예제 #14
0
    def _get_by_ref_or_id(self, ref_or_id, exclude_fields=None):
        resource_db = self._get_by_id(resource_id=ref_or_id, exclude_fields=exclude_fields)

        if not resource_db:
            # Try ref
            resource_db = self._get_by_ref(ref=ref_or_id, exclude_fields=exclude_fields)

        if not resource_db:
            msg = 'Resource with a ref or id "%s" not found' % (ref_or_id)
            raise StackStormDBObjectNotFoundError(msg)

        return resource_db
예제 #15
0
    def get_one(self, ref_or_id, requester_user):
        """
        Outputs the file associated with action entry_point

        Handles requests:
            GET /actions/views/entry_point/1
        """
        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 = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(
            user_db=requester_user,
            resource_db=action_db,
            permission_type=permission_type,
        )

        pack = getattr(action_db, "pack", None)
        entry_point = getattr(action_db, "entry_point", None)

        abs_path = utils.get_entry_point_abs_path(pack, entry_point)

        if not abs_path:
            raise StackStormDBObjectNotFoundError(
                "Action ref_or_id=%s has no entry_point to output" % ref_or_id)

        with codecs.open(abs_path, "r") as fp:
            content = fp.read()

        # Ensure content is utf-8
        if isinstance(content, six.binary_type):
            content = content.decode("utf-8")

        try:
            content_type = mimetypes.guess_type(abs_path)[0]
        except Exception:
            content_type = None

        # Special case if /etc/mime.types doesn't contain entry for yaml, py
        if not content_type:
            _, extension = os.path.splitext(abs_path)
            if extension in [".yaml", ".yml"]:
                content_type = "application/x-yaml"
            elif extension in [".py"]:
                content_type = "application/x-python"
            else:
                content_type = "text/plain"

        response = Response()
        response.headers["Content-Type"] = content_type
        response.text = content
        return response
예제 #16
0
    def get_one(self, ref_or_id, *file_path_components):
        """
            Outputs the content of a specific file in a pack.

            Handles requests:
                GET /packs/views/files/<pack_ref_or_id>/<file path>
        """
        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_components:
            raise ValueError('Missing file path')

        file_path = os.path.join(*file_path_components)
        pack_name = pack_db.name

        normalized_file_path = get_pack_file_abs_path(pack_name=pack_name,
                                                      file_path=file_path)
        if not normalized_file_path or not os.path.isfile(
                normalized_file_path):
            # Ignore references to files which don't exist on disk
            raise StackStormDBObjectNotFoundError('File "%s" not found' %
                                                  (file_path))

        file_size = self._get_file_size(file_path=normalized_file_path)
        if file_size is not None and file_size > MAX_FILE_SIZE:
            msg = ('File %s exceeds maximum allowed file size (%s bytes)' %
                   (file_path, MAX_FILE_SIZE))
            raise ValueError(msg)

        content_type = mimetypes.guess_type(
            normalized_file_path)[0] or 'application/octet-stream'

        response.headers['Cache-Control'] = 'public, max-age=86400'
        response.headers['Content-Type'] = content_type
        response.body = self._get_file_content(file_path=normalized_file_path)
        return response
예제 #17
0
    def get_one(self, ref_or_id, requester_user):
        """
        Outputs the content of all the files inside the pack.

        Handles requests:
            GET /packs/views/files/<pack_ref_or_id>
        """
        pack_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)

        rbac_utils = get_rbac_backend().get_utils_class()
        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)
            raise StackStormDBObjectNotFoundError(msg)

        pack_ref = pack_db.ref
        pack_files = pack_db.files

        result = []
        for file_path in pack_files:
            normalized_file_path = get_pack_file_abs_path(
                pack_ref=pack_ref, file_path=file_path
            )
            if not normalized_file_path or not os.path.isfile(normalized_file_path):
                # Ignore references to files which don't exist on disk
                continue

            file_size = self._get_file_size(file_path=normalized_file_path)
            if file_size is not None and file_size > MAX_FILE_SIZE:
                LOG.debug(
                    'Skipping file "%s" which size exceeds max file size (%s bytes)'
                    % (normalized_file_path, MAX_FILE_SIZE)
                )
                continue

            content = self._get_file_content(file_path=normalized_file_path)

            include_file = self._include_file(file_path=file_path, content=content)
            if not include_file:
                LOG.debug('Skipping binary file "%s"' % (normalized_file_path))
                continue

            item = {"file_path": file_path, "content": content}
            result.append(item)
        return result
예제 #18
0
파일: resource.py 프로젝트: yuemanxilou/st2
    def _get_by_name_or_id(self, name_or_id, exclude_fields=None):
        """
        Retrieve resource object by an id of a name.
        """
        resource_db = self._get_by_id(resource_id=name_or_id, exclude_fields=exclude_fields)

        if not resource_db:
            # Try name
            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' % (name_or_id)
            raise StackStormDBObjectNotFoundError(msg)

        return resource_db
예제 #19
0
def get_runnertype_by_id(runnertype_id):
    """
        Get RunnerType by id.

        On error, raise StackStormDBObjectNotFoundError
    """
    try:
        runnertype = RunnerType.get_by_id(runnertype_id)
    except (ValueError, ValidationError) as e:
        LOG.warning('Database lookup for runnertype with id="%s" resulted in '
                    'exception: %s', runnertype_id, e)
        raise StackStormDBObjectNotFoundError('Unable to find runnertype with '
                                              'id="%s"' % runnertype_id)

    return runnertype
    def get(self, exclude_fields=None, *args, **kwargs):
        raise_exception = kwargs.pop('raise_exception', False)

        instances = self.model.objects(**kwargs)

        if exclude_fields:
            instances = instances.exclude(*exclude_fields)

        instance = instances[0] if instances else None
        log_query_and_profile_data_for_queryset(queryset=instances)

        if not instance and raise_exception:
            msg = 'Unable to find the %s instance. %s' % (self.model.__name__, kwargs)
            raise StackStormDBObjectNotFoundError(msg)

        return instance
예제 #21
0
def get_action_by_id(action_id):
    """
        Get Action by id.

        On error, raise StackStormDBObjectNotFoundError
    """
    action = None

    try:
        action = Action.get_by_id(action_id)
    except (ValueError, ValidationError) as e:
        LOG.warning('Database lookup for action with id="%s" resulted in '
                    'exception: %s', action_id, e)
        raise StackStormDBObjectNotFoundError('Unable to find action with '
                                              'id="%s"' % action_id)

    return action
예제 #22
0
def get_liveaction_by_id(liveaction_id):
    """
        Get LiveAction by id.

        On error, raise ST2DBObjectNotFoundError.
    """
    liveaction = None

    try:
        liveaction = LiveAction.get_by_id(liveaction_id)
    except (ValidationError, ValueError) as e:
        LOG.error('Database lookup for LiveAction with id="%s" resulted in '
                  'exception: %s', liveaction_id, e)
        raise StackStormDBObjectNotFoundError('Unable to find LiveAction with '
                                              'id="%s"' % liveaction_id)

    return liveaction
예제 #23
0
파일: resource.py 프로젝트: kknet/st2
    def _get_one_by_scope_and_name(self, scope, name, from_model_kwargs=None):
        """
        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``
        """
        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 {}
        result = self.model.from_model(instance, **from_model_kwargs)
        LOG.debug('GET with scope=%s and name=%s, client_result=%s', scope, name, result)

        return result
예제 #24
0
파일: keyvalue.py 프로젝트: zwunix/st2
    def get_by_scope_and_name(cls, scope, name):
        """
        Get a key value store given a scope and name.

        :param scope: Scope which the key belongs to.
        :type scope: ``str``

        :param name: Name of the key.
        :type key: ``str``

        :rtype: :class:`KeyValuePairDB` or ``None``
        """
        query_result = cls.impl.query(scope=scope, name=name)

        if not query_result:
            msg = 'The key "%s" does not exist in the StackStorm datastore.'
            raise StackStormDBObjectNotFoundError(msg % name)

        return query_result.first() if query_result else None
예제 #25
0
    def get_one(self, ref_or_id):
        """
            Outputs the content of all the files inside the pack.

            Handles requests:
                GET /packs/views/files/<pack_ref_or_id>
        """
        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)

        pack_name = pack_db.name
        pack_files = pack_db.files

        result = []
        for file_path in pack_files:
            normalized_file_path = get_pack_file_abs_path(pack_name=pack_name,
                                                          file_path=file_path)
            if not normalized_file_path or not os.path.isfile(
                    normalized_file_path):
                # Ignore references to files which don't exist on disk
                continue

            file_size = self._get_file_size(file_path=normalized_file_path)
            if file_size is not None and file_size > MAX_FILE_SIZE:
                LOG.debug(
                    'Skipping file "%s" which size exceeds max file size (%s bytes)'
                    % (normalized_file_path, MAX_FILE_SIZE))
                continue

            content = self._get_file_content(file_path=normalized_file_path)

            include_file = self._include_file(file_path=file_path,
                                              content=content)
            if not include_file:
                LOG.debug('Skipping binary file "%s"' % (normalized_file_path))
                continue

            item = {'file_path': file_path, 'content': content}
            result.append(item)
        return result
예제 #26
0
파일: trace.py 프로젝트: st2sandbox/st2
def get_trace(trace_context, ignore_trace_tag=False):
    """
    :param trace_context: context object using which a trace can be found.
    :type trace_context: ``dict`` or ``TraceContext``

    :param ignore_trace_tag: Even if a trace_tag is provided will be ignored.
    :type ignore_trace_tag: ``str``

    :rtype: ``TraceDB``
    """

    trace_context = _get_valid_trace_context(trace_context)

    if not trace_context.id_ and not trace_context.trace_tag:
        raise ValueError(
            "Atleast one of id_ or trace_tag should be specified.")

    if trace_context.id_:
        try:
            return Trace.get_by_id(trace_context.id_)
        except (ValidationError, ValueError):
            LOG.warning(
                'Database lookup for Trace with id="%s" failed.',
                trace_context.id_,
                exc_info=True,
            )
            raise StackStormDBObjectNotFoundError(
                'Unable to find Trace with id="%s"' % trace_context.id_)

    if ignore_trace_tag:
        return None

    traces = Trace.query(trace_tag=trace_context.trace_tag)

    # Assume this method only handles 1 trace.
    if len(traces) > 1:
        raise UniqueTraceNotFoundException(
            "More than 1 Trace matching %s found." % trace_context.trace_tag)

    return traces[0]
예제 #27
0
파일: utils.py 프로젝트: yangjiebeijing/st2
def create_trigger_instance(trigger,
                            payload,
                            occurrence_time,
                            raise_on_no_trigger=False):
    """
    This creates a trigger instance object given trigger and payload.
    Trigger can be just a string reference (pack.name) or a ``dict``
    containing  'type' and 'parameters'.

    :param trigger: Dictionary with trigger query filters.
    :type trigger: ``dict``

    :param payload: Trigger payload.
    :type payload: ``dict``
    """
    # TODO: This is nasty, this should take a unique reference and not a dict
    if isinstance(trigger, six.string_types):
        trigger_db = TriggerService.get_trigger_db_by_ref(trigger)
    else:
        type_ = trigger.get('type', None)
        parameters = trigger.get('parameters', {})
        trigger_db = TriggerService.get_trigger_db_given_type_and_params(
            type=type_, parameters=parameters)

    if trigger_db is None:
        LOG.debug('No trigger in db for %s', trigger)
        if raise_on_no_trigger:
            raise StackStormDBObjectNotFoundError('Trigger not found for %s',
                                                  trigger)
        return None

    trigger_ref = trigger_db.get_reference().ref

    trigger_instance = TriggerInstanceDB()
    trigger_instance.trigger = trigger_ref
    trigger_instance.payload = payload
    trigger_instance.occurrence_time = occurrence_time
    trigger_instance.status = TRIGGER_INSTANCE_PENDING
    return TriggerInstance.add_or_update(trigger_instance)
예제 #28
0
    def get_one(self, ref_or_id):
        """
            Outputs the file associated with action entry_point

            Handles requests:
                GET /actions/views/entry_point/1
        """
        LOG.info('GET /actions/views/overview with ref_or_id=%s', ref_or_id)
        action_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)

        pack = getattr(action_db, 'pack', None)
        entry_point = getattr(action_db, 'entry_point', None)

        abs_path = utils.get_entry_point_abs_path(pack, entry_point)

        if not abs_path:
            raise StackStormDBObjectNotFoundError(
                'Action ref_or_id=%s has no entry_point to output' % ref_or_id)

        with open(abs_path) as file:
            content = file.read()

        return content
예제 #29
0
    def get_one(self, action_id):
        """
            Outputs the file associated with action entry_point

            Handles requests:
                GET /actions/views/entry_point/1
        """
        LOG.info('GET /actions/views/overview with id=%s', action_id)
        action_db = LookupUtils._get_action_by_id(action_id)

        pack = getattr(action_db, 'pack', None)
        entry_point = getattr(action_db, 'entry_point', None)

        abs_path = RunnerContainerService.get_entry_point_abs_path(
            pack, entry_point)

        if not abs_path:
            raise StackStormDBObjectNotFoundError(
                'Action id=%s has no entry_point to output' % action_id)

        with open(abs_path) as file:
            content = file.read()

        return content