Просмотр исходного кода

Added uwsgi plugin (#4404)

* Added uwsgi plugin

* Added makefile for plugin and fixed some code style issues

* Refactored generating dimensions to allow workers to be added at run-time.
The dimension name is now the PID of the worker.

exceptions, harikiris and respawns are now global and not per worker as this did not make any sense.

* Code-review related formatting changes
robbert-ef 6 лет назад
Родитель
Сommit
ad3ff17ac1

+ 1 - 0
collectors/python.d.plugin/Makefile.am

@@ -95,6 +95,7 @@ include squid/Makefile.inc
 include tomcat/Makefile.inc
 include traefik/Makefile.inc
 include unbound/Makefile.inc
+include uwsgi/Makefile.inc
 include varnish/Makefile.inc
 include w1sensor/Makefile.inc
 include web_log/Makefile.inc

+ 1 - 0
collectors/python.d.plugin/python.d.conf

@@ -90,6 +90,7 @@ nginx_log: no
 # springboot: yes
 # tomcat: yes
 unbound: no
+# uwsgi: yes
 # varnish: yes
 # web_log: yes
 # w1sensor: yes

+ 13 - 0
collectors/python.d.plugin/uwsgi/Makefile.inc

@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+# THIS IS NOT A COMPLETE Makefile
+# IT IS INCLUDED BY ITS PARENT'S Makefile.am
+# IT IS REQUIRED TO REFERENCE ALL FILES RELATIVE TO THE PARENT
+
+# install these files
+dist_python_DATA       += uwsgi/uwsgi.chart.py
+dist_pythonconfig_DATA += uwsgi/uwsgi.conf
+
+# do not install these files, but include them in the distribution
+dist_noinst_DATA       += uwsgi/README.md uwsgi/Makefile.inc
+

+ 37 - 0
collectors/python.d.plugin/uwsgi/README.md

@@ -0,0 +1,37 @@
+# uwsgi
+
+Module monitor uwsgi performance metrics.
+
+https://uwsgi-docs.readthedocs.io/en/latest/StatsServer.html
+
+lines are creates dynamically based on how many workers are there
+
+Following charts are drawn:
+
+1. **Requests**
+ * requests per second
+ * transmitted data
+ * average request time
+
+2. **Memory**
+ * rss
+ * vsz
+
+3. **Exceptions**
+4. **Harakiris**
+5. **Respawns**
+
+### configuration
+
+```yaml
+socket:
+  name     : 'local'
+  socket   : '/tmp/stats.socket'
+
+localhost:
+  name     : 'local'
+  host     : 'localhost'
+  port     : 1717
+```
+
+When no configuration file is found, module tries to connect to TCP/IP socket: `localhost:1717`.

+ 183 - 0
collectors/python.d.plugin/uwsgi/uwsgi.chart.py

@@ -0,0 +1,183 @@
+# -*- coding: utf-8 -*-
+# Description: uwsgi netdata python.d module
+# Author: Robbert Segeren (robbert-ef)
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import json
+from copy import deepcopy
+from bases.FrameworkServices.SocketService import SocketService
+
+# default module values (can be overridden per job in `config`)
+# update_every = 2
+priority = 60000
+retries = 60
+
+ORDER = [
+    'requests',
+    'tx',
+    'avg_rt',
+    'memory_rss',
+    'memory_vsz',
+    'exceptions',
+    'harakiri',
+    'respawn',
+]
+
+DYNAMIC_CHARTS = [
+    'requests',
+    'tx',
+    'avg_rt',
+    'memory_rss',
+    'memory_vsz',
+]
+
+# NOTE: lines are created dynamically in `check()` method
+CHARTS = {
+    'requests': {
+        'options': [None, 'Requests', 'requests/s', 'requests', 'uwsgi.requests', 'stacked'],
+        'lines': [
+            ['requests', 'requests', 'incremental']
+        ]
+    },
+    'tx': {
+        'options': [None, 'Transmitted data', 'KB/s', 'requests', 'uwsgi.tx', 'stacked'],
+        'lines': [
+            ['tx', 'tx', 'incremental']
+        ]
+    },
+    'avg_rt': {
+        'options': [None, 'Average request time', 'ms', 'requests', 'uwsgi.avg_rt', 'line'],
+        'lines': [
+            ['avg_rt', 'avg_rt', 'absolute']
+        ]
+    },
+    'memory_rss': {
+        'options': [None, 'RSS (Resident Set Size)', 'MB', 'memory', 'uwsgi.memory_rss', 'stacked'],
+        'lines': [
+            ['memory_rss', 'memory_rss', 'absolute', 1, 1024 * 1024]
+        ]
+    },
+    'memory_vsz': {
+        'options': [None, 'VSZ (Virtual Memory Size)', 'MB', 'memory', 'uwsgi.memory_vsz', 'stacked'],
+        'lines': [
+            ['memory_vsz', 'memory_vsz', 'absolute', 1, 1024 * 1024]
+        ]
+    },
+    'exceptions': {
+        'options': [None, 'Exceptions', 'exceptions', 'exceptions', 'uwsgi.exceptions', 'line'],
+        'lines': [
+            ['exceptions', 'exceptions', 'incremental']
+        ]
+    },
+    'harakiri': {
+        'options': [None, 'Harakiris', 'harakiris', 'harakiris', 'uwsgi.harakiris', 'line'],
+        'lines': [
+            ['harakiri_count', 'harakiris', 'incremental']
+        ]
+    },
+    'respawn': {
+        'options': [None, 'Respawns', 'respawns', 'respawns', 'uwsgi.respawns', 'line'],
+        'lines': [
+            ['respawn_count', 'respawns', 'incremental']
+        ]
+    },
+}
+
+
+class Service(SocketService):
+    def __init__(self, configuration=None, name=None):
+        super(Service, self).__init__(configuration=configuration, name=name)
+        self.url = self.configuration.get('host', 'localhost')
+        self.port = self.configuration.get('port', 1717)
+        self.order = ORDER
+        self.definitions = deepcopy(CHARTS)
+
+        # Clear dynamic dimensions, these are added during `_get_data()` to allow adding workers at run-time
+        for chart in DYNAMIC_CHARTS:
+            self.definitions[chart]['lines'] = []
+
+        self.last_result = {}
+        self.workers = []
+
+    def read_data(self):
+        """
+        Read data from socket and parse as JSON.
+        :return: (dict) stats
+        """
+        raw_data = self._get_raw_data()
+        if not raw_data:
+            return None
+        try:
+            return json.loads(raw_data)
+        except ValueError as err:
+            self.error(err)
+            return None
+
+    def check(self):
+        """
+        Parse configuration and check if we can read data.
+        :return: boolean
+        """
+        self._parse_config()
+        return bool(self.read_data())
+
+    def add_worker_dimensions(self, key):
+        """
+        Helper to add dimensions for a worker.
+        :param key: (int or str) worker identifier
+        :return:
+        """
+        for chart in DYNAMIC_CHARTS:
+            for line in CHARTS[chart]['lines']:
+                dimension_id = '{}_{}'.format(line[0], key)
+                dimension_name = str(key)
+
+                dimension = [dimension_id, dimension_name] + line[2:]
+                self.charts[chart].add_dimension(dimension)
+
+    @staticmethod
+    def _check_raw_data(data):
+        # The server will close the connection when it's done sending
+        # data, so just keep looping until that happens.
+        return False
+
+    def _get_data(self):
+        """
+        Read data from socket
+        :return: dict
+        """
+        stats = self.read_data()
+        if not stats:
+            return None
+
+        result = {
+            'exceptions': 0,
+            'harakiri_count': 0,
+            'respawn_count': 0,
+        }
+
+        for worker in stats['workers']:
+            key = worker['pid']
+
+            # Add dimensions for new workers
+            if key not in self.workers:
+                self.add_worker_dimensions(key)
+                self.workers.append(key)
+
+            result['requests_{}'.format(key)] = worker['requests']
+            result['tx_{}'.format(key)] = worker['tx']
+            result['avg_rt_{}'.format(key)] = worker['avg_rt']
+
+            # avg_rt is not reset by uwsgi, so reset here
+            if self.last_result.get('requests_{}'.format(key)) == worker['requests']:
+                result['avg_rt_{}'.format(key)] = 0
+
+            result['memory_rss_{}'.format(key)] = worker['rss']
+            result['memory_vsz_{}'.format(key)] = worker['vsz']
+
+            result['exceptions'] += worker['exceptions']
+            result['harakiri_count'] += worker['harakiri_count']
+            result['respawn_count'] += worker['respawn_count']
+
+        self.last_result = result
+        return result

+ 94 - 0
collectors/python.d.plugin/uwsgi/uwsgi.conf

@@ -0,0 +1,94 @@
+# netdata python.d.plugin configuration for uwsgi
+#
+# This file is in YaML format. Generally the format is:
+#
+# name: value
+#
+# There are 2 sections:
+#  - global variables
+#  - one or more JOBS
+#
+# JOBS allow you to collect values from multiple sources.
+# Each source will have its own set of charts.
+#
+# JOB parameters have to be indented (using spaces only, example below).
+
+# ----------------------------------------------------------------------
+# Global Variables
+# These variables set the defaults for all JOBs, however each JOB
+# may define its own, overriding the defaults.
+
+# update_every sets the default data collection frequency.
+# If unset, the python.d.plugin default is used.
+# update_every: 1
+
+# priority controls the order of charts at the netdata dashboard.
+# Lower numbers move the charts towards the top of the page.
+# If unset, the default for python.d.plugin is used.
+# priority: 60000
+
+# retries sets the number of retries to be made in case of failures.
+# If unset, the default for python.d.plugin is used.
+# Attempts to restore the service are made once every update_every
+# and only if the module has collected values in the past.
+# retries: 60
+
+# autodetection_retry sets the job re-check interval in seconds.
+# The job is not deleted if check fails.
+# Attempts to start the job are made once every autodetection_retry.
+# This feature is disabled by default.
+# autodetection_retry: 0
+
+# ----------------------------------------------------------------------
+# JOBS (data collection sources)
+#
+# The default JOBS share the same *name*. JOBS with the same name
+# are mutually exclusive. Only one of them will be allowed running at
+# any time. This allows autodetection to try several alternatives and
+# pick the one that works.
+#
+# Any number of jobs is supported.
+#
+# All python.d.plugin JOBS (for all its modules) support a set of
+# predefined parameters. These are:
+#
+# job_name:
+#     name: myname            # the JOB's name as it will appear at the
+#                             # dashboard (by default is the job_name)
+#                             # JOBs sharing a name are mutually exclusive
+#     update_every: 1         # the JOB's data collection frequency
+#     priority: 60000         # the JOB's order on the dashboard
+#     retries: 60             # the JOB's number of restoration attempts
+#     autodetection_retry: 0  # the JOB's re-check interval in seconds
+#
+# Additionally to the above, uwsgi also supports the following:
+#
+#     socket: 'path/to/uwsgistats.sock'
+#
+#  or
+#     host: 'IP or HOSTNAME' # the host to connect to
+#     port: PORT             # the port to connect to
+#
+# ----------------------------------------------------------------------
+# AUTO-DETECTION JOBS
+# only one of them will run (they have the same name)
+#
+
+socket:
+  name     : 'local'
+  socket   : '/tmp/stats.socket'
+
+localhost:
+  name     : 'local'
+  host     : 'localhost'
+  port     : 1717
+
+localipv4:
+  name     : 'local'
+  host     : '127.0.0.1'
+  port     : 1717
+
+localipv6:
+  name     : 'local'
+  host     : '::1'
+  port     : 1717