#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ Simulates httping for `argos `""" # httping # v1.0 # Tobias Schmidl # schtobia # Short description of what your plugin does. # # python,requests # https://github.com/schtobia/argos-httping/blob/master/httping.py import datetime # for the whole ms → s and vice versa stuff import statistics # for median and stdev import sys # for redirecting print to stderr import requests # for the central HTTP HEAD request __author__ = "Tobias Schmidl" __copyright__ = "Copyright 2018, Tobias Schmidl" __license__ = "MIT" __version__ = "0.0.1" __maintainer__ = "Tobias Schmidl" max_ping = datetime.timedelta(milliseconds=1000) # in seconds targets = ["https://www.google.de", "https://www.bing.com", "https://www.wikipedia.org"] max_ping_in_ms = max_ping.total_seconds() * 1000 in_bin = lambda x, bin: x >= bin[0] and x <= bin[1] class Themes: # Themes are from http://colorbrewer2.org/ purple_green = ["#762a83", "#9970ab", "#c2a5cf", "#a6dba0", "#5aae61", "#1b7837"] red_green = ["#d73027", "#fc8d59", "#fee08b", "#d9ef8b", "#91cf60", "#1a9850"] original = ["#acacac", "#ff0101", "#cc673b", "#ce8458", "#6bbb15", "#0ed812"] selected_colors = red_green generate_bins = lambda min_val, max_val, step_width=2: [[x, x + step_width - 1] for x in range( min_val, max_val, step_width)] bins = generate_bins(0, int(max_ping_in_ms), int(max_ping_in_ms / (len(selected_colors) - 1))) def colorize(response_time): for index, bin in enumerate(Themes.bins): if in_bin(response_time, bin): return Themes.selected_colors[len(Themes.selected_colors) - 1 - index] return Themes.selected_colors[0] def httping(targets): responses = {} for target in targets: try: responses[target] = requests.head(target, timeout=max_ping.total_seconds()).elapsed.total_seconds() * 1000 except requests.exceptions.RequestException as ex: print(str(ex), file=sys.stderr) responses[target] = None response_times = [value for key, value in responses.items() if isinstance(value, float)] if len(response_times) > 1: return responses, statistics.median(response_times), statistics.stdev(response_times) elif len(response_times) > 0: return responses, response_times[0], 0 else: return responses, None, None if __name__ == "__main__": response_times, median, stddev = httping(targets) if isinstance(median, float) and median != max_ping_in_ms: print("⦿ " + str(round(median, 2)) + "±" + str(round(stddev, 2)) + " | color=" + Themes.colorize(median)) else: print("☠ | color=" + Themes.selected_colors[0]) print("---") for target, response_time in response_times.items(): if isinstance(response_time, float): print(target + ": " + str(round(response_time, 2)) + " | color=" + Themes.colorize(response_time)) else: print(target + ": ☠ | color=" + Themes.selected_colors[0])