Skip to content

Commit

Permalink
Remove use of datetime.utcnow()
Browse files Browse the repository at this point in the history
  • Loading branch information
adamchainz committed Oct 4, 2024
1 parent 5614351 commit 61d2861
Show file tree
Hide file tree
Showing 15 changed files with 32 additions and 24 deletions.
4 changes: 3 additions & 1 deletion src/scout_apm/celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ def get_safe_settings():

def before_task_publish_callback(headers=None, properties=None, **kwargs):
if "scout_task_start" not in headers:
headers["scout_task_start"] = datetime_to_timestamp(dt.datetime.utcnow())
headers["scout_task_start"] = datetime_to_timestamp(
dt.datetime.now(dt.timezone.utc)
)


def task_prerun_callback(task=None, **kwargs):
Expand Down
4 changes: 2 additions & 2 deletions src/scout_apm/core/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def report_app_metadata():
event_type="scout.metadata",
event_value=get_metadata(),
source="Pid: " + str(getpid()),
timestamp=dt.datetime.utcnow(),
timestamp=dt.datetime.now(dt.timezone.utc),
)
)

Expand All @@ -24,7 +24,7 @@ def get_metadata():
data = {
"language": "python",
"language_version": "{}.{}.{}".format(*sys.version_info[:3]),
"server_time": dt.datetime.utcnow().isoformat() + "Z",
"server_time": dt.datetime.now(dt.timezone.utc).isoformat() + "Z",
"framework": scout_config.value("framework"),
"framework_version": scout_config.value("framework_version"),
"environment": "",
Expand Down
2 changes: 1 addition & 1 deletion src/scout_apm/core/queue_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def track_job_queue_time(
bool: Whether we succeeded in marking queue time for the job. Used for testing.
"""
if header_value is not None:
now = datetime_to_timestamp(dt.datetime.utcnow()) * 1e9
now = datetime_to_timestamp(dt.datetime.now(dt.timezone.utc)) * 1e9
try:
ambiguous_float_start = typing.cast(float, header_value)
start = _convert_ambiguous_timestamp_to_ns(ambiguous_float_start)
Expand Down
4 changes: 2 additions & 2 deletions src/scout_apm/core/samplers/cpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ class Cpu(object):
human_name = "Process CPU"

def __init__(self):
self.last_run = dt.datetime.utcnow()
self.last_run = dt.datetime.now(dt.timezone.utc)
self.last_cpu_times = psutil.Process().cpu_times()
self.num_processors = psutil.cpu_count()
if self.num_processors is None:
logger.debug("Could not determine CPU count - assuming there is one.")
self.num_processors = 1

def run(self):
now = dt.datetime.utcnow()
now = dt.datetime.now(dt.timezone.utc)
process = psutil.Process() # get a handle on the current process
cpu_times = process.cpu_times()

Expand Down
2 changes: 1 addition & 1 deletion src/scout_apm/core/samplers/thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def run(self):
event = ApplicationEvent(
event_value=event_value,
event_type=event_type,
timestamp=dt.datetime.utcnow(),
timestamp=dt.datetime.now(dt.timezone.utc),
source="Pid: " + str(os.getpid()),
)
CoreAgentSocketThread.send(event)
Expand Down
10 changes: 5 additions & 5 deletions src/scout_apm/core/tracked_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def instance(cls):

def __init__(self):
self.request_id = "req-" + str(uuid4())
self.start_time = dt.datetime.utcnow()
self.start_time = dt.datetime.now(dt.timezone.utc)
self.end_time = None
self.active_spans = []
self.complete_spans = []
Expand Down Expand Up @@ -147,7 +147,7 @@ def finish(self):

logger.debug("Stopping request: %s", self.request_id)
if self.end_time is None:
self.end_time = dt.datetime.utcnow()
self.end_time = dt.datetime.now(dt.timezone.utc)

if self.is_real_request:
self.tag("mem_delta", self._get_mem_delta())
Expand Down Expand Up @@ -219,7 +219,7 @@ def __init__(
should_capture_backtrace=True,
):
self.span_id = "span-" + str(uuid4())
self.start_time = dt.datetime.utcnow()
self.start_time = dt.datetime.now(dt.timezone.utc)
self.end_time = None
self.request_id = request_id
self.operation = operation
Expand All @@ -238,7 +238,7 @@ def __repr__(self):
)

def stop(self):
self.end_time = dt.datetime.utcnow()
self.end_time = dt.datetime.now(dt.timezone.utc)
self.end_objtrace_counts = objtrace.get_counts()

def tag(self, key, value):
Expand All @@ -254,7 +254,7 @@ def duration(self):
return (self.end_time - self.start_time).total_seconds()
else:
# Current, running duration
return (dt.datetime.utcnow() - self.start_time).total_seconds()
return (dt.datetime.now() - self.start_time).total_seconds()

# Add any interesting annotations to the span. Assumes that we are in the
# process of stopping this span.
Expand Down
4 changes: 3 additions & 1 deletion src/scout_apm/rq.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ def wrap_perform(wrapped, instance, args, kwargs):
tracked_request.is_real_request = True
tracked_request.tag("task_id", instance.get_id())
tracked_request.tag("queue", instance.origin)
queue_time = (dt.datetime.utcnow() - instance.enqueued_at).total_seconds()
queue_time = (
dt.datetime.now(dt.timezone.utc) - instance.enqueued_at
).total_seconds()
tracked_request.tag("queue_time", queue_time)
operation = "Job/{}".format(instance.func_name)
tracked_request.operation = operation
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/test_bottle.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def test_user_ip_collection_disabled(tracked_requests):
@parametrize_queue_time_header_name
def test_queue_time(header_name, tracked_requests):
# Not testing floats due to Python 2/3 rounding differences
queue_start = int(datetime_to_timestamp(dt.datetime.utcnow())) - 2
queue_start = int(datetime_to_timestamp(dt.datetime.now())) - 2
with app_with_scout() as app:
response = TestApp(app).get(
"/", headers={header_name: str("t=") + str(queue_start)}
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/test_django.py
Original file line number Diff line number Diff line change
Expand Up @@ -861,7 +861,7 @@ def test_old_style_urlconf(tracked_requests):
@parametrize_queue_time_header_name
def test_queue_time(header_name, tracked_requests):
# Not testing floats due to Python 2/3 rounding differences
queue_start = int(datetime_to_timestamp(dt.datetime.utcnow())) - 2
queue_start = int(datetime_to_timestamp(dt.datetime.now())) - 2
with app_with_scout() as app:
response = TestApp(app).get(
"/", headers={header_name: str("t=") + str(queue_start)}
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/test_falcon.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def test_filtered_params(params, expected_path, tracked_requests):
@parametrize_queue_time_header_name
def test_queue_time(header_name, tracked_requests):
# Not testing floats due to Python 2/3 rounding differences
queue_start = int(datetime_to_timestamp(dt.datetime.utcnow())) - 2
queue_start = int(datetime_to_timestamp(dt.datetime.now())) - 2
with app_with_scout() as app:
response = TestApp(app).get(
"/", headers={header_name: str("t=") + str(queue_start)}
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/test_flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def test_user_ip_collection_disabled(tracked_requests):
@parametrize_queue_time_header_name
def test_queue_time(header_name, tracked_requests):
# Not testing floats due to Python 2/3 rounding differences
queue_start = int(datetime_to_timestamp(dt.datetime.utcnow())) - 2
queue_start = int(datetime_to_timestamp(dt.datetime.now())) - 2
with app_with_scout() as app:
response = TestApp(app).get(
"/", headers={header_name: str("t=") + str(queue_start)}
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/test_starlette.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ async def test_user_ip_collection_disabled(tracked_requests):
@pytest.mark.asyncio
async def test_queue_time(header_name, tracked_requests):
# Not testing floats due to Python 2/3 rounding differences
queue_start = int(datetime_to_timestamp(dt.datetime.utcnow())) - 2
queue_start = int(datetime_to_timestamp(dt.datetime.now())) - 2
with app_with_scout() as app:
communicator = ApplicationCommunicator(
app,
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/core/samplers/test_cpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

def test_run_negative_time_elapsed(caplog):
cpu = Cpu()
cpu.last_run = dt.datetime.utcnow() + dt.timedelta(days=100)
cpu.last_run = dt.datetime.now() + dt.timedelta(days=100)

result = cpu.run()

Expand Down
12 changes: 8 additions & 4 deletions tests/unit/core/test_queue_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

@pytest.mark.parametrize("with_t", [True, False])
def test_track_request_queue_time_valid(with_t, tracked_request):
queue_start = int(datetime_to_timestamp(dt.datetime.utcnow())) - 2
queue_start = int(datetime_to_timestamp(dt.datetime.now(dt.timezone.utc))) - 2
if with_t:
header_value = str("t=") + str(queue_start)
else:
Expand All @@ -35,7 +35,9 @@ def test_track_request_queue_time_valid(with_t, tracked_request):
str(""),
str("t=X"), # first character not a digit
str("t=0.3f"), # raises ValueError on float() conversion
str(datetime_to_timestamp(dt.datetime.utcnow()) + 3600.0), # one hour in future
str(
datetime_to_timestamp(dt.datetime.now(dt.timezone.utc)) + 3600.0
), # one hour in future
str(datetime_to_timestamp(dt.datetime(2009, 1, 1))), # before ambig cutoff
],
)
Expand All @@ -48,7 +50,7 @@ def test_track_request_queue_time_invalid(header_value, tracked_request):

@pytest.mark.parametrize("with_t", [True, False])
def test_track_job_queue_time_valid(with_t, tracked_request):
queue_start = datetime_to_timestamp(dt.datetime.utcnow()) - 2.0
queue_start = datetime_to_timestamp(dt.datetime.now(dt.timezone.utc)) - 2.0
result = track_job_queue_time(queue_start, tracked_request)

assert result is True
Expand All @@ -61,7 +63,9 @@ def test_track_job_queue_time_valid(with_t, tracked_request):
[
str(""),
str("123"),
str(datetime_to_timestamp(dt.datetime.utcnow()) + 3600.0), # one hour in future
str(
datetime_to_timestamp(dt.datetime.now(dt.timezone.utc)) + 3600.0
), # one hour in future
str(datetime_to_timestamp(dt.datetime(2009, 1, 1))), # before ambig cutoff
],
)
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/core/test_tracked_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def test_start_span_at_max_ignores_span(caplog, tracked_request):
def test_span_captures_backtrace(tracked_request):
span = tracked_request.start_span(operation="Sql/Work")
# Pretend it was started 1 second ago
span.start_time = dt.datetime.utcnow() - dt.timedelta(seconds=1)
span.start_time = dt.datetime.now(dt.timezone.utc) - dt.timedelta(seconds=1)
tracked_request.stop_span()
assert "stack" in span.tags

Expand Down

0 comments on commit 61d2861

Please sign in to comment.