Exemple #1
0
    def __init__(self, api_key=None):
        """
        :type api_key: str
        :param api_key: The API key. If no key is passed, the environment
            variable NEW_RELIC_API_KEY is used.
        :raises: If the api_key parameter is not present, and no environment
            variable is present, a :class:`newrelic_api.exceptions.ConfigurationException`
            is raised.
        """
        self.api_key = api_key or os.environ.get('NEW_RELIC_API_KEY') or os.environ.get('NEWRELIC_API_KEY')

        if not self.api_key:
            raise ConfigurationException('NEW_RELIC_API_KEY or NEWRELIC_API_KEY not present in environment!')

        self.headers = {
            'Content-type': 'application/json',
            'X-Api-Key': self.api_key,
        }
    def update(self,
               alert_condition_id,
               policy_id,
               type=None,
               condition_scope=None,
               name=None,
               entities=None,
               metric=None,
               runbook_url=None,
               terms=None,
               user_defined=None,
               violation_close_timer=None,
               enabled=None):
        """
        Updates any of the optional parameters of the alert condition

        :type alert_condition_id: int
        :param alert_condition_id: Alerts condition id to update

        :type policy_id: int
        :param policy_id: Alert policy id where target alert condition belongs to

        :type type: str
        :param type: The type of the condition, can be apm_app_metric,
            apm_kt_metric, servers_metric, browser_metric, mobile_metric

        :type condition_scope: str
        :param condition_scope: The scope of the condition, can be instance or application

        :type name: str
        :param name: The name of the server

        :type entities: list[str]
        :param name: entity ids to which the alert condition is applied

        :type : str
        :param metric: The target metric

        :type : str
        :param runbook_url: The url of the runbook

        :type terms: list[hash]
        :param terms: list of hashes containing threshold config for the alert

        :type user_defined: hash
        :param user_defined: hash containing threshold user_defined for the alert
            required if metric is set to user_defined

        :type violation_close_timer: int
        :param violation_close_timer: Use to automatically close instance-based
            violations, including JVM health metric violations, after the number of hours specified

        :type enabled: bool
        :param enabled: Whether to enable that alert condition

        :rtype: dict
        :return: The JSON response of the API

        :raises: This will raise a
            :class:`NewRelicAPIServerException<newrelic_api.exceptions.NoEntityException>`
            if target alert condition is not included in target policy

        :raises: This will raise a
            :class:`ConfigurationException<newrelic_api.exceptions.ConfigurationException>`
            if metric is set as user_defined but user_defined config is not passed

        ::

            {
                "condition": {
                    "id": "integer",
                    "type": "string",
                    "condition_scope":  "string",
                    "name": "string",
                    "enabled": "boolean",
                    "entities": [
                        "integer"
                    ],
                    "metric": "string",
                    "runbook_url": "string",
                    "violation_close_timer": integer,
                    "terms": [
                        {
                            "duration": "string",
                            "operator": "string",
                            "priority": "string",
                            "threshold": "string",
                            "time_function": "string"
                        }
                    ],
                    "user_defined": {
                        "metric": "string",
                        "value_function": "string"
                    }
                }
            }

        """
        conditions_dict = self.list(policy_id)
        target_condition = None
        for condition in conditions_dict['conditions']:
            if int(condition['id']) == alert_condition_id:
                target_condition = condition
                break

        if target_condition is None:
            raise NoEntityException(
                'Target alert condition is not included in that policy.'
                'policy_id: {}, alert_condition_id {}'.format(
                    policy_id, alert_condition_id))

        data = {
            'condition': {
                'type':
                type or target_condition['type'],
                'name':
                name or target_condition['name'],
                'entities':
                entities or target_condition['entities'],
                'condition_scope':
                condition_scope or target_condition.get('condition_scope'),
                'terms':
                terms or target_condition['terms'],
                'metric':
                metric or target_condition['metric'],
                'runbook_url':
                runbook_url or target_condition.get('runbook_url'),
                'violation_close_timer':
                violation_close_timer
                or target_condition.get('violation_close_timer'),
            }
        }

        if enabled is not None:
            data['condition']['enabled'] = str(enabled).lower()

        if data['condition']['metric'] == 'user_defined':
            if user_defined:
                data['condition']['user_defined'] = user_defined
            elif 'user_defined' in target_condition:
                data['condition']['user_defined'] = target_condition[
                    'user_defined']
            else:
                raise ConfigurationException(
                    'Metric is set as user_defined but no user_defined config specified'
                )

        return self._put(url='{0}alerts_conditions/{1}.json'.format(
            self.URL, alert_condition_id),
                         headers=self.headers,
                         data=data)
    def create(self,
               policy_id,
               type,
               name,
               entities,
               metric,
               terms,
               condition_scope=None,
               runbook_url=None,
               user_defined=None,
               violation_close_timer=None,
               enabled=True):
        """
        Creates an alert condition

        :type policy_id: int
        :param policy_id: Alert policy id where target alert condition belongs to

        :type type: str
        :param type: The type of the condition, can be apm_app_metric,
            apm_kt_metric, servers_metric, browser_metric, mobile_metric

        :type name: str
        :param name: The name of the server

        :type entities: list[str]
        :param name: entity ids to which the alert condition is applied

        :type : str
        :param metric: The target metric

        :type condition_scope: str
        :param condition_scope: The scope of the condition, can be instance or application

        :type : str
        :param runbook_url: The url of the runbook

        :type terms: list[hash]
        :param terms: list of hashes containing threshold config for the alert

        :type user_defined: hash
        :param user_defined: hash containing threshold user_defined for the alert
            required if metric is set to user_defined

        :type violation_close_timer: int
        :param violation_close_timer: Use to automatically close instance-based
            violations, including JVM health metric violations, after the number of hours specified

        :type enabled: bool
        :param enabled: Whether to enable that alert condition

        :rtype: dict
        :return: The JSON response of the API

        ::

            {
                "condition": {
                    "id": "integer",
                    "type": "string",
                    "condition_scope":  "string",
                    "name": "string",
                    "enabled": "boolean",
                    "entities": [
                        "integer"
                    ],
                    "metric": "string",
                    "runbook_url": "string",
                    "violation_close_timer": integer,
                    "terms": [
                        {
                            "duration": "string",
                            "operator": "string",
                            "priority": "string",
                            "threshold": "string",
                            "time_function": "string"
                        }
                    ],
                    "user_defined": {
                        "metric": "string",
                        "value_function": "string"
                    }
                }
            }

        """

        data = {
            'condition': {
                'type': type,
                'name': name,
                'enabled': enabled,
                'entities': entities,
                'condition_scope': condition_scope,
                'terms': terms,
                'metric': metric,
                'runbook_url': runbook_url,
                'violation_close_timer': violation_close_timer
            }
        }

        if metric == 'user_defined':
            if user_defined:
                data['condition']['user_defined'] = user_defined
            else:
                raise ConfigurationException(
                    'Metric is set as user_defined but no user_defined config specified'
                )

        return self._post(url='{0}alerts_conditions/policies/{1}.json'.format(
            self.URL, policy_id),
                          headers=self.headers,
                          data=data)
    def update(  # noqa: C901
            self,
            alert_condition_nrql_id,
            policy_id,
            name=None,
            threshold_type=None,
            query=None,
            since_value=None,
            terms=None,
            expected_groups=None,
            value_function=None,
            runbook_url=None,
            ignore_overlap=None,
            violation_time_limit_seconds=None,
            enabled=True):
        """
        Updates any of the optional parameters of the alert condition nrql

        :type alert_condition_nrql_id: int
        :param alert_condition_nrql_id: Alerts condition NRQL id to update

        :type policy_id: int
        :param policy_id: Alert policy id where target alert condition belongs to

        :type condition_scope: str
        :param condition_scope: The scope of the condition, can be instance or application

        :type name: str
        :param name: The name of the alert

        :type threshold_type: str
        :param threshold_type: The tthreshold_typeype of the condition, can be static or outlier

        :type query: str
        :param query: nrql query for the alerts

        :type since_value: str
        :param since_value: since value for the alert

        :type terms: list[hash]
        :param terms: list of hashes containing threshold config for the alert

        :type expected_groups: int
        :param expected_groups: expected groups setting for outlier alerts

        :type value_function: str
        :param type: value function for static alerts

        :type runbook_url: str
        :param runbook_url: The url of the runbook

        :type ignore_overlap: bool
        :param ignore_overlap: Whether to ignore overlaps for outlier alerts

        :type violation_time_limit_seconds: int
        :param violation_time_limit_seconds: Use to automatically close
            instance-based violations after the number of seconds specified

        :type enabled: bool
        :param enabled: Whether to enable that alert condition

        :rtype: dict
        :return: The JSON response of the API

        :raises: This will raise a
            :class:`NewRelicAPIServerException<newrelic_api.exceptions.NoEntityException>`
            if target alert condition is not included in target policy

        :raises: This will raise a
            :class:`ConfigurationException<newrelic_api.exceptions.ConfigurationException>`
            if metric is set as user_defined but user_defined config is not passed
        ::
        {
            "nrql_condition": {
                "name": "string",
                "runbook_url": "string",
                "enabled": "boolean",
                "expected_groups": "integer",
                "ignore_overlap": "boolean",
                "value_function": "string",
                "violation_time_limit_seconds": "integer",
                "terms": [
                    {
                        "duration": "string",
                        "operator": "string",
                        "priority": "string",
                        "threshold": "string",
                        "time_function": "string"
                    }
                ],
                "nrql": {
                    "query": "string",
                    "since_value": "string"
                }
            }
        }
        """

        conditions_nrql_dict = self.list(policy_id)
        target_condition_nrql = None
        for condition in conditions_nrql_dict['nrql_conditions']:
            if int(condition['id']) == alert_condition_nrql_id:
                target_condition_nrql = condition
                break

        if target_condition_nrql is None:
            raise NoEntityException(
                'Target alert condition nrql is not included in that policy.'
                'policy_id: {}, alert_condition_nrql_id {}'.format(
                    policy_id, alert_condition_nrql_id))

        data = {
            'nrql_condition': {
                'type': threshold_type or target_condition_nrql['type'],
                'enabled': target_condition_nrql['enabled'],
                'name': name or target_condition_nrql['name'],
                'terms': terms or target_condition_nrql['terms'],
                'nrql': {
                    'query':
                    query or target_condition_nrql['nrql']['query'],
                    'since_value':
                    since_value
                    or target_condition_nrql['nrql']['since_value'],
                }
            }
        }

        if enabled is not None:
            data['nrql_condition']['enabled'] = str(enabled).lower()

        if runbook_url is not None:
            data['nrql_condition']['runbook_url'] = runbook_url
        elif 'runbook_url' in target_condition_nrql:
            data['nrql_condition']['runbook_url'] = target_condition_nrql[
                'runbook_url']

        if expected_groups is not None:
            data['nrql_condition']['expected_groups'] = expected_groups
        elif 'expected_groups' in target_condition_nrql:
            data['nrql_condition']['expected_groups'] = target_condition_nrql[
                'expected_groups']

        if ignore_overlap is not None:
            data['nrql_condition']['ignore_overlap'] = ignore_overlap
        elif 'ignore_overlap' in target_condition_nrql:
            data['nrql_condition']['ignore_overlap'] = target_condition_nrql[
                'ignore_overlap']

        if value_function is not None:
            data['nrql_condition']['value_function'] = value_function
        elif 'value_function' in target_condition_nrql:
            data['nrql_condition']['value_function'] = target_condition_nrql[
                'value_function']

        if violation_time_limit_seconds is not None:
            data['nrql_condition'][
                'violation_time_limit_seconds'] = violation_time_limit_seconds
        elif 'violation_time_limit_seconds' in target_condition_nrql:
            data['nrql_condition']['violation_time_limit_seconds'] = \
                target_condition_nrql['violation_time_limit_seconds']

        if data['nrql_condition']['type'] == 'static':
            if 'value_function' not in data['nrql_condition']:
                raise ConfigurationException(
                    'Alert is set as static but no value_function config specified'
                )
            data['nrql_condition'].pop('expected_groups', None)
            data['nrql_condition'].pop('ignore_overlap', None)

        elif data['nrql_condition']['type'] == 'outlier':
            if 'expected_groups' not in data['nrql_condition']:
                raise ConfigurationException(
                    'Alert is set as outlier but expected_groups config is not specified'
                )
            if 'ignore_overlap' not in data['nrql_condition']:
                raise ConfigurationException(
                    'Alert is set as outlier but ignore_overlap config is not  specified'
                )
            data['nrql_condition'].pop('value_function', None)

        return self._put(url='{0}alerts_nrql_conditions/{1}.json'.format(
            self.URL, alert_condition_nrql_id),
                         headers=self.headers,
                         data=data)
Exemple #5
0
    def create(  # noqa: C901
            self,
            policy_id,
            name,
            threshold_type,
            query,
            terms,
            expected_groups=None,
            value_function=None,
            runbook_url=None,
            ignore_overlap=None,
            violation_time_limit_seconds=None,
            enabled=True,
            signal=None):
        """
        Creates an alert condition nrql

        :type policy_id: int
        :param policy_id: Alert policy id where target alert condition nrql belongs to

        :type name: str
        :param name: The name of the alert

        :type threshold_type: str
        :param type: The threshold_type of the condition, can be static or outlier

        :type query: str
        :param query: nrql query for the alerts

        :type terms: list[hash]
        :param terms: list of hashes containing threshold config for the alert

        :type expected_groups: int
        :param expected_groups: expected groups setting for outlier alerts

        :type value_function: str
        :param type: value function for static alerts

        :type runbook_url: str
        :param runbook_url: The url of the runbook

        :type ignore_overlap: bool
        :param ignore_overlap: Whether to ignore overlaps for outlier alerts

        :type violation_time_limit_seconds: int
        :param violation_time_limit_seconds: Use to automatically close
            instance-based violations after the number of seconds specified

        :type enabled: bool
        :param enabled: Whether to enable that alert condition

        :type signal: list[hash]
        :param terms: list of hashes containing signal config for the alert

        :rtype: dict
        :return: The JSON response of the API

        :raises: This will raise a
            :class:`NewRelicAPIServerException<newrelic_api.exceptions.NoEntityException>`
            if target alert condition is not included in target policy

        :raises: This will raise a
            :class:`ConfigurationException<newrelic_api.exceptions.ConfigurationException>`
            if metric is set as user_defined but user_defined config is not passed
        ::
        {
            "nrql_condition": {
                "name": "string",
                "runbook_url": "string",
                "enabled": "boolean",
                "expected_groups": "integer",
                "ignore_overlap": "boolean",
                "value_function": "string",
                "terms": [
                    {
                        "duration": "string",
                        "operator": "string",
                        "priority": "string",
                        "threshold": "string",
                        "time_function": "string"
                    }
                ],
                "nrql": {
                    "query": "string"
                }
            }
        }
        """

        data = {
            'nrql_condition': {
                'type': threshold_type,
                'name': name,
                'enabled': enabled,
                'terms': terms,
                'nrql': {
                    'query': query
                }
            }
        }

        if runbook_url is not None:
            data['nrql_condition']['runbook_url'] = runbook_url

        if expected_groups is not None:
            data['nrql_condition']['expected_groups'] = expected_groups

        if ignore_overlap is not None:
            data['nrql_condition']['ignore_overlap'] = ignore_overlap

        if value_function is not None:
            data['nrql_condition']['value_function'] = value_function

        if violation_time_limit_seconds is not None:
            data['nrql_condition'][
                'violation_time_limit_seconds'] = violation_time_limit_seconds

        if data['nrql_condition']['type'] == 'static':
            if 'value_function' not in data['nrql_condition']:
                raise ConfigurationException(
                    'Alert is set as static but no value_function config specified'
                )
            data['nrql_condition'].pop('expected_groups', None)
            data['nrql_condition'].pop('ignore_overlap', None)

        elif data['nrql_condition']['type'] == 'outlier':
            if 'expected_groups' not in data['nrql_condition']:
                raise ConfigurationException(
                    'Alert is set as outlier but expected_groups config is not specified'
                )
            if 'ignore_overlap' not in data['nrql_condition']:
                raise ConfigurationException(
                    'Alert is set as outlier but ignore_overlap config is not  specified'
                )
            data['nrql_condition'].pop('value_function', None)

        if signal is not None:
            data['nrql_condition']['signal'] = signal

        return self._post(
            url='{0}alerts_nrql_conditions/policies/{1}.json'.format(
                self.URL, policy_id),
            headers=self.headers,
            data=data)