cloudflare-hit-rate.py 1.83 KB
Newer Older
syed-awais-ali committed
1 2 3 4 5
"""
CloudFlare API
https://api.cloudflare.com/#zone-analytics-dashboard

"""
6 7
import requests
import argparse
syed-awais-ali committed
8
import sys
9 10 11 12

CLOUDFLARE_API_ENDPOINT = "https://api.cloudflare.com/client/v4/"


syed-awais-ali committed
13
def calcualte_cache_hit_rate(zone_id, auth_key, email, threshold):
14 15 16
    HEADERS = {"Accept": "application/json",
               "X-Auth-Key": auth_key,
               "X-Auth-Email": email}
syed-awais-ali committed
17
    # for the past one hour, -59 indicates minutes, we can go
syed-awais-ali committed
18 19
    # beyond that as well, for example for last 15
    # hours it will be -899
syed-awais-ali committed
20
    PARAMS = {"since": "-59", "continuous": "true"}
21
    res = requests.get(CLOUDFLARE_API_ENDPOINT + "zones/" + zone_id
syed-awais-ali committed
22 23 24 25 26 27 28 29 30 31 32
                       + "/analytics/dashboard", headers=HEADERS,
                       params=PARAMS)
    try:
        data = res.json()
        all_req = float(data["result"]["timeseries"][0]["requests"]["all"])
        cached_req = float(data["result"]["timeseries"][0]["requests"]["cached"])
        current_cache_hit_rate = cached_req / all_req * 100
        if current_cache_hit_rate < threshold:
            sys.exit(1)

    except Exception as error:
syed-awais-ali committed
33
        print("JSON Error: {} \n Content returned from API call: {}".format(error, res.text))
syed-awais-ali committed
34 35


36 37 38 39 40 41 42 43 44 45


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-z', '--zone', required=True,
                        help="Cloudflare's Zone ID")
    parser.add_argument('-k', '--auth_key', required=True,
                        help="Authentication Key")
    parser.add_argument('-e', '--email', required=True,
                        help="email to use for authentication for CloudFlare API")
syed-awais-ali committed
46 47
    parser.add_argument('-t', '--threshold', required=True,
                        help="Threshold limit to be passed to check against it")
48 49
    args = parser.parse_args()

syed-awais-ali committed
50
    calcualte_cache_hit_rate(args.zone, args.auth_key, args.email, args.threshold)