Skip to content

Commit 8d3e7b5

Browse files
committed
style: format BaseCollector and utils files.
Used ruff (vscode) to: - Black-compatible code formatting. - fix all auto-fixable violations, like unused imports. - isort-compatible import sorting. Signed-off-by: Paulo Vital <[email protected]>
1 parent 732b7ed commit 8d3e7b5

File tree

2 files changed

+78
-43
lines changed

2 files changed

+78
-43
lines changed

src/instana/collector/base.py

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,30 @@
22
# (c) Copyright Instana Inc. 2020
33

44
"""
5-
A Collector launches a background thread and continually collects & reports data. The data
6-
can be any combination of metrics, snapshot data and spans.
5+
A Collector launches a background thread and continually collects & reports data.
6+
The data can be any combination of metrics, snapshot data and spans.
77
"""
88

99
import queue # pylint: disable=import-error
1010
import threading
1111
import time
12+
from typing import TYPE_CHECKING, Any, DefaultDict, Dict, List, Type
1213

1314
from instana.log import logger
1415
from instana.util import DictionaryOfStan
1516

17+
if TYPE_CHECKING:
18+
from instana.agent.base import BaseAgent
19+
from instana.span.readable_span import ReadableSpan
20+
1621

1722
class BaseCollector(object):
1823
"""
1924
Base class to handle the collection & reporting of snapshot and metric data
2025
This class launches a background thread to do this work.
2126
"""
2227

23-
def __init__(self, agent):
28+
def __init__(self, agent: Type["BaseAgent"]) -> None:
2429
# The agent for this process. Can be Standard, AWSLambda or Fargate
2530
self.agent = agent
2631

@@ -61,7 +66,7 @@ def __init__(self, agent):
6166
# Start time of fetching metadata
6267
self.fetching_start_time = 0
6368

64-
def is_reporting_thread_running(self):
69+
def is_reporting_thread_running(self) -> bool:
6570
"""
6671
Indicates if there is a thread running with the name self.THREAD_NAME
6772
"""
@@ -70,14 +75,14 @@ def is_reporting_thread_running(self):
7075
return True
7176
return False
7277

73-
def start(self):
78+
def start(self) -> None:
7479
"""
7580
Starts the collector and starts reporting as long as the agent is in a ready state.
7681
@return: None
7782
"""
7883
if self.is_reporting_thread_running():
7984
if self.thread_shutdown.is_set():
80-
# Force a restart.
85+
# Force a restart.
8186
self.thread_shutdown.clear()
8287
# Reschedule this start in 5 seconds from now
8388
timer = threading.Timer(5, self.start)
@@ -92,7 +97,9 @@ def start(self):
9297
if self.agent.can_send():
9398
logger.debug("BaseCollector.start: launching collection thread")
9499
self.thread_shutdown.clear()
95-
self.reporting_thread = threading.Thread(target=self.background_report, args=())
100+
self.reporting_thread = threading.Thread(
101+
target=self.background_report, args=()
102+
)
96103
self.reporting_thread.daemon = True
97104
self.reporting_thread.name = self.THREAD_NAME
98105
self.reporting_thread.start()
@@ -102,7 +109,7 @@ def start(self):
102109
"BaseCollector.start: the agent tells us we can't send anything out"
103110
)
104111

105-
def shutdown(self, report_final=True):
112+
def shutdown(self, report_final: bool = True) -> None:
106113
"""
107114
Shuts down the collector and reports any final data (if possible).
108115
e.g. If the host agent disappeared, we won't be able to report final data.
@@ -118,10 +125,10 @@ def background_report(self) -> None:
118125
"""
119126
The main work-horse method to report data in the background thread.
120127
121-
This method runs indefinitely, preparing and reporting data at regular
128+
This method runs indefinitely, preparing and reporting data at regular
122129
intervals.
123130
It checks for a shutdown signal and stops execution if it's set.
124-
131+
125132
@return: None
126133
"""
127134
while True:
@@ -134,7 +141,7 @@ def background_report(self) -> None:
134141
self.prepare_and_report_data()
135142
time.sleep(self.report_interval)
136143

137-
def prepare_and_report_data(self):
144+
def prepare_and_report_data(self) -> bool:
138145
"""
139146
Prepare and report the data payload.
140147
@return: Boolean
@@ -144,26 +151,26 @@ def prepare_and_report_data(self):
144151
self.agent.report_data_payload(payload)
145152
return True
146153

147-
def prepare_payload(self):
154+
def prepare_payload(self) -> DefaultDict[str, Any]:
148155
"""
149156
Method to prepare the data to be reported.
150157
@return: DictionaryOfStan()
151158
"""
152159
logger.debug("BaseCollector: prepare_payload needs to be overridden")
153160
return DictionaryOfStan()
154161

155-
def should_send_snapshot_data(self):
162+
def should_send_snapshot_data(self) -> bool:
156163
"""
157164
Determines if snapshot data should be sent
158165
@return: Boolean
159166
"""
160167
logger.debug("BaseCollector: should_send_snapshot_data needs to be overridden")
161168
return False
162169

163-
def collect_snapshot(self, *argv, **kwargs):
170+
def collect_snapshot(self, *argv, **kwargs) -> None:
164171
logger.debug("BaseCollector: collect_snapshot needs to be overridden")
165172

166-
def queued_spans(self):
173+
def queued_spans(self) -> List["ReadableSpan"]:
167174
"""
168175
Get all of the queued spans
169176
@return: list
@@ -178,7 +185,7 @@ def queued_spans(self):
178185
spans.append(span)
179186
return spans
180187

181-
def queued_profiles(self):
188+
def queued_profiles(self) -> List[Dict[str, Any]]:
182189
"""
183190
Get all of the queued profiles
184191
@return: list

src/instana/util/__init__.py

Lines changed: 55 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,32 +4,42 @@
44
import importlib.metadata
55
import json
66
from collections import defaultdict
7+
from typing import Any, DefaultDict
78
from urllib import parse
89

910
from instana.log import logger
1011

1112

12-
def nested_dictionary():
13+
def nested_dictionary() -> DefaultDict[str, Any]:
1314
return defaultdict(DictionaryOfStan)
1415

1516

1617
# Simple implementation of a nested dictionary.
17-
DictionaryOfStan = nested_dictionary
18+
DictionaryOfStan: DefaultDict[str, Any] = nested_dictionary
1819

1920

20-
def to_json(obj):
21+
# Assisted by watsonx Code Assistant
22+
def to_json(obj: Any) -> bytes:
2123
"""
22-
Convert obj to json. Used mostly to convert the classes in json_span.py until we switch to nested
23-
dicts (or something better)
24+
Convert the given object to a JSON binary string.
2425
25-
:param obj: the object to serialize to json
26-
:return: json string
26+
This function is primarily used to serialize objects from `json_span.py`
27+
until a switch to nested dictionaries (or a better solution) is made.
28+
29+
:param obj: The object to serialize to JSON.
30+
:return: The JSON string encoded as bytes.
2731
"""
2832
try:
2933

30-
def extractor(o):
34+
def extractor(o: Any) -> dict:
35+
"""
36+
Extract dictionary-like attributes from an object.
37+
38+
:param o: The object to extract attributes from.
39+
:return: A dictionary containing the object's attributes.
40+
"""
3141
if not hasattr(o, "__dict__"):
32-
logger.debug("Couldn't serialize non dict type: %s", type(o))
42+
logger.debug(f"Couldn't serialize non dict type: {type(o)}")
3343
return {}
3444
else:
3545
return {k.lower(): v for k, v in o.__dict__.items() if v is not None}
@@ -41,9 +51,12 @@ def extractor(o):
4151
logger.debug("to_json non-fatal encoding issue: ", exc_info=True)
4252

4353

44-
def to_pretty_json(obj):
54+
# Assisted by watsonx Code Assistant
55+
def to_pretty_json(obj: Any) -> str:
4556
"""
46-
Convert obj to pretty json. Used mostly in logging/debugging.
57+
Convert an object to a pretty-printed JSON string.
58+
59+
This function is primarily used for logging and debugging purposes.
4760
4861
:param obj: the object to serialize to json
4962
:return: json string
@@ -64,26 +77,40 @@ def extractor(o):
6477
logger.debug("to_pretty_json non-fatal encoding issue: ", exc_info=True)
6578

6679

67-
def package_version():
80+
# Assisted by watsonx Code Assistant
81+
def package_version() -> str:
6882
"""
69-
Determine the version of this package.
83+
Determine the version of the 'instana' package.
84+
85+
This function uses the `importlib.metadata` module to fetch the version of
86+
the 'instana' package.
87+
If the package is not found, it returns 'unknown'.
7088
71-
:return: String representing known version
89+
:return: A string representing the version of the 'instana' package.
7290
"""
73-
version = ""
7491
try:
7592
version = importlib.metadata.version("instana")
7693
except importlib.metadata.PackageNotFoundError:
94+
logger.debug("Not able to identify the Instana package version.")
7795
version = "unknown"
7896

7997
return version
8098

8199

82-
def get_default_gateway():
100+
# Assisted by watsonx Code Assistant
101+
def get_default_gateway() -> str:
83102
"""
84103
Attempts to read /proc/self/net/route to determine the default gateway in use.
85104
86-
:return: String - the ip address of the default gateway or None if not found/possible/non-existant
105+
This function reads the /proc/self/net/route file, which contains network
106+
routing information for the current process.
107+
It specifically looks for the line where the Destination is 00000000,
108+
indicating the default route.
109+
The Gateway IP is encoded backwards in hex, which this function decodes and
110+
converts to a standard IP address format.
111+
112+
:return: String - the ip address of the default gateway or None if not
113+
found/possible/non-existant
87114
"""
88115
try:
89116
hip = None
@@ -98,28 +125,29 @@ def get_default_gateway():
98125

99126
if hip is not None and len(hip) == 8:
100127
# Reverse order, convert hex to int
101-
return "%i.%i.%i.%i" % (
102-
int(hip[6:8], 16),
103-
int(hip[4:6], 16),
104-
int(hip[2:4], 16),
105-
int(hip[0:2], 16),
106-
)
128+
return f"{int(hip[6:8], 16)}.{int(hip[4:6], 16)}.{int(hip[2:4], 16)}.{int(hip[0:2], 16)}"
107129

108130
except Exception:
109131
logger.warning("get_default_gateway: ", exc_info=True)
110132

111133

112-
def validate_url(url):
134+
# Assisted by watsonx Code Assistant
135+
def validate_url(url: str) -> bool:
113136
"""
114-
Validate if <url> is a valid url
137+
Validate if the provided <url> is a valid URL.
138+
139+
This function checks if the given string is a valid URL by attempting to
140+
parse it using the `urlparse` function from the `urllib.parse` module.
141+
A URL is considered valid if it has both a scheme (like 'http' or 'https')
142+
and a network location (netloc).
115143
116144
Examples:
117145
- "http://localhost:5000" - valid
118146
- "http://localhost:5000/path" - valid
119147
- "sandwich" - invalid
120148
121-
@param url: string
122-
@return: Boolean
149+
@param url: A string representing the URL to validate.
150+
@return: A boolean value. Returns `True` if the URL is valid, otherwise `False`.
123151
"""
124152
try:
125153
result = parse.urlparse(url)

0 commit comments

Comments
 (0)