Nginx   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 6
c 2
b 0
f 1
dl 0
loc 61
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B poll() 0 29 5
A __init__() 0 18 1
1
# -*- coding: utf-8 -*-
2
"""Nginx reader plugin for stub status url."""
3
4
import sys
5
from collections import deque
6
7
PY3 = sys.version_info > (3,)
8
if PY3:
9
    import urllib.request as urllib
10
else:
11
    import urllib2 as urllib
0 ignored issues
show
Configuration introduced by
The import urllib2 could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
12
13
import plumd
14
15
__author__ = 'Kenny Freeman'
16
__email__ = '[email protected]'
17
__license__ = "ISCL"
18
__docformat__ = 'reStructuredText'
19
20
21
class Nginx(plumd.Reader):
22
    """Plugin to record nginx stub_status metrics."""
23
24
    # default config values
25
    defaults = {
26
        'poll.interval': 10,
27
        'url': "/status",    # url nginx stub_status is configured for
28
        'proto': 'http',     # http/https
29
        'host': '127.0.0.1',  # Nginx server hostname/ip
30
        'port': 80,          # Nginx server port
31
        'timeout': 10
32
    }
33
34
    def __init__(self, log, config):
35
        """Plugin to record nginx stub_status metrics.
36
37
        :param log: A logger
38
        :type log: logging.RootLogger
39
        :param config: a plumd.config.Conf configuration helper instance.
40
        :type config: plumd.config.Conf
41
        """
42
        super(Nginx, self).__init__(log, config)
43
        self.config.defaults(Nginx.defaults)
44
45
        # Nginx connection
46
        proto = self.config.get('proto')
47
        host = self.config.get('host')
48
        port = self.config.get('port')
49
        url = self.config.get('url')
50
        self.url = "{0}://{1}:{2}{3}".format(proto, host, port, url)
51
        self.timeout = config.get('timeout')
52
53
    def poll(self):
54
        """Query Nginx for metrics.
55
56
        :rtype: ResultSet
57
        """
58
        result = plumd.Result("nginx")
59
        name = self.name
60
        try:
61
            ret = urllib.urlopen(self.url, timeout=self.timeout).read()
62
            if PY3:
63
                dat = deque(ret.decode('utf8').split("\n"))
64
            else:
65
                dat = deque(ret.split("\n"))
66
            ncons = dat.popleft().split()[-1]
67
            dat.popleft()
68
            hnames = ["accepts", "handled", "requests"]
69
            hmetrics = dict(zip(hnames, dat.popleft().split()))
70
            rwnames = ["reading", "writing", "waiting"]
71
            rwmetrics = dict(zip(rwnames, dat.popleft().split()[1::2]))
72
            mfmt = "{0}.{1}"
73
            result.add(plumd.Int(mfmt.format(name, "connections"), ncons))
74
            for key, val in hmetrics.items():
75
                result.add(plumd.Int(mfmt.format(name, key), val))
76
            for key, val in rwmetrics.items():
77
                result.add(plumd.Int(mfmt.format(name, key), val))
78
        except Exception as exc:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
79
            msg = "Nginx: check failed: {0} : {1}".format(self.url, exc)
80
            self.log.error(msg)
81
        return plumd.ResultSet([result])
82