Ticket #28271: tor-check-onionperf

File tor-check-onionperf, 4.2 KB (added by irl, 9 months ago)
Line 
1#!/usr/bin/python3
2#
3# Copyright 2014,2018 The Tor Project
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9# * Redistributions of source code must retain the above copyright
10#   notice, this list of conditions and the following disclaimer.
11#
12# * Redistributions in binary form must reproduce the above
13#   copyright notice, this list of conditions and the following disclaimer
14#   in the documentation and/or other materials provided with the
15#   distribution.
16#
17# * Neither the names of the copyright owners nor the names of its
18#   contributors may be used to endorse or promote products derived from
19#   this software without specific prior written permission.
20#
21# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32"""Nagios plugin to check that the Onionperf service has run its analyze task
33at the last midnight."""
34
35import sys
36import datetime
37import urllib.error
38from urllib.request import urlopen
39from xml.dom.minidom import parse
40
41# Standard Nagios return codes
42OK, WARNING, CRITICAL, UNKNOWN = range(4)
43
44# Test URL to download and verify
45INDEX_URL = '/index.xml'
46
47# ISO datetime pattern
48ISO_DATE = "%Y-%m-%d"
49
50# Analysis result filename format
51RESULT_FILENAME_FORMAT = "%s.onionperf.analysis.json.xz"
52
53# Time in hours to wait for the analyze task to run
54WARNING_IF_MISSED = 1
55CRITICAL_IF_MISSED = 2
56
57
58def test_onionperf():
59    """Fetch minimal summary document and checks that it's recent."""
60
61    # Build URL
62    url = ("https://" + host + INDEX_URL)
63
64    # Determine latest file that should be present
65    yesterday_date = (datetime.datetime.utcnow() - datetime.timedelta(days=1))
66    yesterday = yesterday_date.strftime(ISO_DATE)
67    latest_filename = RESULT_FILENAME_FORMAT % (yesterday,)
68
69    # Fetch document from Onionoo service.
70    try:
71        response = urlopen(url)
72    except urllib.error.URLError as error:
73        return CRITICAL, "Error fetching index file: %s" % \
74                         (error.reason, )
75
76    # Parse XML-formatted response.
77    try:
78        response_xml = parse(response)
79    except ValueError as error:
80        return CRITICAL, "Error parsing XML format: %s %s" % \
81                         (error, response_str[:40], )
82
83    # Check for latest result file
84    for f in response_xml.getElementsByTagName('file'):
85        if f.getAttribute("name") == latest_filename:
86            return OK, "Analysis result found for %s" % (yesterday,)
87
88    # We didn't find the file
89    hour = datetime.datetime.utcnow().hour
90    message = "Analysis result not found for %s" % (yesterday,)
91    if hour < WARNING_IF_MISSED:
92        return OK, message + " (grace period)"
93    elif hour < CRITICAL_IF_MISSED:
94        return WARNING, message
95    else:
96        return CRITICAL, message
97
98
99if __name__ == "__main__":
100    status, message = None, None
101
102    if len(sys.argv) == 2:
103        host = sys.argv[1]
104    else:
105        print("usage: tor-check-onionperf {hostname}")
106        sys.exit(CRITICAL)
107
108    try:
109        status, message = test_onionperf()
110    except KeyboardInterrupt:
111        status, message = CRITICAL, "Caught Control-C..."
112    except Exception as e:
113        status = CRITICAL
114        message = repr(e)
115    finally:
116        if status == OK:
117            print("OK: %s" % message)
118        elif status == WARNING:
119            print("WARNING: %s" % message)
120        elif status == CRITICAL:
121            print("CRITICAL: %s" % message)
122        else:
123            print("UNKNOWN: %s" % message)
124            status = UNKNOWN
125
126        sys.exit(status)