Skip to content

Commit

Permalink
resolve several deprecated warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
jertel committed Dec 2, 2023
1 parent 31468fb commit 2ced92f
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 18 deletions.
16 changes: 7 additions & 9 deletions elastalert/elastalert.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
from socket import error
import statsd


import dateutil.tz
import pytz
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor
Expand Down Expand Up @@ -1130,26 +1128,26 @@ def start(self):
name='Internal: Handle Config Change')
self.scheduler.start()
while self.running:
next_run = datetime.datetime.utcnow() + self.run_every
next_run = datetime.datetime.now(tz=datetime.UTC) + self.run_every

# Quit after end_time has been reached
if self.args.end:
endtime = ts_to_dt(self.args.end)

next_run_dt = next_run.replace(tzinfo=dateutil.tz.tzutc())
next_run_dt = next_run.replace(tzinfo=timezone.utc)
if next_run_dt > endtime:
elastalert_logger.info("End time '%s' falls before the next run time '%s', exiting." % (endtime, next_run_dt))
exit(0)

if next_run < datetime.datetime.utcnow():
if next_run < datetime.datetime.now(tz=datetime.UTC):
continue

# Show disabled rules
if self.show_disabled_rules:
elastalert_logger.info("Disabled rules are: %s" % (str(self.get_disabled_rules())))

# Wait before querying again
sleep_duration = total_seconds(next_run - datetime.datetime.utcnow())
sleep_duration = total_seconds(next_run - datetime.datetime.now(tz=datetime.UTC))
self.sleep_for(sleep_duration)

def wait_until_responsive(self, timeout, clock=timeit.default_timer):
Expand Down Expand Up @@ -1209,7 +1207,7 @@ def handle_config_change(self):

def handle_rule_execution(self, rule):
self.thread_data.alerts_sent = 0
next_run = datetime.datetime.utcnow() + rule['run_every']
next_run = datetime.datetime.now(tz=datetime.UTC) + rule['run_every']
# Set endtime based on the rule's delay
delay = rule.get('query_delay')
if hasattr(self.args, 'end') and self.args.end:
Expand All @@ -1232,7 +1230,7 @@ def handle_rule_execution(self, rule):
# That means that we need to pause execution after this run
if endtime_epoch + rule['run_every'].total_seconds() < exec_next - 59:
# apscheduler requires pytz tzinfos, so don't use unix_to_dt here!
rule['next_starttime'] = datetime.datetime.utcfromtimestamp(exec_next).replace(tzinfo=pytz.utc)
rule['next_starttime'] = datetime.datetime.fromtimestamp(exec_next, tz=datetime.UTC).replace(tzinfo=pytz.utc)
if rule.get('limit_execution_coverage'):
rule['next_min_starttime'] = rule['next_starttime']
if not rule['has_run_once']:
Expand Down Expand Up @@ -1260,7 +1258,7 @@ def handle_rule_execution(self, rule):

self.thread_data.alerts_sent = 0

if next_run < datetime.datetime.utcnow():
if next_run < datetime.datetime.now(tz=datetime.UTC):
# We were processing for longer than our refresh interval
# This can happen if --start was specified with a large time period
# or if we are running too slow to process events in real time.
Expand Down
9 changes: 5 additions & 4 deletions elastalert/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,8 @@ def dt_to_ts_with_format(dt, ts_format):


def ts_now():
return datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
now = datetime.datetime.now(tz=datetime.UTC)
return now.replace(tzinfo=dateutil.tz.tzutc())


def ts_utc_to_tz(ts, tz_name):
Expand Down Expand Up @@ -268,16 +269,16 @@ def total_seconds(dt):


def dt_to_int(dt):
dt = dt.replace(tzinfo=None)
return int(total_seconds((dt - datetime.datetime.utcfromtimestamp(0))) * 1000)
dt = dt.replace(tzinfo=datetime.UTC)
return int(total_seconds((dt - datetime.datetime.fromtimestamp(0, tz=datetime.UTC))) * 1000)


def unixms_to_dt(ts):
return unix_to_dt(float(ts) / 1000)


def unix_to_dt(ts):
dt = datetime.datetime.utcfromtimestamp(float(ts))
dt = datetime.datetime.fromtimestamp(float(ts), tz=datetime.UTC)
dt = dt.replace(tzinfo=dateutil.tz.tzutc())
return dt

Expand Down
6 changes: 3 additions & 3 deletions tests/base_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ def test_silence(ea):
with mock.patch('elastalert.elastalert.ts_now') as mock_ts:
with mock.patch('elastalert.elastalert.elasticsearch_client'):
# Converted twice to add tzinfo
mock_ts.return_value = ts_to_dt(dt_to_ts(datetime.datetime.utcnow() + datetime.timedelta(hours=5)))
mock_ts.return_value = ts_to_dt(dt_to_ts(datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(hours=5)))
ea.run_rule(ea.rules[0], END, START)
assert ea.rules[0]['alert'][0].alert.call_count == 1

Expand Down Expand Up @@ -681,7 +681,7 @@ def test_silence_query_key(ea):
with mock.patch('elastalert.elastalert.ts_now') as mock_ts:
with mock.patch('elastalert.elastalert.elasticsearch_client'):
# Converted twice to add tzinfo
mock_ts.return_value = ts_to_dt(dt_to_ts(datetime.datetime.utcnow() + datetime.timedelta(hours=5)))
mock_ts.return_value = ts_to_dt(dt_to_ts(datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(hours=5)))
ea.run_rule(ea.rules[0], END, START)
assert ea.rules[0]['alert'][0].alert.call_count == 2

Expand All @@ -708,7 +708,7 @@ def test_realert(ea):
with mock.patch('elastalert.elastalert.ts_now') as mock_ts:
with mock.patch('elastalert.elastalert.elasticsearch_client'):
# mock_ts is converted twice to add tzinfo
mock_ts.return_value = ts_to_dt(dt_to_ts(datetime.datetime.utcnow() + datetime.timedelta(minutes=10)))
mock_ts.return_value = ts_to_dt(dt_to_ts(datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(minutes=10)))
ea.rules[0]['type'].matches = matches
ea.run_rule(ea.rules[0], END, START)
assert ea.rules[0]['alert'][0].alert.call_count == 2
Expand Down
4 changes: 2 additions & 2 deletions tests/util_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ def test_parse_deadline(spec, expected_deadline):
# Note: Can't mock ``utcnow`` directly because ``datetime`` is a built-in.
class MockDatetime(datetime):
@staticmethod
def utcnow():
return dt('2017-07-07T10:00:00.000Z')
def now(tz=None):
return datetime(2017, 7, 7, 10, 0, 0)

with mock.patch('datetime.datetime', MockDatetime):
assert parse_deadline(spec) == expected_deadline
Expand Down

0 comments on commit 2ced92f

Please sign in to comment.