Skip to content

Commit c017a3f

Browse files
committed
fix: Apply PR#861 review suggestions.
- Introduced type hints and code cleanup. - removed None defaults from .get() calls. - import reorganization. - boolean expression formatting. Signed-off-by: Paulo Vital <paulo.vital@ibm.com>
1 parent aec920b commit c017a3f

4 files changed

Lines changed: 69 additions & 43 deletions

File tree

src/instana/collector/helpers/fargate/docker.py

Lines changed: 58 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,20 @@
55

66
from __future__ import division
77

8-
from ....log import logger
9-
from ....util import DictionaryOfStan
10-
from ..base import BaseHelper
8+
from typing import TYPE_CHECKING, Any, Type
9+
10+
from instana.collector.helpers.base import BaseHelper
11+
from instana.log import logger
12+
from instana.util import DictionaryOfStan
13+
14+
if TYPE_CHECKING:
15+
from instana.collector.base import BaseCollector
1116

1217

1318
class DockerHelper(BaseHelper):
1419
"""This class acts as a helper to collect Docker snapshot and metric information"""
1520

16-
def __init__(self, collector):
21+
def __init__(self, collector: Type[BaseCollector]) -> None:
1722
super(DockerHelper, self).__init__(collector)
1823

1924
# The metrics from the previous report cycle
@@ -23,7 +28,7 @@ def __init__(self, collector):
2328
# Indexed by docker_id: self.previous_blkio[docker_id][metric]
2429
self.previous_blkio = DictionaryOfStan()
2530

26-
def collect_metrics(self, **kwargs):
31+
def collect_metrics(self, **kwargs: Any) -> list[dict[str, Any]]:
2732
"""
2833
Collect and return docker metrics (and optionally snapshot data) for this task
2934
@return: list - with one or more plugin entities
@@ -33,7 +38,7 @@ def collect_metrics(self, **kwargs):
3338
if self.collector.task_metadata is not None:
3439
containers = self.collector.task_metadata.get("Containers", [])
3540
for container in containers:
36-
plugin_data = dict()
41+
plugin_data = {}
3742
plugin_data["name"] = "com.instana.plugin.docker"
3843
docker_id = container.get("DockerId")
3944

@@ -43,7 +48,7 @@ def collect_metrics(self, **kwargs):
4348

4449
plugin_data["entityId"] = f"{task_arn}::{name}"
4550
plugin_data["data"] = DictionaryOfStan()
46-
plugin_data["data"]["Id"] = container.get("DockerId", None)
51+
plugin_data["data"]["Id"] = container.get("DockerId")
4752

4853
with_snapshot = kwargs.get("with_snapshot", False)
4954
# Metrics
@@ -61,25 +66,27 @@ def collect_metrics(self, **kwargs):
6166
logger.debug("DockerHelper.collect_metrics: ", exc_info=True)
6267
return plugins
6368

64-
def _collect_container_snapshot(self, plugin_data, container):
69+
def _collect_container_snapshot(
70+
self, plugin_data: dict[str, Any], container: dict[str, Any]
71+
) -> None:
6572
try:
6673
# Snapshot Data
67-
plugin_data["data"]["Created"] = container.get("CreatedAt", None)
68-
plugin_data["data"]["Started"] = container.get("StartedAt", None)
69-
plugin_data["data"]["Image"] = container.get("Image", None)
70-
plugin_data["data"]["Labels"] = container.get("Labels", None)
71-
plugin_data["data"]["Ports"] = container.get("Ports", None)
74+
plugin_data["data"]["Created"] = container.get("CreatedAt")
75+
plugin_data["data"]["Started"] = container.get("StartedAt")
76+
plugin_data["data"]["Image"] = container.get("Image")
77+
plugin_data["data"]["Labels"] = container.get("Labels")
78+
plugin_data["data"]["Ports"] = container.get("Ports")
7279

7380
networks = container.get("Networks", [])
7481
if len(networks) >= 1:
75-
plugin_data["data"]["NetworkMode"] = networks[0].get(
76-
"NetworkMode", None
77-
)
82+
plugin_data["data"]["NetworkMode"] = networks[0].get("NetworkMode")
7883
except Exception:
7984
logger.debug("_collect_container_snapshot: ", exc_info=True)
8085

81-
def _collect_container_metrics(self, plugin_data, docker_id, with_snapshot):
82-
container = self.collector.task_stats_metadata.get(docker_id, None)
86+
def _collect_container_metrics(
87+
self, plugin_data: dict[str, Any], docker_id: str, with_snapshot: bool
88+
) -> None:
89+
container = self.collector.task_stats_metadata.get(docker_id)
8390
if container is not None:
8491
self._collect_network_metrics(
8592
container, plugin_data, docker_id, with_snapshot
@@ -93,10 +100,14 @@ def _collect_container_metrics(self, plugin_data, docker_id, with_snapshot):
93100
)
94101

95102
def _collect_network_metrics(
96-
self, container, plugin_data, docker_id, with_snapshot
97-
):
103+
self,
104+
container: dict[str, Any],
105+
plugin_data: dict[str, Any],
106+
docker_id: str,
107+
with_snapshot: bool,
108+
) -> None:
98109
try:
99-
networks = container.get("networks", None)
110+
networks = container.get("networks")
100111
tx_bytes_total = tx_dropped_total = tx_errors_total = tx_packets_total = 0
101112
rx_bytes_total = rx_dropped_total = rx_errors_total = rx_packets_total = 0
102113

@@ -173,11 +184,17 @@ def _collect_network_metrics(
173184
except Exception:
174185
logger.debug("_collect_network_metrics: ", exc_info=True)
175186

176-
def _collect_cpu_metrics(self, container, plugin_data, docker_id, with_snapshot):
187+
def _collect_cpu_metrics(
188+
self,
189+
container: dict[str, Any],
190+
plugin_data: dict[str, Any],
191+
docker_id: str,
192+
with_snapshot: bool,
193+
) -> None:
177194
try:
178195
cpu_stats = container.get("cpu_stats", {})
179-
cpu_usage = cpu_stats.get("cpu_usage", None)
180-
throttling_data = cpu_stats.get("throttling_data", None)
196+
cpu_usage = cpu_stats.get("cpu_usage")
197+
throttling_data = cpu_stats.get("throttling_data")
181198

182199
if cpu_usage is not None:
183200
online_cpus = cpu_stats.get("online_cpus", 1)
@@ -234,10 +251,16 @@ def _collect_cpu_metrics(self, container, plugin_data, docker_id, with_snapshot)
234251
except Exception:
235252
logger.debug("_collect_cpu_metrics: ", exc_info=True)
236253

237-
def _collect_memory_metrics(self, container, plugin_data, docker_id, with_snapshot):
254+
def _collect_memory_metrics(
255+
self,
256+
container: dict[str, Any],
257+
plugin_data: dict[str, Any],
258+
docker_id: str,
259+
with_snapshot: bool,
260+
) -> None:
238261
try:
239262
memory = container.get("memory_stats", {})
240-
memory_stats = memory.get("stats", None)
263+
memory_stats = memory.get("stats")
241264

242265
self.apply_delta(
243266
memory,
@@ -307,11 +330,17 @@ def _collect_memory_metrics(self, container, plugin_data, docker_id, with_snapsh
307330
except Exception:
308331
logger.debug("_collect_memory_metrics: ", exc_info=True)
309332

310-
def _collect_blkio_metrics(self, container, plugin_data, docker_id, with_snapshot):
333+
def _collect_blkio_metrics(
334+
self,
335+
container: dict[str, Any],
336+
plugin_data: dict[str, Any],
337+
docker_id: str,
338+
with_snapshot: bool,
339+
) -> None:
311340
try:
312-
blkio_stats = container.get("blkio_stats", None)
341+
blkio_stats = container.get("blkio_stats")
313342
if blkio_stats is not None:
314-
service_bytes = blkio_stats.get("io_service_bytes_recursive", None)
343+
service_bytes = blkio_stats.get("io_service_bytes_recursive")
315344
if service_bytes is not None:
316345
for entry in service_bytes:
317346
if entry["op"] == "Read":

src/instana/util/config.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ def parse_span_disabling_dict(items: Dict[str, bool]) -> Tuple[List[str], List[s
348348

349349
def get_disable_trace_configurations_from_env() -> Tuple[List[str], List[str]]:
350350
# Read INSTANA_TRACING_DISABLE environment variable
351-
if tracing_disable := os.environ.get("INSTANA_TRACING_DISABLE", None):
351+
if tracing_disable := os.environ.get("INSTANA_TRACING_DISABLE"):
352352
if is_truthy(tracing_disable):
353353
# INSTANA_TRACING_DISABLE is True/true/1, then we disable all tracing
354354
disabled_spans = []
@@ -388,14 +388,14 @@ def get_disable_trace_configurations_from_yaml() -> Tuple[List[str], List[str]]:
388388
if not root_key:
389389
return [], []
390390

391-
if tracing_disable_config := config_reader.data[root_key].get("disable", None):
391+
if tracing_disable_config := config_reader.data[root_key].get("disable"):
392392
return parse_span_disabling(tracing_disable_config)
393393
return [], []
394394

395395

396396
def get_disable_trace_configurations_from_local() -> Tuple[List[str], List[str]]:
397397
if "tracing" in config and (
398-
tracing_disable_config := config["tracing"].get("disable", None)
398+
tracing_disable_config := config["tracing"].get("disable")
399399
):
400400
return parse_span_disabling(tracing_disable_config)
401401
return [], []

src/instana/util/span_utils.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,10 @@ def match_key_filter(span_value: str, rule_value: str, match_type: str) -> bool:
5757

5858
return bool(
5959
rule_value == "*"
60-
or match_type == "strict"
61-
and span_value == rule_value
62-
or match_type == "contains"
63-
and rule_value in span_value
64-
or match_type == "startswith"
65-
and span_value.startswith(rule_value)
66-
or match_type == "endswith"
67-
and span_value.endswith(rule_value)
60+
or (match_type == "strict" and span_value == rule_value)
61+
or (match_type == "contains" and rule_value in span_value)
62+
or (match_type == "startswith" and span_value.startswith(rule_value))
63+
or (match_type == "endswith" and span_value.endswith(rule_value))
6864
)
6965

7066

tests/apps/fastapi_app/__init__.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,18 @@
22
# (c) Copyright Instana Inc. 2020
33

44
import uvicorn
5-
from ...helpers import testenv
6-
from instana.log import logger as logger
5+
6+
from tests.helpers import testenv
77

88
testenv["fastapi_port"] = 10816
99
testenv["fastapi_server"] = "http://127.0.0.1:" + str(testenv["fastapi_port"])
1010

1111

1212
def launch_fastapi():
13-
from .app import fastapi_server
1413
from instana.singletons import agent
1514

15+
from .app import fastapi_server
16+
1617
# Hack together a manual custom headers list; We'll use this in tests
1718
agent.options.extra_http_headers = [
1819
"X-Capture-This",

0 commit comments

Comments
 (0)