Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

query manager generic tag mapping #9803

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 3 additions & 15 deletions datadog_checks_base/datadog_checks/base/stubs/aggregator.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,24 +39,12 @@ def backend_normalize_metric_name(metric_name):


def check_tag_names(metric, tags):
forbidden_tags = [
'cluster_name',
'clustername',
'cluster',
'clusterid',
'cluster_id',
'env',
'host_name',
'hostname',
'host',
'service',
'version',
]

if not os.environ.get('DDEV_SKIP_GENERIC_TAGS_CHECK'):
from datadog_checks.base.utils.tagging import GENERIC_TAGS

for tag in tags:
tag_name = tag.split(':')[0]
if tag_name in forbidden_tags:
if tag_name in GENERIC_TAGS:
raise Exception(
"Metric {} was submitted with a forbidden tag: {}. Please rename this tag, or skip "
"the tag validation with DDEV_SKIP_GENERIC_TAGS_CHECK environment variable.".format(
Expand Down
8 changes: 3 additions & 5 deletions datadog_checks_base/datadog_checks/base/utils/db/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ def __init__(
self.error_handler = error_handler
self.queries = [Query(payload) for payload in queries or []] # type: List[Query]
self.hostname = hostname # type: str
self.logger = self.check.log

custom_queries = list(self.check.instance.get('custom_queries', [])) # type: List[str]
use_global_custom_queries = self.check.instance.get('use_global_custom_queries', True) # type: str
Expand Down Expand Up @@ -145,10 +144,9 @@ def execute(self, extra_tags=None):
# anything but are collected into the row values for other columns to reference.
if transformer is None:
continue
elif column_type == 'tag':
tags.append(transformer(None, column_value)) # get_tag transformer
elif column_type == 'tag_list':
tags.extend(transformer(None, column_value)) # get_tag_list transformer
elif column_type == 'tag' or column_type == 'tag_list':
# get_tag transformer or get_tag_list transformer
tags.extend(transformer(None, column_value, self.check))
else:
submission_queue.append((transformer, column_value))

Expand Down
36 changes: 26 additions & 10 deletions datadog_checks_base/datadog_checks/base/utils/db/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
from datetime import datetime
from typing import Any, Callable, Dict, List, Tuple

from datadog_checks.base import AgentCheck
from datadog_checks.base.types import ServiceCheckStatus
from datadog_checks.base.utils.db.types import Transformer, TransformerFactory
from datadog_checks.base.utils.tagging import GENERIC_TAGS

from ... import is_affirmative
from ...constants import ServiceCheck
Expand Down Expand Up @@ -43,19 +45,32 @@ def get_tag(transformers, column_name, **modifiers):
to the string `true` or `false`. So for example if you named the column `alive` and the result was the
number `0` the tag will be `alive:false`.
"""
template = '{}:{{}}'.format(column_name)
boolean = is_affirmative(modifiers.pop('boolean', None))

def tag(_, value, **kwargs):
# type: (List, str, Dict[str, Any]) -> str
def tag(_, value, check, **kwargs):
# type: (List, str, AgentCheck, Dict[str, Any]) -> List[str]
if boolean:
value = str(is_affirmative(value)).lower()

return template.format(value)
return _transform_tag(name, value, check)

return tag


def _transform_tag(name, value, check):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should not modify the database utils at all and instead add your logic here:

def _normalize_tags_type(self, tags, device_name=None, metric_name=None):
# type: (Sequence[Union[None, str, bytes]], str, str) -> List[str]
"""
Normalize tags contents and type:
- append `device_name` as `device:` tag
- normalize tags type
- doesn't mutate the passed list, returns a new list
"""

# type: (str, str, AgentCheck) -> List[str]
template = '{}:{}'
tags = []
if name in GENERIC_TAGS:
new_name = '{}_{}'.format(check.name, name)
if not not is_affirmative(check.instance.get('disable_generic_tags', False)):
check._log_deprecation(name, new_name)
tags.append(template.format(name, value))
tags.append(template.format(new_name, value))
else:
tags.append(template.format(name, value))
return tags


def get_tag_list(transformers, column_name, **modifiers):
# type: (Dict[str, Transformer], str, Any) -> Transformer
"""
Expand All @@ -67,14 +82,15 @@ def get_tag_list(transformers, column_name, **modifiers):
For example, if the column is named `server_tag` and the column returned the value `'us,primary'`, then all
submissions for that row will be tagged by `server_tag:us` and `server_tag:primary`.
"""
template = '%s:{}' % column_name

def tag_list(_, value, **kwargs):
# type: (List, str, Dict[str, Any]) -> List[str]
def tag_list(_, value, check, **kwargs):
# type: (List, str, AgentCheck, Dict[str, Any]) -> List[str]
if isinstance(value, str):
value = [v.strip() for v in value.split(',')]

return [template.format(v) for v in value]
tags = []
for v in value:
tags.extend(_transform_tag(name, v, check))
return tags

return tag_list

Expand Down
14 changes: 14 additions & 0 deletions datadog_checks_base/datadog_checks/base/utils/tagging.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,17 @@
import tagger
except ImportError:
from ..stubs import tagger # noqa: F401

GENERIC_TAGS = {
'cluster_name',
'clustername',
'cluster',
'clusterid',
'cluster_id',
'env',
'host_name',
'hostname',
'host',
'service',
'version',
}