Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:

strategy:
matrix:
python-version: ['3.10', '3.11']
python-version: ['3.12']

steps:
- uses: actions/checkout@v4
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ jobs:

steps:
- uses: actions/checkout@v4
- name: Set up Python 3.11
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: 3.11
python-version: 3.12
- name: Install dependencies
id: install-deps
run: |
Expand Down Expand Up @@ -64,10 +64,10 @@ jobs:

steps:
- uses: actions/checkout@v4
- name: Set up Python 3.11
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: 3.11
python-version: 3.12
- name: Build
id: build
run: |
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:

strategy:
matrix:
python-version: ['3.10', '3.12']
python-version: ['3.12']

steps:
- uses: actions/checkout@v4
Expand Down Expand Up @@ -91,7 +91,7 @@ jobs:

strategy:
matrix:
python-version: ['3.10', '3.12']
python-version: ['3.12']

steps:
- uses: actions/checkout@v4
Expand Down Expand Up @@ -174,10 +174,10 @@ jobs:
libldap2-dev \
libsasl2-dev \
xmlsec1
- name: Set up Python 3.10
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: '3.10'
python-version: '3.12'
architecture: 'x64'
- name: Install dependencies
id: install-deps
Expand Down
4 changes: 2 additions & 2 deletions alerta/auth/oidc.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
from datetime import datetime, timedelta
from datetime import UTC, datetime, timedelta
from uuid import uuid4

import jwt
Expand Down Expand Up @@ -96,7 +96,7 @@ def openid():
data['client_secret'] = current_app.config['OAUTH2_CLIENT_SECRET']
r = requests.post(token_endpoint, data)
elif preferred_token_auth_method == 'client_secret_jwt':
now = datetime.utcnow()
now = datetime.now(UTC)
payload = dict(
iss=request.json['clientId'],
sub=request.json['clientId'],
Expand Down
4 changes: 2 additions & 2 deletions alerta/auth/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime, timedelta
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any, List, cast
from urllib.parse import urljoin
from uuid import uuid4
Expand Down Expand Up @@ -49,7 +49,7 @@ def get_customers(login: str, groups: List[str]) -> List[str]:

def create_token(user_id: str, name: str, login: str, provider: str, customers: List[str], scopes: List[str],
email: str = None, email_verified: bool = None, picture: str = None, **kwargs) -> 'Jwt':
now = datetime.utcnow()
now = datetime.now(UTC)
return Jwt(
iss=request.url_root,
typ='Bearer',
Expand Down
4 changes: 2 additions & 2 deletions alerta/commands.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import sys
from datetime import datetime, timedelta
from datetime import UTC, datetime, timedelta
from typing import Any, Dict

import click
Expand Down Expand Up @@ -63,7 +63,7 @@ def key(username, want_key, scopes, duration, text, customer, all, force):
raise click.UsageError('Can only set API key with "--username".')

scopes = [Scope(s) for s in scopes] or [Scope.admin, Scope.write, Scope.read]
expires = datetime.utcnow() + timedelta(seconds=duration) if duration else None
expires = datetime.now(UTC) + timedelta(seconds=duration) if duration else None
text = text or 'Created by alertad script'

def create_key(admin, key=None):
Expand Down
26 changes: 13 additions & 13 deletions alerta/database/backends/mongodb/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from collections import defaultdict
from datetime import date, datetime, time, timedelta
from datetime import UTC, date, datetime, time, timedelta

from flask import current_app
from pymongo import ASCENDING, TEXT, MongoClient, ReturnDocument
Expand Down Expand Up @@ -187,7 +187,7 @@ def is_flapping(self, alert, window=1800, count=2):
}},
{'$unwind': '$history'},
{'$match': {
'history.updateTime': {'$gt': datetime.utcnow() - timedelta(seconds=window)},
'history.updateTime': {'$gt': datetime.now(UTC) - timedelta(seconds=window)},
'history.type': 'severity'
}},
{'$group': {'_id': '$history.type', 'count': {'$sum': 1}}}
Expand All @@ -211,7 +211,7 @@ def dedup_alert(self, alert, history):
'customer': alert.customer
}

now = datetime.utcnow()
now = datetime.now(UTC)
update = {
'$set': {
'status': alert.status,
Expand Down Expand Up @@ -1366,7 +1366,7 @@ def get_heartbeats_by_status(self, status=None, query=None, page=None, page_size
if status:
pipeline.extend([
{'$addFields': {'timeoutInMs': {'$multiply': ['$timeout', 1000]}}},
{'$addFields': {'isExpired': {'$gt': [{'$subtract': [datetime.utcnow(), '$receiveTime']}, '$timeoutInMs']}}},
{'$addFields': {'isExpired': {'$gt': [{'$subtract': [datetime.now(UTC), '$receiveTime']}, '$timeoutInMs']}}},
{'$addFields': {'isSlow': {'$gt': [{'$subtract': ['$receiveTime', '$createTime']}, max_latency]}}}
])
match_or = list()
Expand Down Expand Up @@ -1444,7 +1444,7 @@ def update_key_last_used(self, key):
return self.get_db().keys.update_one(
{'$or': [{'key': key}, {'_id': key}]},
{
'$set': {'lastUsedTime': datetime.utcnow()},
'$set': {'lastUsedTime': datetime.now(UTC)},
'$inc': {'count': 1}
}
).matched_count == 1
Expand Down Expand Up @@ -1511,7 +1511,7 @@ def get_user_by_hash(self, hash):
def update_last_login(self, id):
return self.get_db().users.update_one(
{'_id': id},
update={'$set': {'lastLogin': datetime.utcnow()}}
update={'$set': {'lastLogin': datetime.now(UTC)}}
).matched_count == 1

def update_user(self, id, **kwargs):
Expand Down Expand Up @@ -1553,7 +1553,7 @@ def delete_user(self, id):
def set_email_hash(self, id, hash):
return self.get_db().users.update_one(
{'_id': id},
update={'$set': {'hash': hash, 'updateTime': datetime.utcnow()}}
update={'$set': {'hash': hash, 'updateTime': datetime.now(UTC)}}
).matched_count == 1

# GROUPS
Expand Down Expand Up @@ -1769,7 +1769,7 @@ def get_customer_notes(self, customer, page=None, page_size=None):
return self.get_db().notes.find({'customer': customer}).skip((page - 1) * page_size).limit(page_size)

def update_note(self, id, **kwargs):
kwargs['updateTime'] = datetime.utcnow()
kwargs['updateTime'] = datetime.now(UTC)
return self.get_db().notes.find_one_and_update(
{'_id': id},
update={'$set': kwargs},
Expand Down Expand Up @@ -1855,12 +1855,12 @@ def get_expired(self, expired_threshold, info_threshold):
# and 'informational' alerts older than "info_threshold" seconds

if expired_threshold:
expired_seconds_ago = datetime.utcnow() - timedelta(seconds=expired_threshold)
expired_seconds_ago = datetime.now(UTC) - timedelta(seconds=expired_threshold)
self.get_db().alerts.delete_many(
{'status': {'$in': ['closed', 'expired']}, 'lastReceiveTime': {'$lt': expired_seconds_ago}})

if info_threshold:
info_seconds_ago = datetime.utcnow() - timedelta(seconds=info_threshold)
info_seconds_ago = datetime.now(UTC) - timedelta(seconds=info_threshold)
self.get_db().alerts.delete_many({'severity': alarm_model.DEFAULT_INFORM_SEVERITY, 'lastReceiveTime': {'$lt': info_seconds_ago}})

# get list of alerts to be newly expired
Expand All @@ -1870,7 +1870,7 @@ def get_expired(self, expired_threshold, info_threshold):
'computedTimeout': {'$multiply': [{'$ifNull': ['$timeout', current_app.config['ALERT_TIMEOUT']]}, 1000]}
}},
{'$addFields': {
'isExpired': {'$lt': [{'$add': ['$lastReceiveTime', '$computedTimeout']}, datetime.utcnow()]}
'isExpired': {'$lt': [{'$add': ['$lastReceiveTime', '$computedTimeout']}, datetime.now(UTC)]}
}},
{'$match': {'isExpired': True, 'computedTimeout': {'$ne': 0}}}
]
Expand Down Expand Up @@ -1920,7 +1920,7 @@ def get_unshelve(self):
'computedTimeout': {'$multiply': [{'$ifNull': ['$history.timeout', current_app.config['SHELVE_TIMEOUT']]}, 1000]}
}},
{'$addFields': {
'isExpired': {'$lt': [{'$add': ['$updateTime', '$computedTimeout']}, datetime.utcnow()]}
'isExpired': {'$lt': [{'$add': ['$updateTime', '$computedTimeout']}, datetime.now(UTC)]}
}},
{'$match': {'isExpired': True, 'computedTimeout': {'$ne': 0}}}
]
Expand Down Expand Up @@ -1970,7 +1970,7 @@ def get_unack(self):
'computedTimeout': {'$multiply': [{'$ifNull': ['$history.timeout', current_app.config['ACK_TIMEOUT']]}, 1000]}
}},
{'$addFields': {
'isExpired': {'$lt': [{'$add': ['$updateTime', '$computedTimeout']}, datetime.utcnow()]}
'isExpired': {'$lt': [{'$add': ['$updateTime', '$computedTimeout']}, datetime.now(UTC)]}
}},
{'$match': {'isExpired': True, 'computedTimeout': {'$ne': 0}}}
]
Expand Down
12 changes: 6 additions & 6 deletions alerta/database/backends/mongodb/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import json
import re
from collections import namedtuple
from datetime import datetime
from datetime import UTC, datetime
from typing import Any, Dict, List # noqa

import pytz
Expand Down Expand Up @@ -247,11 +247,11 @@ def from_params(params: ImmutableMultiDict, customers=None, query_time=None):
if status:
query['$or'] = list()
if BlackoutStatus.Active in status:
query['$or'].append({'$and': [{'startTime': {'$lte': datetime.utcnow()}}, {'endTime': {'$gt': datetime.utcnow()}}]})
query['$or'].append({'$and': [{'startTime': {'$lte': datetime.now(UTC)}}, {'endTime': {'$gt': datetime.now(UTC)}}]})
if BlackoutStatus.Pending in status:
query['$or'].append({'startTime': {'$gt': datetime.utcnow()}})
query['$or'].append({'startTime': {'$gt': datetime.now(UTC)}})
if BlackoutStatus.Expired in status:
query['$or'].append({'endTime': {'$lte': datetime.utcnow()}})
query['$or'].append({'endTime': {'$lte': datetime.now(UTC)}})

# filter, sort-by, group-by
query = QueryBuilder.filter_query(params, Blackouts.VALID_PARAMS, query)
Expand Down Expand Up @@ -527,9 +527,9 @@ def from_params(params: MultiDict, customers=None, query_time=None):
if status:
query['$or'] = list()
if ApiKeyStatus.Active in status:
query['$or'].append({'expireTime': {'$gte': datetime.utcnow()}})
query['$or'].append({'expireTime': {'$gte': datetime.now(UTC)}})
if ApiKeyStatus.Expired in status:
query['$or'].append({'expireTime': {'$lt': datetime.utcnow()}})
query['$or'].append({'expireTime': {'$lt': datetime.now(UTC)}})

# filter, sort-by, group-by
query = QueryBuilder.filter_query(params, ApiKeys.VALID_PARAMS, query)
Expand Down
10 changes: 5 additions & 5 deletions alerta/database/backends/postgres/base.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import threading
import time
from collections import defaultdict, namedtuple
from datetime import datetime, timedelta
from datetime import UTC, datetime, timedelta
from uuid import uuid4

import psycopg2
Expand Down Expand Up @@ -636,7 +636,7 @@ def get_escalate(self):
FROM alerts
WHERE status='open' AND last_receive_time < %(etime)s
"""
return self._fetchall(select, {'etime': datetime.utcnow() - timedelta(minutes=current_app.config['ESCALATE_TIME'])}, limit=1000)
return self._fetchall(select, {'etime': datetime.now(UTC) - timedelta(minutes=current_app.config['ESCALATE_TIME'])}, limit=1000)

def get_alert_history(self, alert, page=None, page_size=None):
select = """
Expand Down Expand Up @@ -1505,7 +1505,7 @@ def create_notification_rule_history(self, update_type: str, notification_rule):
data['reactivate'] = data['reactivate'].isoformat() if data.get('reactivate') is not None else None
data['createTime'] = data['createTime'].isoformat() if data.get('createTime') is not None else None
data['delayTime'] = str(data['delayTime']) if data.get('delayTime') is not None else None
return self._insert(insert, {'data': data, 'id': notification_rule.id, 'user': notification_rule.user, 'type': update_type, 'create_time': datetime.utcnow()})
return self._insert(insert, {'data': data, 'id': notification_rule.id, 'user': notification_rule.user, 'type': update_type, 'create_time': datetime.now(UTC)})

def get_notification_rule_history(self, rule_id: str, page, page_size):
select = """
Expand Down Expand Up @@ -1773,7 +1773,7 @@ def confirm_notification_history(self, id):
WHERE id=%(id)s
RETURNING *
"""
return self._updateone(update, {'id': id, 'time': datetime.utcnow()}, returning=True)
return self._updateone(update, {'id': id, 'time': datetime.now(UTC)}, returning=True)

# ESCALATION RULES

Expand Down Expand Up @@ -1853,7 +1853,7 @@ def get_escalation_alerts(self):
SELECT * from alert_tags
WHERE alert_tags.id NOT IN (SELECT DISTINCT alert_excluded.id FROM alert_excluded)
"""
return self._fetchall(select, {'now': datetime.utcnow()}, limit='ALL')
return self._fetchall(select, {'now': datetime.now(UTC)}, limit='ALL')

def update_escalation_rule(self, id, **kwargs):
update = """
Expand Down
4 changes: 2 additions & 2 deletions alerta/dev.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import datetime
from datetime import UTC, datetime

BUILD_NUMBER = 'DEV'
BUILD_DATE = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
BUILD_DATE = datetime.now(UTC).strftime('%Y-%m-%dT%H:%M:%SZ')
BUILD_VCS_NUMBER = 'HEAD'
2 changes: 1 addition & 1 deletion alerta/management/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def health_check():
try:
heartbeats = Heartbeat.find_all()
for heartbeat in heartbeats:
delta = datetime.datetime.utcnow() - heartbeat.receive_time
delta = datetime.datetime.now(datetime.UTC) - heartbeat.receive_time
threshold = int(heartbeat.timeout) * 4
if delta.seconds > threshold:
return f'HEARTBEAT_STALE: {heartbeat.origin}', 503
Expand Down
Loading