summaryrefslogtreecommitdiffstats
path: root/python.d/haproxy.chart.py
blob: a9ee666500f3317b8c02f684996aa5e6b6ae3d73 (plain)
1
2
3
4
5
6
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# -*- coding: utf-8 -*-
# Description: haproxy netdata python.d module
# Author: l2isbad

from collections import defaultdict
from re import compile as re_compile

try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

from base import UrlService, SocketService

# default module values (can be overridden per job in `config`)
# update_every = 2
priority = 60000
retries = 60

# charts order (can be overridden if you want less charts, or different order)
ORDER = ['fbin', 'fbout', 'fscur', 'fqcur', 'bbin', 'bbout', 'bscur', 'bqcur',
         'health_sdown', 'health_bdown', 'health_idle']
CHARTS = {
    'fbin': {
        'options': [None, "Kilobytes In", "KB/s", 'frontend', 'haproxy_f.bin', 'line'],
        'lines': [
        ]},
    'fbout': {
        'options': [None, "Kilobytes Out", "KB/s", 'frontend', 'haproxy_f.bout', 'line'],
        'lines': [
        ]},
    'fscur': {
        'options': [None, "Sessions Active", "sessions", 'frontend', 'haproxy_f.scur', 'line'],
        'lines': [
        ]},
    'fqcur': {
        'options': [None, "Session In Queue", "sessions", 'frontend', 'haproxy_f.qcur', 'line'],
        'lines': [
        ]},
    'bbin': {
        'options': [None, "Kilobytes In", "KB/s", 'backend', 'haproxy_b.bin', 'line'],
        'lines': [
        ]},
    'bbout': {
        'options': [None, "Kilobytes Out", "KB/s", 'backend', 'haproxy_b.bout', 'line'],
        'lines': [
        ]},
    'bscur': {
        'options': [None, "Sessions Active", "sessions", 'backend', 'haproxy_b.scur', 'line'],
        'lines': [
        ]},
    'bqcur': {
        'options': [None, "Sessions In Queue", "sessions", 'backend', 'haproxy_b.qcur', 'line'],
        'lines': [
        ]},
    'health_sdown': {
        'options': [None, "Backend Servers In DOWN State", "failed servers", 'health',
                    'haproxy_hs.down', 'line'],
        'lines': [
        ]},
    'health_bdown': {
        'options': [None, "Is Backend Alive? 1 = DOWN", "failed backend", 'health', 'haproxy_hb.down', 'line'],
        'lines': [
        ]},
    'health_idle': {
        'options': [None, "The Ratio Of Polling Time Vs Total Time", "percent", 'health', 'haproxy.idle', 'line'],
        'lines': [
            ['idle', None, 'absolute']
        ]}
}

METRICS = {'bin': {'algorithm': 'incremental', 'divisor': 1024},
           'bout': {'algorithm': 'incremental', 'divisor': 1024},
           'scur': {'algorithm': 'absolute', 'divisor': 1},
           'qcur': {'algorithm': 'absolute', 'divisor': 1}}

REGEX = dict(url=re_compile(r'idle = (?P<idle>[0-9]+)'),
             socket=re_compile(r'Idle_pct: (?P<idle>[0-9]+)'))


class Service(UrlService, SocketService):
    def __init__(self, configuration=None, name=None):
        if 'socket' in configuration:
            SocketService.__init__(self, configuration=configuration, name=name)
            self.poll = SocketService
            self.options_ = dict(regex=REGEX['socket'],
                                 stat='show stat\n'.encode(),
                                 info='show info\n'.encode())
        else:
            UrlService.__init__(self, configuration=configuration, name=name)
            self.poll = UrlService
            self.options_ = dict(regex=REGEX['url'],
                                 stat=self.url,
                                 info=url_remove_params(self.url))
        self.order = ORDER
        self.definitions = CHARTS

    def check(self):
        if self.poll.check(self):
            self.create_charts()
            self.info('We are using %s.' % self.poll.__name__)
            return True
        return False

    def _get_data(self):
        to_netdata = dict()
        self.request, self.url = self.options_['stat'], self.options_['stat']
        stat_data = self._get_stat_data()
        self.request, self.url = self.options_['info'], self.options_['info']
        info_data = self._get_info_data(regex=self.options_['regex'])

        to_netdata.update(stat_data)
        to_netdata.update(info_data)
        return to_netdata or None

    def _get_stat_data(self):
        """
        :return: dict
        """
        raw_data = self.poll._get_raw_data(self)

        if not raw_data:
            return dict()

        raw_data = raw_data.splitlines()
        self.data = parse_data_([dict(zip(raw_data[0].split(','), raw_data[_].split(',')))
                                 for _ in range(1, len(raw_data))])
        if not self.data:
            return dict()

        stat_data = dict()

        for frontend in self.data['frontend']:
            for metric in METRICS:
                idx = frontend['# pxname'].replace('.', '_')
                stat_data['_'.join(['frontend', metric, idx])] = frontend.get(metric) or 0

        for backend in self.data['backend']:
            name, idx = backend['# pxname'], backend['# pxname'].replace('.', '_')
            stat_data['hsdown_' + idx] = len([server for server in self.data['servers']
                                              if server_down(server, name)])
            stat_data['hbdown_' + idx] = 1 if backend.get('status') == 'DOWN' else 0
            for metric in METRICS:
                stat_data['_'.join(['backend', metric, idx])] = backend.get(metric) or 0
        return stat_data

    def _get_info_data(self, regex):
        """
        :return: dict
        """
        raw_data = self.poll._get_raw_data(self)
        if not raw_data:
            return dict()

        match = regex.search(raw_data)
        return match.groupdict() if match else dict()

    @staticmethod
    def _check_raw_data(data):
        """
        Check if all data has been gathered from socket
        :param data: str
        :return: boolean
        """
        return not bool(data)

    def create_charts(self):
        for front in self.data['frontend']:
            name, idx = front['# pxname'], front['# pxname'].replace('.', '_')
            for metric in METRICS:
                self.definitions['f' + metric]['lines'].append(['_'.join(['frontend', metric, idx]),
                                                                name, METRICS[metric]['algorithm'], 1,
                                                                METRICS[metric]['divisor']])
        for back in self.data['backend']:
            name, idx = back['# pxname'], back['# pxname'].replace('.', '_')
            for metric in METRICS:
                self.definitions['b' + metric]['lines'].append(['_'.join(['backend', metric, idx]),
                                                                name, METRICS[metric]['algorithm'], 1,
                                                                METRICS[metric]['divisor']])
            self.definitions['health_sdown']['lines'].append(['hsdown_' + idx, name, 'absolute'])
            self.definitions['health_bdown']['lines'].append(['hbdown_' + idx, name, 'absolute'])


def parse_data_(data):
    def is_backend(backend):
        return backend.get('svname') == 'BACKEND' and backend.get('# pxname') != 'stats'

    def is_frontend(frontend):
        return frontend.get('svname') == 'FRONTEND' and frontend.get('# pxname') != 'stats'

    def is_server(server):
        return not server.get('svname', '').startswith(('FRONTEND', 'BACKEND'))

    if not data:
        return None

    result = defaultdict(list)
    for elem in data:
        if is_backend(elem):
            result['backend'].append(elem)
            continue
        elif is_frontend(elem):
            result['frontend'].append(elem)
            continue
        elif is_server(elem):
            result['servers'].append(elem)

    return result or None


def server_down(server, backend_name):
    return server.get('# pxname') == backend_name and server.get('status') == 'DOWN'


def url_remove_params(url):
    parsed = urlparse(url or str())
    return '{scheme}://{netloc}{path}'.format(scheme=parsed.scheme, netloc=parsed.netloc, path=parsed.path)