Skip to content

Commit

Permalink
refactor: replace all occurences of deprecated method datetime.utcnow…
Browse files Browse the repository at this point in the history
…() with datetime.now(tz=timezone.utc)

Update imports to accomodate this change

Resolves issue saltstack#65604
  • Loading branch information
abismor committed Nov 24, 2023
1 parent 6f9c83a commit 2c4d713
Show file tree
Hide file tree
Showing 34 changed files with 155 additions and 155 deletions.
4 changes: 2 additions & 2 deletions salt/beacons/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@
to check the minion log for errors after configuring this beacon.
"""
import datetime
from datetime import datetime, timezone
import logging

import salt.exceptions
Expand Down Expand Up @@ -117,7 +117,7 @@ def beacon(config):
Return status for requested information
"""
log.debug(config)
ctime = datetime.datetime.utcnow().isoformat()
ctime = datetime.now(tz=timezone.utc).isoformat()

whitelist = []
config = salt.utils.beacons.remove_hidden_options(config, whitelist)
Expand Down
4 changes: 2 additions & 2 deletions salt/client/ssh/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import base64
import binascii
import copy
import datetime
from datetime import datetime, timezone
import getpass
import hashlib
import logging
Expand Down Expand Up @@ -408,7 +408,7 @@ def _update_roster(self):
'# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n'
" host: {hostname}\n user: {user}\n passwd: {passwd}\n".format(
s_user=getpass.getuser(),
s_time=datetime.datetime.utcnow().isoformat(),
s_time=datetime.now(tz=timezone.utc).isoformat(),
hostname=self.opts.get("tgt", ""),
user=self.opts.get("ssh_user", ""),
passwd=self.opts.get("ssh_passwd", ""),
Expand Down
8 changes: 4 additions & 4 deletions salt/cloud/clouds/ec2.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@

import base64
import binascii
import datetime
from datetime import datetime, timezone
import decimal
import hashlib
import hmac
Expand Down Expand Up @@ -290,7 +290,7 @@ def query(
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
params_with_headers = params.copy()
timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
timestamp = datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

if not location:
location = get_location()
Expand Down Expand Up @@ -327,7 +327,7 @@ def query(
host = endpoint.strip()

# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
t = datetime.now(tz=timezone.utc)
amz_date = t.strftime("%Y%m%dT%H%M%SZ") # Format date as YYYYMMDD'T'HHMMSS'Z'
datestamp = t.strftime("%Y%m%d") # Date w/o time, used in credential scope

Expand Down Expand Up @@ -1198,7 +1198,7 @@ def get_imageid(vm_):
"Filter.0.Value.0": image,
}
# Query AWS, sort by 'creationDate' and get the last imageId
_t = lambda x: datetime.datetime.strptime(
_t = lambda x: datetime.strptime(
x["creationDate"], "%Y-%m-%dT%H:%M:%S.%fZ"
)
image_id = sorted(
Expand Down
4 changes: 2 additions & 2 deletions salt/cloud/clouds/joyent.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"""

import base64
import datetime
from datetime import datetime, timezone
import http.client
import inspect
import logging
Expand Down Expand Up @@ -1159,7 +1159,7 @@ def query(action=None, command=None, args=None, method="GET", location=None, dat
if (not user) or (not ssh_keyfile) or (not ssh_keyname) or (not location):
return None

timenow = datetime.datetime.utcnow()
timenow = datetime.now(tz=timezone.utc)
timestamp = timenow.strftime("%a, %d %b %Y %H:%M:%S %Z").strip()
rsa_key = salt.crypt.get_rsa_key(ssh_keyfile, None)
if HAS_M2:
Expand Down
8 changes: 4 additions & 4 deletions salt/grains/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
as those returned here
"""

import datetime
from datetime import datetime, timezone
import hashlib
import locale
import logging
Expand Down Expand Up @@ -2698,7 +2698,7 @@ def locale_info():
grains["locale_info"]["timezone"] = "unknown"
if _DATEUTIL_TZ:
try:
grains["locale_info"]["timezone"] = datetime.datetime.now(
grains["locale_info"]["timezone"] = datetime.now(
dateutil.tz.tzlocal()
).tzname()
except UnicodeDecodeError:
Expand Down Expand Up @@ -2810,11 +2810,11 @@ def ip_fqdn():
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
start_time = datetime.now(tz=timezone.utc)
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list({item[4][0] for item in info})
except (OSError, UnicodeError):
timediff = datetime.datetime.utcnow() - start_time
timediff = datetime.now(tz=timezone.utc) - start_time
if timediff.seconds > 5 and __opts__["__role"] == "master":
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
Expand Down
4 changes: 2 additions & 2 deletions salt/modules/inspectlib/fsdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@


import csv
import datetime
from datetime import datetime, timezone
import gzip
import os
import re
Expand Down Expand Up @@ -72,7 +72,7 @@ def _label(self):
:return:
"""
return datetime.datetime.utcnow().strftime("%Y%m%d-%H%M%S")
return datetime.now(tz=timezone.utc).strftime("%Y%m%d-%H%M%S")

def new(self):
"""
Expand Down
4 changes: 2 additions & 2 deletions salt/modules/purefa.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@

import os
import platform
from datetime import datetime
from datetime import datetime, timezone

from salt.exceptions import CommandExecutionError

Expand Down Expand Up @@ -235,7 +235,7 @@ def snap_create(name, suffix=None):
array = _get_system()
if suffix is None:
suffix = "snap-" + str(
(datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds()
(datetime.now(tz=timezone.utc) - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds()
)
suffix = suffix.replace(".", "")
if _get_volume(name, array) is not None:
Expand Down
4 changes: 2 additions & 2 deletions salt/modules/purefb.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@


import os
from datetime import datetime
from datetime import datetime, timezone

from salt.exceptions import CommandExecutionError

Expand Down Expand Up @@ -195,7 +195,7 @@ def snap_create(name, suffix=None):
blade = _get_blade()
if suffix is None:
suffix = "snap-" + str(
(datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds()
(datetime.now(tz=timezone.utc) - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds()
)
suffix = suffix.replace(".", "")
if _get_fs(name, blade) is not None:
Expand Down
4 changes: 2 additions & 2 deletions salt/modules/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import os.path
import re
from datetime import datetime, timedelta, tzinfo
from datetime import datetime, timedelta, tzinfo, timezone

import salt.utils.files
import salt.utils.path
Expand Down Expand Up @@ -255,7 +255,7 @@ def _get_offset_time(utc_offset):
if utc_offset is not None:
minutes = _offset_to_min(utc_offset)
offset = timedelta(minutes=minutes)
offset_time = datetime.utcnow() + offset
offset_time = datetime.now(tz=timezone.utc) + offset
offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes))
else:
offset_time = datetime.now()
Expand Down
10 changes: 5 additions & 5 deletions salt/modules/tls.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@
import os
import re
import time
from datetime import datetime
from datetime import datetime, timezone

import salt.utils.data
import salt.utils.files
Expand Down Expand Up @@ -357,7 +357,7 @@ def maybe_fix_ssl_version(ca_name, cacert_path=None, ca_filename=None):
try:
days = (
datetime.strptime(cert.get_notAfter(), "%Y%m%d%H%M%SZ")
- datetime.utcnow()
- datetime.now(tz=timezone.utc)
).days
except (ValueError, TypeError):
days = 365
Expand Down Expand Up @@ -763,7 +763,7 @@ def create_ca(
err,
)
bck = "{}.unloadable.{}".format(
ca_keyp, datetime.utcnow().strftime("%Y%m%d%H%M%S")
ca_keyp, datetime.now(tz=timezone.utc).strftime("%Y%m%d%H%M%S")
)
log.info("Saving unloadable CA ssl key in %s", bck)
os.rename(ca_keyp, bck)
Expand Down Expand Up @@ -821,7 +821,7 @@ def create_ca(
keycontent = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key)
write_key = True
if os.path.exists(ca_keyp):
bck = "{}.{}".format(ca_keyp, datetime.utcnow().strftime("%Y%m%d%H%M%S"))
bck = "{}.{}".format(ca_keyp, datetime.now(tz=timezone.utc).strftime("%Y%m%d%H%M%S"))
with salt.utils.files.fopen(ca_keyp) as fic:
old_key = salt.utils.stringutils.to_unicode(fic.read()).strip()
if old_key.strip() == keycontent.strip():
Expand Down Expand Up @@ -1912,7 +1912,7 @@ def revoke_cert(
)
index_r_data = "R\t{}\t{}\t{}".format(
expire_date,
_four_digit_year_to_two_digit(datetime.utcnow()),
_four_digit_year_to_two_digit(datetime.now(tz=timezone.utc)),
index_serial_subject,
)

Expand Down
4 changes: 2 additions & 2 deletions salt/modules/vsphere.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@
"""


import datetime
from datetime import datetime, timezone
import logging
import sys
from functools import wraps
Expand Down Expand Up @@ -3878,7 +3878,7 @@ def update_host_datetime(
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
date_time_manager = _get_date_time_mgr(host_ref)
try:
date_time_manager.UpdateDateTime(datetime.datetime.utcnow())
date_time_manager.UpdateDateTime(datetime.now(tz=timezone.utc))
except vim.fault.HostConfigFault as err:
msg = "'vsphere.update_date_time' failed for host {}: {}".format(
host_name, err
Expand Down
6 changes: 3 additions & 3 deletions salt/modules/win_timezone.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Module for managing timezone on Windows systems.
"""
import logging
from datetime import datetime
from datetime import datetime, timezone

from salt.exceptions import CommandExecutionError

Expand Down Expand Up @@ -240,7 +240,7 @@ def get_offset():
"""
# http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and-pytz-localize-vs-normalize/
tz_object = pytz.timezone(get_zone())
utc_time = pytz.utc.localize(datetime.utcnow())
utc_time = pytz.utc.localize(datetime.now(tz=timezone.utc))
loc_time = utc_time.astimezone(tz_object)
norm_time = tz_object.normalize(loc_time)
return norm_time.strftime("%z")
Expand All @@ -260,7 +260,7 @@ def get_zonecode():
salt '*' timezone.get_zonecode
"""
tz_object = pytz.timezone(get_zone())
loc_time = tz_object.localize(datetime.utcnow())
loc_time = tz_object.localize(datetime.now(tz=timezone.utc))
return loc_time.tzname()


Expand Down
24 changes: 12 additions & 12 deletions salt/modules/x509.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

import ast
import ctypes
import datetime
from datetime import datetime, timezone
import glob
import hashlib
import logging
Expand Down Expand Up @@ -252,13 +252,13 @@ def _parse_openssl_crl(crl_filename):
crl["Issuer"] = subject
if line.startswith("Last Update: "):
crl["Last Update"] = line.replace("Last Update: ", "")
last_update = datetime.datetime.strptime(
last_update = datetime.strptime(
crl["Last Update"], "%b %d %H:%M:%S %Y %Z"
)
crl["Last Update"] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith("Next Update: "):
crl["Next Update"] = line.replace("Next Update: ", "")
next_update = datetime.datetime.strptime(
next_update = datetime.strptime(
crl["Next Update"], "%b %d %H:%M:%S %Y %Z"
)
crl["Next Update"] = next_update.strftime("%Y-%m-%d %H:%M:%S")
Expand All @@ -282,7 +282,7 @@ def _parse_openssl_crl(crl_filename):
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
for rev_values in rev_yaml.values():
if "Revocation Date" in rev_values:
rev_date = datetime.datetime.strptime(
rev_date = datetime.strptime(
rev_values["Revocation Date"], "%b %d %H:%M:%S %Y %Z"
)
rev_values["Revocation Date"] = rev_date.strftime("%Y-%m-%d %H:%M:%S")
Expand Down Expand Up @@ -1000,18 +1000,18 @@ def create_crl(
serial_number = salt.utils.stringutils.to_bytes(serial_number)

if "not_after" in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
not_after = datetime.strptime(
rev_item["not_after"], "%Y-%m-%d %H:%M:%S"
)
if datetime.datetime.now() > not_after:
if datetime.now() > not_after:
continue

if "revocation_date" not in rev_item:
rev_item["revocation_date"] = datetime.datetime.now().strftime(
rev_item["revocation_date"] = datetime.now().strftime(
"%Y-%m-%d %H:%M:%S"
)

rev_date = datetime.datetime.strptime(
rev_date = datetime.strptime(
rev_item["revocation_date"], "%Y-%m-%d %H:%M:%S"
)
rev_date = rev_date.strftime("%Y%m%d%H%M%SZ")
Expand Down Expand Up @@ -1534,7 +1534,7 @@ def create_certificate(path=None, text=False, overwrite=True, ca_server=None, **
fmt = "%Y-%m-%d %H:%M:%S"
if "not_before" in kwargs:
try:
time = datetime.datetime.strptime(kwargs["not_before"], fmt)
time = datetime.strptime(kwargs["not_before"], fmt)
except:
raise salt.exceptions.SaltInvocationError(
"not_before: {} is not in required format {}".format(
Expand All @@ -1552,7 +1552,7 @@ def create_certificate(path=None, text=False, overwrite=True, ca_server=None, **

if "not_after" in kwargs:
try:
time = datetime.datetime.strptime(kwargs["not_after"], fmt)
time = datetime.strptime(kwargs["not_after"], fmt)
except:
raise salt.exceptions.SaltInvocationError(
"not_after: {} is not in required format {}".format(
Expand Down Expand Up @@ -1959,7 +1959,7 @@ def expired(certificate):
ret["path"] = certificate
cert = _get_certificate_obj(certificate)

_now = datetime.datetime.utcnow()
_now = datetime.now(tz=timezone.utc)
_expiration_date = cert.get_not_after().get_datetime()

ret["cn"] = _parse_subject(cert.get_subject())["CN"]
Expand Down Expand Up @@ -2003,7 +2003,7 @@ def will_expire(certificate, days):

cert = _get_certificate_obj(certificate)

_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_check_time = datetime.now(tz=timezone.utc) + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()

ret["cn"] = _parse_subject(cert.get_subject())["CN"]
Expand Down
4 changes: 2 additions & 2 deletions salt/modules/x509_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@
"""
import base64
import copy
import datetime
from datetime import datetime, timezone, timedelta
import glob
import logging
import os.path
Expand Down Expand Up @@ -1374,7 +1374,7 @@ def expires(certificate, days=0):
"""
cert = x509util.load_cert(certificate)
# dates are encoded in UTC/GMT, they are returned as a naive datetime object
return cert.not_valid_after <= datetime.datetime.utcnow() + datetime.timedelta(
return cert.not_valid_after <= datetime.now(tz=timezone.utc) + timedelta(
days=days
)

Expand Down
Loading

0 comments on commit 2c4d713

Please sign in to comment.