Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing zabbix timezone code #304

Merged
merged 2 commits into from
Jun 29, 2021
Merged

Conversation

JeffAshton
Copy link
Contributor

@JeffAshton JeffAshton commented Jun 28, 2021

@nsano-rururu, the test case test_zabbix_basic fails if the current timezone is not UTC.

=================================== FAILURES ===================================
______________________________ test_zabbix_basic _______________________________

caplog = <_pytest.logging.LogCaptureFixture object at 0x7fabd89de190>

    def test_zabbix_basic(caplog):
        caplog.set_level(logging.WARNING)
        rule = {
            'name': 'Basic Zabbix test',
            'type': 'any',
            'alert_text_type': 'alert_text_only',
            'alert': [],
            'alert_subject': 'Test Zabbix',
            'zbx_host': 'example.com',
            'zbx_key': 'example-key'
        }
        rules_loader = FileRulesLoader({})
        rules_loader.load_modules(rule)
        alert = ZabbixAlerter(rule)
        match = {
            '@timestamp': '2021-01-01T00:00:00Z',
            'somefield': 'foobarbaz'
        }
        with mock.patch('pyzabbix.ZabbixSender.send') as mock_zbx_send:
            alert.alert([match])
    
            zabbix_metrics = {
                "host": "example.com",
                "key": "example-key",
                "value": "1",
                "clock": 1609459200
            }
            alerter_args = mock_zbx_send.call_args.args
>           assert vars(alerter_args[0][0]) == zabbix_metrics
E           AssertionError: assert {'clock': 160... 'value': '1'} == {'clock': 160... 'value': '1'}
E             Omitting 3 identical items, use -vv to show
E             Differing items:
E             {'clock': 1609477200} != {'clock': 1609459200}
E             Use -v to get the full diff

tests/alerters/zabbix_test.py:39: AssertionError
------------------------------ Captured log call -------------------------------
WARNING  elastalert:zabbix.py:84 Missing zabbix host 'example.com' or host's item 'example-key', alert will be discarded
------------- generated xml file: /tmp/tmp-135248PYktsmhWQN7b.xml --------------
=========================== short test summary info ============================
FAILED tests/alerters/zabbix_test.py::test_zabbix_basic - AssertionError: ass...
========================= 1 failed, 6 passed in 0.57s ==========================

@@ -57,7 +57,7 @@ def __init__(self, *args):
self.zbx_key = self.rule.get('zbx_key', None)
self.timestamp_field = self.rule.get('timestamp_field', '@timestamp')
self.timestamp_type = self.rule.get('timestamp_type', 'iso')
self.timestamp_strptime = self.rule.get('timestamp_strptime', '%Y-%m-%dT%H:%M:%S.%fZ')
self.timestamp_strptime = self.rule.get('timestamp_strptime', '%Y-%m-%dT%H:%M:%S.%f%z')
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using just Z parses the timezone incorrectly.

@@ -72,10 +72,10 @@ def alert(self, matches):
else:
try:
ts_epoch = int(datetime.strptime(match[self.timestamp_field], self.timestamp_strptime)
.strftime('%s'))
.timestamp())
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returns the unix epoch as a float instead of a string.

@jertel jertel requested a review from nsano-rururu June 28, 2021 21:14
@jertel
Copy link
Owner

jertel commented Jun 28, 2021

@nsano-rururu Will you please review this? My primary concern is whether the parse using %z will cause any problem if some ES clusters use a timestamp format of ...Z and others use ...+05:00. The docs for %z state it expects the latter.

@JeffAshton
Copy link
Contributor Author

JeffAshton commented Jun 28, 2021

@nsano-rururu Will you please review this? My primary concern is whether the parse using %z will cause any problem if some ES clusters use a timestamp format of ...Z and others use ...+05:00. The docs for %z state it expects the latter.

@nsano-rururu Will you please review this? My primary concern is whether the parse using %z will cause any problem if some ES clusters use a timestamp format of ...Z and others use ...+05:00. The docs for %z state it expects the latter.

Z is just a short form for +00:00. With %z it will actually match the timezone properly, but as currently written it doesn't process the timezone correctly:

>>> datetime.strptime('2021-06-28T21:27:00Z', '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2021, 6, 28, 21, 27, tzinfo=datetime.timezone.utc)

vs

>>> datetime.strptime('2021-06-28T21:27:00Z', '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2021, 6, 28, 21, 27)

@nsano-rururu
Copy link
Collaborator

I get a lot of my names for some reason, but I'm not sure because zabbix_basic wasn't made by me.
zabbix_basic was made by @ferozsalam

@JeffAshton
Copy link
Contributor Author

I get a lot of my names for some reason, but I'm not sure because zabbix_basic wasn't made by me.
zabbix_basic was made by @ferozsalam

My bad. This demonstrates %z in action:

UTC: Z

>>> datetime.strptime('2021-06-28T21:27:00Z', '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2021, 6, 28, 21, 27, tzinfo=datetime.timezone.utc)

UTC: +00:00

>>> datetime.strptime('2021-06-28T21:27:00+00:00', '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2021, 6, 28, 21, 27, tzinfo=datetime.timezone.utc)

EST

>>> datetime.strptime('2021-06-28T21:27:00+05:00', '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2021, 6, 28, 21, 27, tzinfo=datetime.timezone(datetime.timedelta(seconds=18000)))

Doing just Z, it's treated just as a character, but not as a timezone.

@jertel jertel merged commit f1a5666 into jertel:master Jun 29, 2021
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 22, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants