calvin.py 4.94 KB
Newer Older
Nagy Gergő committed
1 2
import requests

Nagy Gergő committed
3 4 5

class GraphiteHandler:

Nagy Gergő committed
6
    def __init__(self, server_name="localhost", server_port="8080"):
Nagy Gergő committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
        self.__server_name = server_name
        self.__server_port = server_port
        self.__queries = []
        self.__responses = []

    def put(self, query):
        self.__queries.append(query)

    def cleanUpQueries(self):
        self.__queries = []

    def cleanUpResponses(self):
        self.__responses = []

    def isEmpty(self):
        return len(self.__queries) is 0

    def generateAll(self):
        """
        Regenerate the queries before sending.
        """
        for query in self.__queries:
            query.generate()

    def send(self):
        """
        Generates the corrent query for the Graphite webAPI and flush all the
        queries in the fifo.
        Important: After sending queries to the server the fifo will lost its
        content.
        """
Nagy Gergő committed
38 39
        url_base = "http://%s:%s/render?" % (self.__server_name,
                                             self.__server_port)
Nagy Gergő committed
40 41 42
        for query in self.__queries:
            response = requests.get(url_base + query.getGenerated())
            if query.getFormat() is "json":
Nagy Gergő committed
43
                self.__responses.append(response.json())  # DICT
Nagy Gergő committed
44 45 46 47 48 49 50 51 52
            else:
                self.__responses.append(response)
        self.cleanUpQueries()

    def pop(self):
        """
        Pop the first query has got from the server.
        """
        try:
Nagy Gergő committed
53
            return self.__responses.pop(0)  # Transform to dictionary
Nagy Gergő committed
54 55 56
        except:
            print("There is no more responses.")

Nagy Gergő committed
57

Nagy Gergő committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
class Query:

    def __init__(self):
        """
        Query initializaion:
            default format is json dictionary
            keys: ("target <string>","datapoints <list>")
        """
        self.__target = ""
        self.__metric = ""
        self.__start = ""
        self.__end = ""
        self.__function = ""
        self.__response_format = "json"
        self.__generated = ""

    def setTarget(self, target):
        """
        Hostname of the target we should get the information from.
        After the hostname you should use the domain the target is in.
        Example: "foo.foodomain.domain.com.DOMAIN" where DOMAIN is
        the root of the graphite server.
        """
        self.__target = '.'.join(target.split('.')[::-1])

    def getTarget(self):
        return self.__target

    def setMetric(self, metric):
        self.__metric = metric

    def getMetric(self):
        return self.__metric

    def setAbsoluteStart(self, year, month, day, hour, minute):
        """
        Function for setting the time you want to get the reports from.
        """
Nagy Gergő committed
96
        if(len(year) > 4 or len(year) < 2):
Nagy Gergő committed
97 98 99 100 101 102 103
            raise
        self.__start = hour + ":" + minute + "_" + year + month + day

    def setRelativeStart(self, value, scale):
        """
        Function for setting the time you want to get the reports from.
        """
Nagy Gergő committed
104 105
        if (scale not in ["years",
                          "months", "days", "hours", "minutes", "seconds"]):
Nagy Gergő committed
106 107 108 109 110 111 112 113 114 115
            raise
        self.__start = "-" + str(value) + scale

    def getStart(self):
        return self.__start

    def setAbsoluteEnd(self, year, month, day, hour, minute):
        """
        Function for setting the time until you want to get the reports from.
        """
Nagy Gergő committed
116
        if(len(year) > 4 or len(year) < 2):
Nagy Gergő committed
117 118 119 120 121 122 123
            raise
        self.__end = hour + ":" + minute + "_" + year + month + day

    def setRelativeEnd(self, value, scale):
        """
        Function for setting the time until you want to get the reports from.
        """
Nagy Gergő committed
124 125
        if (scale not in ["years",
                          "months", "days", "hours", "minutes", "seconds"]):
Nagy Gergő committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
            raise
        self.__end = "-" + str(value) + scale

    def getEnd(self):
        return self.__end

    def setFormat(self, fmat):
        """
        Function for setting the format of the response from the server.
        Valid values: ["csv", "raw", "json"]
        """
        valid_formats = ["csv", "raw", "json"]
        if fmat not in valid_formats:
            raise
        self.__response_format = fmat

    def getFormat(self):
        return self.__response_format

    def generate(self):
        """
        You must always call this function before sending the metric to the
        server for it generates the valid format that the graphite API can
        parse.
        """
        tmp = "target=" + self.__target + "." + self.__metric
        if len(self.__start) is not 0:
            tmp = tmp + "&from=" + self.__start
        if len(self.__end) is not 0:
            tmp = tmp + "&until=" + self.__end
        tmp = tmp + "&format=" + self.__response_format
        self.__generated = tmp
        return self.__generated

    def getGenerated(self):
        """
        Returns the generated query string.
        Throws exception if it haven't been done yet.
        """
        if len(self.__generated) is 0:
            raise
        return self.__generated