Skip to content

Commit 703a49e

Browse files
committed
Refactor datadog_checks_base and dev
1 parent 6e0f6aa commit 703a49e

File tree

52 files changed

+159
-181
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+159
-181
lines changed

datadog_checks_base/datadog_checks/base/checks/base.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -147,12 +147,12 @@ class except the `check` method but sometimes it might be useful for a Check to
147147
# a mapping type, then each key will be considered a `name` and will be sent with its (str) value.
148148
METADATA_TRANSFORMERS = None
149149

150-
FIRST_CAP_RE = re.compile(br'(.)([A-Z][a-z]+)')
151-
ALL_CAP_RE = re.compile(br'([a-z0-9])([A-Z])')
152-
METRIC_REPLACEMENT = re.compile(br'([^a-zA-Z0-9_.]+)|(^[^a-zA-Z]+)')
153-
TAG_REPLACEMENT = re.compile(br'[,\+\*\-/()\[\]{}\s]')
154-
MULTIPLE_UNDERSCORE_CLEANUP = re.compile(br'__+')
155-
DOT_UNDERSCORE_CLEANUP = re.compile(br'_*\._*')
150+
FIRST_CAP_RE = re.compile(rb'(.)([A-Z][a-z]+)')
151+
ALL_CAP_RE = re.compile(rb'([a-z0-9])([A-Z])')
152+
METRIC_REPLACEMENT = re.compile(rb'([^a-zA-Z0-9_.]+)|(^[^a-zA-Z]+)')
153+
TAG_REPLACEMENT = re.compile(rb'[,\+\*\-/()\[\]{}\s]')
154+
MULTIPLE_UNDERSCORE_CLEANUP = re.compile(rb'__+')
155+
DOT_UNDERSCORE_CLEANUP = re.compile(rb'_*\._*')
156156

157157
# allows to set a limit on the number of metric name and tags combination
158158
# this check can send per run. This is useful for checks that have an unbounded
@@ -1146,10 +1146,10 @@ def convert_to_underscore_separated(self, name):
11461146
And substitute illegal metric characters
11471147
"""
11481148
name = ensure_bytes(name)
1149-
metric_name = self.FIRST_CAP_RE.sub(br'\1_\2', name)
1150-
metric_name = self.ALL_CAP_RE.sub(br'\1_\2', metric_name).lower()
1151-
metric_name = self.METRIC_REPLACEMENT.sub(br'_', metric_name)
1152-
return self.DOT_UNDERSCORE_CLEANUP.sub(br'.', metric_name).strip(b'_')
1149+
metric_name = self.FIRST_CAP_RE.sub(rb'\1_\2', name)
1150+
metric_name = self.ALL_CAP_RE.sub(rb'\1_\2', metric_name).lower()
1151+
metric_name = self.METRIC_REPLACEMENT.sub(rb'_', metric_name)
1152+
return self.DOT_UNDERSCORE_CLEANUP.sub(rb'.', metric_name).strip(b'_')
11531153

11541154
def warning(self, warning_message, *args, **kwargs):
11551155
# type: (str, *Any, **Any) -> None
@@ -1243,10 +1243,10 @@ def normalize(self, metric, prefix=None, fix_case=False):
12431243
if prefix is not None:
12441244
prefix = self.convert_to_underscore_separated(prefix)
12451245
else:
1246-
name = self.METRIC_REPLACEMENT.sub(br'_', metric)
1247-
name = self.DOT_UNDERSCORE_CLEANUP.sub(br'.', name).strip(b'_')
1246+
name = self.METRIC_REPLACEMENT.sub(rb'_', metric)
1247+
name = self.DOT_UNDERSCORE_CLEANUP.sub(rb'.', name).strip(b'_')
12481248

1249-
name = self.MULTIPLE_UNDERSCORE_CLEANUP.sub(br'_', name)
1249+
name = self.MULTIPLE_UNDERSCORE_CLEANUP.sub(rb'_', name)
12501250

12511251
if prefix is not None:
12521252
name = ensure_bytes(prefix) + b"." + name
@@ -1262,9 +1262,9 @@ def normalize_tag(self, tag):
12621262
"""
12631263
if isinstance(tag, str):
12641264
tag = tag.encode('utf-8', 'ignore')
1265-
tag = self.TAG_REPLACEMENT.sub(br'_', tag)
1266-
tag = self.MULTIPLE_UNDERSCORE_CLEANUP.sub(br'_', tag)
1267-
tag = self.DOT_UNDERSCORE_CLEANUP.sub(br'.', tag).strip(b'_')
1265+
tag = self.TAG_REPLACEMENT.sub(rb'_', tag)
1266+
tag = self.MULTIPLE_UNDERSCORE_CLEANUP.sub(rb'_', tag)
1267+
tag = self.DOT_UNDERSCORE_CLEANUP.sub(rb'.', tag).strip(b'_')
12681268
return to_native_string(tag)
12691269

12701270
def check(self, instance):

datadog_checks_base/datadog_checks/base/checks/network.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def check(self, instance):
3333
try:
3434
statuses = self._check(instance)
3535
except Exception:
36-
self.log.exception(u"Failed to run instance '%s'.", instance.get('name', u""))
36+
self.log.exception("Failed to run instance '%s'.", instance.get('name', ""))
3737
else:
3838
if isinstance(statuses, tuple):
3939
# Assume the check only returns one service check

datadog_checks_base/datadog_checks/base/checks/prometheus/mixins.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -561,15 +561,15 @@ def poll(self, endpoint, pFormat=PrometheusFormat.PROTOBUF, headers=None, instan
561561
headers['Accept-Encoding'] = 'gzip'
562562
if pFormat == PrometheusFormat.PROTOBUF:
563563
headers['accept'] = (
564-
'application/vnd.google.protobuf; ' 'proto=io.prometheus.client.MetricFamily; ' 'encoding=delimited'
564+
'application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited'
565565
)
566566
handler = self.get_http_handler(endpoint, instance)
567567
if (
568568
endpoint.startswith('https')
569569
and not handler.ignore_tls_warning
570570
and not is_affirmative(handler.options.get('ssl_verify', True))
571571
):
572-
self.log.debug(u'An unverified HTTPS request is being made to %s', endpoint)
572+
self.log.debug('An unverified HTTPS request is being made to %s', endpoint)
573573

574574
try:
575575
response = handler.get(endpoint, extra_headers=headers, stream=False)

datadog_checks_base/datadog_checks/base/checks/win/wmi/base.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -68,14 +68,14 @@ def _format_tag_query(self, sampler, wmi_obj, tag_query):
6868
target_property = tag_query[3]
6969
except IndexError:
7070
self.log.error(
71-
u"Wrong `tag_queries` parameter format. " "Please refer to the configuration file for more information."
71+
"Wrong `tag_queries` parameter format. Please refer to the configuration file for more information."
7272
)
7373
raise
7474
except TypeError:
7575
wmi_property = tag_query[0]
7676
wmi_class = sampler.class_name
7777
self.log.error(
78-
u"Incorrect 'link source property' in `tag_queries` parameter: `%s` is not a property of `%s`",
78+
"Incorrect 'link source property' in `tag_queries` parameter: `%s` is not a property of `%s`",
7979
wmi_property,
8080
wmi_class,
8181
)
@@ -94,7 +94,7 @@ def _raise_on_invalid_tag_query_result(self, sampler, wmi_obj, tag_query):
9494
message = "multiple results returned (one expected)"
9595

9696
self.log.warning(
97-
u"Failed to extract a tag from `tag_queries` parameter: %s. wmi_object=%s - query=%s",
97+
"Failed to extract a tag from `tag_queries` parameter: %s. wmi_object=%s - query=%s",
9898
message,
9999
wmi_obj,
100100
tag_query,
@@ -103,7 +103,7 @@ def _raise_on_invalid_tag_query_result(self, sampler, wmi_obj, tag_query):
103103

104104
if sampler[0][target_property] is None:
105105
self.log.error(
106-
u"Incorrect 'target property' in `tag_queries` parameter: `%s` is empty or is not a property of `%s`",
106+
"Incorrect 'target property' in `tag_queries` parameter: `%s` is empty or is not a property of `%s`",
107107
target_property,
108108
target_class,
109109
)
@@ -116,7 +116,7 @@ def _get_tag_query_tag(self, sampler, wmi_obj, tag_query):
116116
117117
Returns: tag or TagQueryUniquenessFailure exception.
118118
"""
119-
self.log.debug(u"`tag_queries` parameter found. wmi_object=%s - query=%s", wmi_obj, tag_query)
119+
self.log.debug("`tag_queries` parameter found. wmi_object=%s - query=%s", wmi_obj, tag_query)
120120

121121
# Extract query information
122122
target_class, target_property, filters = self._format_tag_query(sampler, wmi_obj, tag_query)
@@ -134,7 +134,7 @@ def _get_tag_query_tag(self, sampler, wmi_obj, tag_query):
134134

135135
tag = "{tag_name}:{tag_value}".format(tag_name=target_property.lower(), tag_value="_".join(link_value.split()))
136136

137-
self.log.debug(u"Extracted `tag_queries` tag: '%s'", tag)
137+
self.log.debug("Extracted `tag_queries` tag: '%s'", tag)
138138
return tag
139139

140140
def _extract_metrics(self, wmi_sampler, tag_by, tag_queries, constant_tags):
@@ -154,7 +154,7 @@ def _extract_metrics(self, wmi_sampler, tag_by, tag_queries, constant_tags):
154154
"""
155155
if len(wmi_sampler) > 1 and not tag_by:
156156
raise MissingTagBy(
157-
u"WMI query returned multiple rows but no `tag_by` value was given."
157+
"WMI query returned multiple rows but no `tag_by` value was given."
158158
" class={wmi_class} - properties={wmi_properties} - filters={filters}".format(
159159
wmi_class=wmi_sampler.class_name,
160160
wmi_properties=wmi_sampler.property_names,
@@ -209,11 +209,11 @@ def _extract_metrics(self, wmi_sampler, tag_by, tag_queries, constant_tags):
209209
extracted_metrics.append(WMIMetric(wmi_property, float(wmi_value), tags))
210210
except ValueError:
211211
self.log.warning(
212-
u"When extracting metrics with WMI, found a non digit value for property '%s'.", wmi_property
212+
"When extracting metrics with WMI, found a non digit value for property '%s'.", wmi_property
213213
)
214214
continue
215215
except TypeError:
216-
self.log.warning(u"When extracting metrics with WMI, found a missing property '%s'", wmi_property)
216+
self.log.warning("When extracting metrics with WMI, found a missing property '%s'", wmi_property)
217217
continue
218218
return extracted_metrics
219219

@@ -241,7 +241,7 @@ def _submit_metrics(self, metrics, metric_name_and_type_by_property):
241241
try:
242242
func = getattr(self, metric_type.lower())
243243
except AttributeError:
244-
raise Exception(u"Invalid metric type: {0}".format(metric_type))
244+
raise Exception("Invalid metric type: {0}".format(metric_type))
245245

246246
func(metric_name, metric.value, metric.tags)
247247

@@ -270,7 +270,7 @@ def get_running_wmi_sampler(self, properties, filters, **kwargs):
270270
username=self.username,
271271
password=self.password,
272272
tag_by=tag_by,
273-
**kwargs
273+
**kwargs,
274274
)
275275

276276
def _get_running_wmi_sampler(self, instance_key, wmi_class, properties, tag_by="", **kwargs):

datadog_checks_base/datadog_checks/base/checks/win/wmi/sampler.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
Original discussion thread: https://github.com/DataDog/dd-agent/issues/1952
2424
Credits to @TheCloudlessSky (https://github.com/TheCloudlessSky)
2525
"""
26+
2627
from copy import deepcopy
2728
from threading import Event, Thread
2829

@@ -227,7 +228,7 @@ def provider(self, value):
227228
result = parsed_value
228229

229230
if result is None:
230-
self.logger.error(u"Invalid '%s' WMI Provider Architecture. The parameter is ignored.", value)
231+
self.logger.error("Invalid '%s' WMI Provider Architecture. The parameter is ignored.", value)
231232

232233
self._provider = result or ProviderArchitecture.DEFAULT
233234

@@ -278,7 +279,7 @@ def __len__(self):
278279
"""
279280
# No data is returned while sampling
280281
if self._sampling:
281-
raise TypeError(u"Sampling `WMISampler` object has no len()")
282+
raise TypeError("Sampling `WMISampler` object has no len()")
282283

283284
return len(self._current_sample)
284285

@@ -288,7 +289,7 @@ def __iter__(self):
288289
"""
289290
# No data is returned while sampling
290291
if self._sampling:
291-
raise TypeError(u"Sampling `WMISampler` object is not iterable")
292+
raise TypeError("Sampling `WMISampler` object is not iterable")
292293

293294
if self.is_raw_perf_class:
294295
# Format required
@@ -334,7 +335,7 @@ def _get_property_calculator(self, counter_type):
334335
calculator = get_calculator(counter_type)
335336
except UndefinedCalculator:
336337
self.logger.warning(
337-
u"Undefined WMI calculator for counter_type %s. Values are reported as RAW.", counter_type
338+
"Undefined WMI calculator for counter_type %s. Values are reported as RAW.", counter_type
338339
)
339340

340341
return calculator
@@ -364,7 +365,7 @@ def get_connection(self):
364365
Create a new WMI connection
365366
"""
366367
self.logger.debug(
367-
u"Connecting to WMI server (host=%s, namespace=%s, provider=%s, username=%s).",
368+
"Connecting to WMI server (host=%s, namespace=%s, provider=%s, username=%s).",
368369
self.host,
369370
self.namespace,
370371
self.provider,
@@ -550,7 +551,7 @@ def _query(self): # pylint: disable=E0202
550551
wql = "Select {property_names} from {class_name}{filters}".format(
551552
property_names=formated_property_names, class_name=self.class_name, filters=self.formatted_filters
552553
)
553-
self.logger.debug(u"Querying WMI: %s", wql)
554+
self.logger.debug("Querying WMI: %s", wql)
554555
except Exception as e:
555556
self.logger.error(str(e))
556557
return []
@@ -575,7 +576,7 @@ def _query(self): # pylint: disable=E0202
575576
results = self._parse_results(raw_results, includes_qualifiers=includes_qualifiers)
576577

577578
except pywintypes.com_error:
578-
self.logger.warning(u"Failed to execute WMI query (%s)", wql, exc_info=True)
579+
self.logger.warning("Failed to execute WMI query (%s)", wql, exc_info=True)
579580
results = []
580581

581582
return results
@@ -615,7 +616,6 @@ def _parse_results(self, raw_results, includes_qualifiers):
615616
)
616617

617618
if should_get_qualifier_type:
618-
619619
# Can't index into "Qualifiers_" for keys that don't exist
620620
# without getting an exception.
621621
qualifiers = dict((q.Name, q.Value) for q in wmi_property.Qualifiers_)
@@ -628,14 +628,14 @@ def _parse_results(self, raw_results, includes_qualifiers):
628628
self._property_counter_types[wmi_property.Name] = counter_type
629629

630630
self.logger.debug(
631-
u"Caching property qualifier CounterType: %s.%s = %s",
631+
"Caching property qualifier CounterType: %s.%s = %s",
632632
self.class_name,
633633
wmi_property.Name,
634634
counter_type,
635635
)
636636
else:
637637
self.logger.debug(
638-
u"CounterType qualifier not found for %s.%s", self.class_name, wmi_property.Name
638+
"CounterType qualifier not found for %s.%s", self.class_name, wmi_property.Name
639639
)
640640

641641
try:

datadog_checks_base/datadog_checks/base/checks/windows/perf_counters/connection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def __init__(self, config):
7777
# https://docs.microsoft.com/en-us/windows/win32/api/winnetwk/ns-winnetwk-netresourcea
7878
# https://mhammond.github.io/pywin32/PyNETRESOURCE.html
7979
self.network_resource = win32wnet.NETRESOURCE()
80-
self.network_resource.lpRemoteName = fr'\\{server}'
80+
self.network_resource.lpRemoteName = rf'\\{server}'
8181

8282
self.__query_handle = None
8383

datadog_checks_base/datadog_checks/base/stubs/datadog_agent.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,10 @@ def assert_external_tags(self, hostname, external_tags, match_tags_order=False):
6767
external_tags = {k: sorted(v) for (k, v) in external_tags.items()}
6868
tags = {k: sorted(v) for (k, v) in tags.items()}
6969

70-
assert (
71-
external_tags == tags
72-
), 'Expected {} external tags for hostname {}, found {}. Submitted external tags: {}'.format(
73-
external_tags, hostname, tags, repr(self._external_tags)
70+
assert external_tags == tags, (
71+
'Expected {} external tags for hostname {}, found {}. Submitted external tags: {}'.format(
72+
external_tags, hostname, tags, repr(self._external_tags)
73+
)
7474
)
7575
return
7676

datadog_checks_base/datadog_checks/base/utils/db/query.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -214,9 +214,7 @@ def compile(
214214
elif extra_type not in extra_transformers and extra_type not in submission_transformers:
215215
raise ValueError('unknown type `{}` for extra {} of {}'.format(extra_type, extra_name, query_name))
216216

217-
transformer_factory = extra_transformers.get(
218-
extra_type, submission_transformers.get(extra_type)
219-
) # type: TransformerFactory
217+
transformer_factory = extra_transformers.get(extra_type, submission_transformers.get(extra_type)) # type: TransformerFactory
220218

221219
extra_source = extra.get('source')
222220
if extra_type in submission_transformers:

datadog_checks_base/datadog_checks/base/utils/db/transform.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,7 @@ def get_monotonic_gauge(transformers, column_name, **modifiers):
8585
Send the result as both a `gauge` suffixed by `.total` and a `monotonic_count` suffixed by `.count`.
8686
"""
8787
gauge = transformers['gauge'](transformers, '{}.total'.format(column_name), **modifiers) # type: Callable
88-
monotonic_count = transformers['monotonic_count'](
89-
transformers, '{}.count'.format(column_name), **modifiers
90-
) # type: Callable
88+
monotonic_count = transformers['monotonic_count'](transformers, '{}.count'.format(column_name), **modifiers) # type: Callable
9189

9290
def monotonic_gauge(_, value, **kwargs):
9391
# type: (List, str, Dict[str, Any]) -> None

datadog_checks_base/datadog_checks/base/utils/http.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,7 @@ def options_method(self, url, **options):
378378

379379
def _request(self, method, url, options):
380380
if self.log_requests:
381-
self.logger.debug(u'Sending %s request to %s', method.upper(), url)
381+
self.logger.debug('Sending %s request to %s', method.upper(), url)
382382

383383
if self.no_proxy_uris and should_bypass_proxy(url, self.no_proxy_uris):
384384
options.setdefault('proxies', PROXY_SETTINGS_DISABLED)
@@ -390,7 +390,7 @@ def _request(self, method, url, options):
390390
new_options = self.populate_options(options)
391391

392392
if url.startswith('https') and not self.ignore_tls_warning and not new_options['verify']:
393-
self.logger.debug(u'An unverified HTTPS request is being made to %s', url)
393+
self.logger.debug('An unverified HTTPS request is being made to %s', url)
394394

395395
extra_headers = options.pop('extra_headers', None)
396396
if extra_headers is not None:
@@ -416,7 +416,7 @@ def _request(self, method, url, options):
416416
response = self.make_request_aia_chasing(request_method, method, url, new_options, persist)
417417
response.raise_for_status()
418418
except Exception as e:
419-
self.logger.debug(u'Renewing auth token, as an error occurred: %s', e)
419+
self.logger.debug('Renewing auth token, as an error occurred: %s', e)
420420
self.handle_auth_token(method=method, url=url, default_options=self.options, error=str(e))
421421
response = self.make_request_aia_chasing(request_method, method, url, new_options, persist)
422422
else:

0 commit comments

Comments
 (0)