Skip to content

Commit

Permalink
Avoid deprecated utcnow() (ansible-collections#8222)
Browse files Browse the repository at this point in the history
Avoid deprecated utcnow().
  • Loading branch information
felixfontein authored and aretrosen committed Apr 22, 2024
1 parent 17afd0e commit 7e1a5d5
Show file tree
Hide file tree
Showing 19 changed files with 142 additions and 64 deletions.
3 changes: 3 additions & 0 deletions changelogs/fragments/8222-datetime.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
minor_changes:
- "Use offset-aware ``datetime.datetime`` objects (with timezone UTC) instead of offset-naive UTC timestamps,
which are deprecated in Python 3.12 (https://github.com/ansible-collections/community.general/pull/8222)."
13 changes: 8 additions & 5 deletions plugins/callback/loganalytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,16 @@
import socket
import getpass

from datetime import datetime
from os.path import basename

from ansible.module_utils.urls import open_url
from ansible.parsing.ajson import AnsibleJSONEncoder
from ansible.plugins.callback import CallbackBase

from ansible_collections.community.general.plugins.module_utils.datetime import (
now,
)


class AzureLogAnalyticsSource(object):
def __init__(self):
Expand Down Expand Up @@ -93,7 +96,7 @@ def __build_workspace_url(self, workspace_id):
return "https://{0}.ods.opinsights.azure.com/api/logs?api-version=2016-04-01".format(workspace_id)

def __rfc1123date(self):
return datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
return now().strftime('%a, %d %b %Y %H:%M:%S GMT')

def send_event(self, workspace_id, shared_key, state, result, runtime):
if result._task_fields['args'].get('_ansible_check_mode') is True:
Expand Down Expand Up @@ -167,7 +170,7 @@ def __init__(self, display=None):

def _seconds_since_start(self, result):
return (
datetime.utcnow() -
now() -
self.start_datetimes[result._task._uuid]
).total_seconds()

Expand All @@ -185,10 +188,10 @@ def v2_playbook_on_start(self, playbook):
self.loganalytics.ansible_playbook = basename(playbook._file_name)

def v2_playbook_on_task_start(self, task, is_conditional):
self.start_datetimes[task._uuid] = datetime.utcnow()
self.start_datetimes[task._uuid] = now()

def v2_playbook_on_handler_task_start(self, task):
self.start_datetimes[task._uuid] = datetime.utcnow()
self.start_datetimes[task._uuid] = now()

def v2_runner_on_ok(self, result, **kwargs):
self.loganalytics.send_event(
Expand Down
9 changes: 6 additions & 3 deletions plugins/callback/logstash.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@
import socket
import uuid
import logging
from datetime import datetime

try:
import logstash
Expand All @@ -109,6 +108,10 @@

from ansible.plugins.callback import CallbackBase

from ansible_collections.community.general.plugins.module_utils.datetime import (
now,
)


class CallbackModule(CallbackBase):

Expand All @@ -126,7 +129,7 @@ def __init__(self):
"pip install python-logstash for Python 2"
"pip install python3-logstash for Python 3")

self.start_time = datetime.utcnow()
self.start_time = now()

def _init_plugin(self):
if not self.disabled:
Expand Down Expand Up @@ -185,7 +188,7 @@ def v2_playbook_on_start(self, playbook):
self.logger.info("ansible start", extra=data)

def v2_playbook_on_stats(self, stats):
end_time = datetime.utcnow()
end_time = now()
runtime = end_time - self.start_time
summarize_stat = {}
for host in stats.processed.keys():
Expand Down
13 changes: 8 additions & 5 deletions plugins/callback/splunk.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,16 @@
import socket
import getpass

from datetime import datetime
from os.path import basename

from ansible.module_utils.urls import open_url
from ansible.parsing.ajson import AnsibleJSONEncoder
from ansible.plugins.callback import CallbackBase

from ansible_collections.community.general.plugins.module_utils.datetime import (
now,
)


class SplunkHTTPCollectorSource(object):
def __init__(self):
Expand Down Expand Up @@ -134,7 +137,7 @@ def send_event(self, url, authtoken, validate_certs, include_milliseconds, batch
else:
time_format = '%Y-%m-%d %H:%M:%S +0000'

data['timestamp'] = datetime.utcnow().strftime(time_format)
data['timestamp'] = now().strftime(time_format)
data['host'] = self.host
data['ip_address'] = self.ip_address
data['user'] = self.user
Expand Down Expand Up @@ -181,7 +184,7 @@ def __init__(self, display=None):

def _runtime(self, result):
return (
datetime.utcnow() -
now() -
self.start_datetimes[result._task._uuid]
).total_seconds()

Expand Down Expand Up @@ -220,10 +223,10 @@ def v2_playbook_on_start(self, playbook):
self.splunk.ansible_playbook = basename(playbook._file_name)

def v2_playbook_on_task_start(self, task, is_conditional):
self.start_datetimes[task._uuid] = datetime.utcnow()
self.start_datetimes[task._uuid] = now()

def v2_playbook_on_handler_task_start(self, task):
self.start_datetimes[task._uuid] = datetime.utcnow()
self.start_datetimes[task._uuid] = now()

def v2_runner_on_ok(self, result, **kwargs):
self.splunk.send_event(
Expand Down
14 changes: 8 additions & 6 deletions plugins/callback/sumologic.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,16 @@
import socket
import getpass

from datetime import datetime
from os.path import basename

from ansible.module_utils.urls import open_url
from ansible.parsing.ajson import AnsibleJSONEncoder
from ansible.plugins.callback import CallbackBase

from ansible_collections.community.general.plugins.module_utils.datetime import (
now,
)


class SumologicHTTPCollectorSource(object):
def __init__(self):
Expand Down Expand Up @@ -84,8 +87,7 @@ def send_event(self, url, state, result, runtime):
data['uuid'] = result._task._uuid
data['session'] = self.session
data['status'] = state
data['timestamp'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S '
'+0000')
data['timestamp'] = now().strftime('%Y-%m-%d %H:%M:%S +0000')
data['host'] = self.host
data['ip_address'] = self.ip_address
data['user'] = self.user
Expand Down Expand Up @@ -123,7 +125,7 @@ def __init__(self, display=None):

def _runtime(self, result):
return (
datetime.utcnow() -
now() -
self.start_datetimes[result._task._uuid]
).total_seconds()

Expand All @@ -144,10 +146,10 @@ def v2_playbook_on_start(self, playbook):
self.sumologic.ansible_playbook = basename(playbook._file_name)

def v2_playbook_on_task_start(self, task, is_conditional):
self.start_datetimes[task._uuid] = datetime.utcnow()
self.start_datetimes[task._uuid] = now()

def v2_playbook_on_handler_task_start(self, task):
self.start_datetimes[task._uuid] = datetime.utcnow()
self.start_datetimes[task._uuid] = now()

def v2_runner_on_ok(self, result, **kwargs):
self.sumologic.send_event(
Expand Down
32 changes: 32 additions & 0 deletions plugins/module_utils/datetime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2023 Felix Fontein <[email protected]>
# Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
# SPDX-License-Identifier: BSD-2-Clause

from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import datetime as _datetime
import sys


_USE_TIMEZONE = sys.version_info >= (3, 6)


def ensure_timezone_info(value):
if not _USE_TIMEZONE or value.tzinfo is not None:
return value
return value.astimezone(_datetime.timezone.utc)


def fromtimestamp(value):
if _USE_TIMEZONE:
return _datetime.fromtimestamp(value, tz=_datetime.timezone.utc)
return _datetime.utcfromtimestamp(value)


def now():
if _USE_TIMEZONE:
return _datetime.datetime.now(tz=_datetime.timezone.utc)
return _datetime.datetime.utcnow()
8 changes: 6 additions & 2 deletions plugins/module_utils/scaleway.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
from ansible.module_utils.urls import fetch_url
from ansible.module_utils.six.moves.urllib.parse import urlencode

from ansible_collections.community.general.plugins.module_utils.datetime import (
now,
)

SCALEWAY_SECRET_IMP_ERR = None
try:
from passlib.hash import argon2
Expand Down Expand Up @@ -306,10 +310,10 @@ def wait_to_complete_state_transition(self, resource, stable_states, force_wait=
# Prevent requesting the resource status too soon
time.sleep(wait_sleep_time)

start = datetime.datetime.utcnow()
start = now()
end = start + datetime.timedelta(seconds=wait_timeout)

while datetime.datetime.utcnow() < end:
while now() < end:
self.module.debug("We are going to wait for the resource to finish its transition")

state = self.fetch_state(resource)
Expand Down
9 changes: 6 additions & 3 deletions plugins/modules/cobbler_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,16 @@
# Default return values
'''

import datetime
import ssl

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six.moves import xmlrpc_client
from ansible.module_utils.common.text.converters import to_text

from ansible_collections.community.general.plugins.module_utils.datetime import (
now,
)


def main():
module = AnsibleModule(
Expand Down Expand Up @@ -110,7 +113,7 @@ def main():
changed=True,
)

start = datetime.datetime.utcnow()
start = now()

ssl_context = None
if not validate_certs:
Expand Down Expand Up @@ -142,7 +145,7 @@ def main():
except Exception as e:
module.fail_json(msg="Failed to sync Cobbler. {error}".format(error=to_text(e)))

elapsed = datetime.datetime.utcnow() - start
elapsed = now() - start
module.exit_json(elapsed=elapsed.seconds, **result)


Expand Down
9 changes: 6 additions & 3 deletions plugins/modules/cobbler_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,14 +152,17 @@
type: dict
'''

import datetime
import ssl

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import iteritems
from ansible.module_utils.six.moves import xmlrpc_client
from ansible.module_utils.common.text.converters import to_text

from ansible_collections.community.general.plugins.module_utils.datetime import (
now,
)

IFPROPS_MAPPING = dict(
bondingopts='bonding_opts',
bridgeopts='bridge_opts',
Expand Down Expand Up @@ -232,7 +235,7 @@ def main():
changed=False,
)

start = datetime.datetime.utcnow()
start = now()

ssl_context = None
if not validate_certs:
Expand Down Expand Up @@ -340,7 +343,7 @@ def main():
if module._diff:
result['diff'] = dict(before=system, after=result['system'])

elapsed = datetime.datetime.utcnow() - start
elapsed = now() - start
module.exit_json(elapsed=elapsed.seconds, **result)


Expand Down
10 changes: 7 additions & 3 deletions plugins/modules/github_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,17 @@
pubkey: "{{ lookup('ansible.builtin.file', '/home/foo/.ssh/id_rsa.pub') }}"
'''

import datetime
import json
import re

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url

from ansible_collections.community.general.plugins.module_utils.datetime import (
now,
)


API_BASE = 'https://api.github.com'

Expand Down Expand Up @@ -151,14 +156,13 @@ def get_all_keys(session):

def create_key(session, name, pubkey, check_mode):
if check_mode:
from datetime import datetime
now = datetime.utcnow()
now_t = now()
return {
'id': 0,
'key': pubkey,
'title': name,
'url': 'http://example.com/CHECK_MODE_GITHUB_KEY',
'created_at': datetime.strftime(now, '%Y-%m-%dT%H:%M:%SZ'),
'created_at': datetime.strftime(now_t, '%Y-%m-%dT%H:%M:%SZ'),
'read_only': False,
'verified': False
}
Expand Down
Loading

0 comments on commit 7e1a5d5

Please sign in to comment.