Conntrack.poll()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
1
# -*- coding: utf-8 -*-
2
"""Conntrack metrics reader for /proc on Linux."""
3
import os.path
4
5
import plumd
6
from plumd.util import get_file
7
8
__author__ = 'Kenny Freeman'
9
__email__ = '[email protected]'
10
__license__ = "ISCL"
11
__docformat__ = 'reStructuredText'
12
13
14
class Conntrack(plumd.Reader):
15
    """Plugin to measure conntrack metrics from /proc."""
16
17
    defaults = {
18
        'poll.interval': 10,
19
        'proc_path': '/proc',
20
        'conntrack_paths': [("{0}/sys/net/netfilter/nf_conntrack_count",
21
                             "{0}/sys/net/nf_conntrack_max"),
22
                            ("{0}/sys/net/ipv4/netfilter/ip_conntrack_count",
23
                             "{0}/sys/net/ipv4/netfilter/ip_conntrack_max")]
24
    }
25
26
    def __init__(self, log, config):
27
        """Plugin to measure various kernel metrics from /proc.
28
29
        :param log: A logger
30
        :type log: logging.RootLogger
31
        :param config: a plumd.config.Conf configuration helper instance.
32
        :type config: plumd.config.Conf
33
        """
34
        super(Conntrack, self).__init__(log, config)
35
        config.defaults(Conntrack.defaults)
36
        proc_path = config.get('proc_path')
37
        for fcount, fmax in config.get('conntrack_paths'):
38
            self.fname_cnt = fcount.format(proc_path)
39
            self.fname_max = fmax.format(proc_path)
40
            if os.path.isfile(self.fname_cnt) and os.path.isfile(self.fname_max):
41
                break
42
            msg = "Conntrack: invalid path: {0}"
43
            self.log.warn(msg.format(self.fname_cnt))
44
            self.log.warn(msg.format(self.fname_max))
45
        self.enabled = True
46
        if not os.path.isfile(self.fname_cnt) or not os.path.isfile(self.fname_max):
47
            self.enabled = False
48
            msg = "Conntrack: no paths found, disabling (iptables running?)."
49
            self.log.error(msg)
50
51
    def poll(self):
52
        """Poll for kernel metrics under /proc.
53
54
        :rtype: ResultSet
55
        """
56
        return plumd.ResultSet(self.check())
57
58
    def check(self):
59
        """Return current conntrack count and max.
60
61
        :rtype: plumd.Result
62
        """
63
        result = plumd.Result("conntrack")
64
        if not self.enabled:
65
            return [result]
66
        curr_val = 0
67
        max_val = 0
68
        # read and process /proc/stat
69
        curr_val = get_file(self.fname_cnt)
70
        max_val = get_file(self.fname_max)
71
        result.add(plumd.Int("cur", curr_val))
72
        result.add(plumd.Int("max", max_val))
73
        return [result]
74