예제 #1
0
    def __init__(self, policy_json=None):
        self.gate_name = policy_json.get('gate')
        self.trigger_name = policy_json.get('trigger')
        self.trigger_params = { p.get('name'): p.get('value') for p in policy_json.get('params')}

        action = policy_json.get('action', '').lower()
        try:
            self.action = GateAction.__members__[action]
        except KeyError:
            raise InvalidGateAction(action=action, gate_name=self.gate_name, trigger_name=self.trigger_name,
                                    valid_actions=filter(lambda x: not x.startswith('_'), GateAction.__dict__.keys()))

        self.error_exc = None
        self.errors = []

        # Configure the trigger instance
        try:
            self.gate_cls = Gate.registry[self.gate_name.lower()]
            try:
                selected_trigger_cls = self.gate_cls.get_trigger_named(self.trigger_name)
                self.configured_trigger = selected_trigger_cls(parent_gate_cls=self.gate_cls, **self.trigger_params)
            except [TriggerNotFoundError, InvalidParameterError, InputParameterValidationError] as e:
                # Error finding or initializing the trigger
                log.exception('Policy rule execution exception: {}'.format(e))
                self.error_exc = TriggerNotFoundError(self.gate_name, self.trigger_name)
                self.configured_trigger = None
                raise

        except PolicyError:
            raise
        except KeyError:
            # Gate not found
            raise GateNotFoundError(self.gate_name)
        except Exception as e:
            raise ValidationError(e)
예제 #2
0
 def get_trigger_named(cls, name):
     """
     Returns an the trigger class with the specified name
     :param name: name to match against the trigger classes' __trigger_name__ value 
     :return: a trigger class object 
     """
     found = filter(lambda x: x.__trigger_name__ == name, cls.__triggers__)
     if found:
         return found[0]
     else:
         raise TriggerNotFoundError(trigger_name=name,
                                    gate_name=cls.__gate_name__)
예제 #3
0
    def execute(self, image_obj, exec_context):
        """
        Execute the trigger specified in the rule with the image and gate (for prepared context) and exec_context)

        :param image_obj: The image to execute against
        :param exec_context: The prepared execution context from the gate init
        :return: a tuple of a list of erros and a list of PolicyRuleDecisions, one for each fired trigger match produced by the trigger execution
        """

        matches = None

        try:
            if not self.configured_trigger:
                log.error(
                    'No configured trigger to execute for gate {} and trigger: {}. Returning'
                    .format(self.gate_name, self.trigger_name))
                raise TriggerNotFoundError(trigger_name=self.trigger_name,
                                           gate_name=self.gate_name)

            try:
                self.configured_trigger.execute(image_obj, exec_context)
            except TriggerEvaluationError as e:
                log.exception('Error executing trigger {} on image {}'.format(
                    self.trigger_name, image_obj.id))
                raise
            except Exception as e:
                log.exception(
                    'Unmapped exception caught during trigger evaluation')
                raise TriggerEvaluationError(
                    'Could not evaluate trigger due to error in evaluation execution'
                )

            matches = self.configured_trigger.fired
            decisions = []

            # Try all rules and record all decisions and errors so multiple errors can be reported if present, not just the first encountered
            for match in matches:
                try:
                    decisions.append(
                        PolicyRuleDecision(trigger_match=match,
                                           policy_rule=self))
                except TriggerEvaluationError as e:
                    log.exception(
                        'Policy rule decision mapping exception: {}'.format(e))
                    self.errors.append(str(e))

            return self.errors, decisions
        except Exception as e:
            log.exception('Error executing trigger!')
            raise
예제 #4
0
    def __init__(self, parent, policy_json=None):
        super(ExecutablePolicyRule, self).__init__(parent, policy_json)

        # Configure the trigger instance
        try:
            self.gate_cls = Gate.get_gate_by_name(self.gate_name)
        except KeyError:
            # Gate not found
            self.error_exc = GateNotFoundError(gate=self.gate_name, valid_gates=Gate.registered_gate_names(), rule_id=self.rule_id)
            self.configured_trigger = None
            raise self.error_exc

        try:
            selected_trigger_cls = self.gate_cls.get_trigger_named(self.trigger_name.lower())
        except KeyError:
            self.error_exc = TriggerNotFoundError(valid_triggers=self.gate_cls.trigger_names(), trigger=self.trigger_name, gate=self.gate_name, rule_id=self.rule_id)
            self.configured_trigger = None
            raise self.error_exc

        try:
            try:
                self.configured_trigger = selected_trigger_cls(parent_gate_cls=self.gate_cls, rule_id=self.rule_id, **self.trigger_params)
            except (TriggerNotFoundError, InvalidParameterError, ParameterValueInvalidError) as e:
                # Error finding or initializing the trigger
                self.error_exc = e
                self.configured_trigger = None

                if hasattr(e, 'gate') and e.gate is None:
                    e.gate = self.gate_name
                if hasattr(e, 'trigger') and e.trigger is None:
                    e.trigger = self.trigger_name
                if hasattr(e, 'rule_id') and e.rule_id is None:
                    e.rule_id = self.rule_id
                raise e
        except PolicyError:
            raise # To filter out already-handled errors
        except Exception as e:
            raise ValidationError.caused_by(e)
예제 #5
0
    def __init__(self, policy_json=None):
        self.gate_name = policy_json.get('gate')
        self.trigger_name = policy_json.get('trigger')
        self.rule_id = policy_json.get('id')

        # Convert to lower-case for case-insensitive matches
        self.trigger_params = {
            p.get('name').lower(): p.get('value')
            for p in policy_json.get('params')
        }

        action = policy_json.get('action', '').lower()
        try:
            self.action = GateAction.__members__[action]
        except KeyError:
            raise InvalidGateAction(gate=self.gate_name,
                                    trigger=self.trigger_name,
                                    rule_id=self.rule_id,
                                    action=action,
                                    valid_actions=filter(
                                        lambda x: not x.startswith('_'),
                                        GateAction.__dict__.keys()))

        self.error_exc = None
        self.errors = []

        # Configure the trigger instance
        try:
            self.gate_cls = Gate.get_gate_by_name(self.gate_name)
        except KeyError:
            # Gate not found
            self.error_exc = GateNotFoundError(
                gate=self.gate_name,
                valid_gates=Gate.registered_gate_names(),
                rule_id=self.rule_id)
            self.configured_trigger = None
            raise self.error_exc

        try:
            selected_trigger_cls = self.gate_cls.get_trigger_named(
                self.trigger_name.lower())
        except KeyError:
            self.error_exc = TriggerNotFoundError(
                valid_triggers=self.gate_cls.trigger_names(),
                trigger=self.trigger_name,
                gate=self.gate_name,
                rule_id=self.rule_id)
            self.configured_trigger = None
            raise self.error_exc

        try:

            try:
                self.configured_trigger = selected_trigger_cls(
                    parent_gate_cls=self.gate_cls,
                    rule_id=self.rule_id,
                    **self.trigger_params)
            except [
                    TriggerNotFoundError, InvalidParameterError,
                    ParameterValueInvalidError
            ] as e:
                # Error finding or initializing the trigger
                log.exception('Policy rule execution exception: {}'.format(e))
                self.error_exc = e
                self.configured_trigger = None

                if hasattr(e, 'gate') and e.gate is None:
                    e.gate = self.gate_name
                if hasattr(e, 'trigger') and e.trigger is None:
                    e.trigger = self.trigger_name
                if hasattr(e, 'rule_id') and e.rule_id is None:
                    e.rule_id = self.rule_id
                raise e
        except PolicyError:
            raise  # To filter out already-handled errors
        except Exception as e:
            raise ValidationError.caused_by(e)