calvin.py 5.12 KB
Newer Older
Gregory Nagy committed
1 2 3 4 5 6
import requests
import os


class GraphiteHandler:

7
    def __init__(self):
8
        if os.getenv("GRAPHITE_HOST") in ['', None]:
9
            raise RuntimeError
10 11
        self.__server_name = os.getenv("GRAPHITE_HOST")
        if os.getenv("GRAPHITE_PORT") in ['', None]:
12
            raise RuntimeError
Gregory Nagy committed
13
        self.__server_port = os.getenv("GRAPHITE_PORT")
14 15 16 17 18 19
        self.__queries = []
        self.__responses = []

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

Gregory Nagy committed
20
    def clean_up_queries(self):
21 22
        self.__queries = []

Gregory Nagy committed
23
    def clean_up_responses(self):
24 25
        self.__responses = []

Gregory Nagy committed
26
    def is_empty(self):
27 28
        return len(self.__queries) is 0

Gregory Nagy committed
29
    def generate_all(self):
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
        """
        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.
        """
        url_base = "http://%s:%s/render?" % (self.__server_name,
                                             self.__server_port)
        for query in self.__queries:
Gregory Nagy committed
46
            response = requests.get(url_base + query.get_generated())
Gregory Nagy committed
47
            if query.get_format() == "json":
48 49 50
                self.__responses.append(response.json())  # DICT
            else:
                self.__responses.append(response)
Gregory Nagy committed
51
        self.clean_up_queries()
52 53 54 55 56 57 58 59 60

    def pop(self):
        """
        Pop the first query has got from the server.
        """
        try:
            return self.__responses.pop(0)  # Transform to dictionary
        except:
            raise RuntimeError
Gregory Nagy committed
61 62 63


class Query:
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

    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 = ""

Gregory Nagy committed
79
    def set_target(self, target):
80 81 82 83 84 85 86 87
        """
        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])

Gregory Nagy committed
88
    def get_target(self):
89 90
        return self.__target

Gregory Nagy committed
91
    def set_metric(self, metric):
92 93
        self.__metric = metric

Gregory Nagy committed
94
    def get_metric(self):
95 96
        return self.__metric

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

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

Gregory Nagy committed
114
    def get_start(self):
115 116
        return self.__start

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

Gregory Nagy committed
125
    def set_relative_end(self, value, scale):
126 127 128 129 130 131 132 133
        """
        Function for setting the time until you want to get the reports from.
        """
        if (scale not in ["years",
                          "months", "days", "hours", "minutes", "seconds"]):
            raise
        self.__end = "-" + str(value) + scale

Gregory Nagy committed
134
    def get_end(self):
135 136
        return self.__end

Gregory Nagy committed
137
    def set_format(self, fmat):
138 139 140 141 142 143 144 145 146
        """
        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

Gregory Nagy committed
147
    def get_format(self):
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
        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

Gregory Nagy committed
165
    def get_generated(self):
166 167 168 169 170 171 172
        """
        Returns the generated query string.
        Throws exception if it haven't been done yet.
        """
        if len(self.__generated) is 0:
            raise
        return self.__generated