Completed
Branch master (2f3d56)
by Kenny
01:12
created

Conntrack.check()   A

Complexity

Conditions 2

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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