Last active
December 22, 2015 09:38
-
-
Save skyjur/6453001 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| """ | |
| Monitor downtime of url: | |
| >>> python monitor_downtime.py http://www.google.com | |
| 200 | |
| 200 | |
| 200 | |
| 200 | |
| 200 | |
| <Crl+C>Total time monitored: 3.0 sec | |
| Total downtime: 0.0 sec | |
| """ | |
| from functools import partial | |
| import time | |
| import argparse | |
| import requests | |
| args_parser = argparse.ArgumentParser(description='Monitor url uptime') | |
| args_parser.add_argument('url', help='Url to monitor') | |
| args_parser.add_argument('--timeout', type=float, default=1.0, | |
| help='Seconds to wait between requests') | |
| args_parser.add_argument('--sleep-time', type=float, default=1.0, | |
| help='Seconds to wait between requests') | |
| args_parser.add_argument('--http-user', help='Http auth user') | |
| args_parser.add_argument('--http-password', help='Http auth password') | |
| def construct_request_func(url, http_user=None, http_password=None, timeout=1.0): | |
| kw = {} | |
| if http_user: | |
| kw['auth'] = (http_user, http_password) | |
| return partial(requests.get, url, **kw) | |
| def monitor(request_func, sleep_time=1.0): | |
| start = time.time() | |
| log = [] | |
| try: | |
| while True: | |
| try: | |
| response = request_func() | |
| code = response.status_code | |
| err = None | |
| except requests.RequestException as e: | |
| code = None | |
| err = e | |
| if code: | |
| print code | |
| else: | |
| print err | |
| log.append((time.time(), code == 200)) | |
| time.sleep(sleep_time) | |
| except KeyboardInterrupt: | |
| pass | |
| downtime = 0.0 | |
| prev_clock = start | |
| for clock, success in log: | |
| if not success: | |
| downtime += clock - prev_clock | |
| prev_clock = clock | |
| print 'Total time monitored: %.2f seconds' % (log[-1][0] - start) | |
| print 'Total downtime: %.2f seconds' % downtime | |
| def main(): | |
| opts = args_parser.parse_args() | |
| request_func = construct_request_func(opts.url, opts.http_user, | |
| opts.http_password, opts.timeout) | |
| monitor(request_func, opts.sleep_time) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment