From c1b029e4fd69a08d1020385ae2fba1164dc88ec5 Mon Sep 17 00:00:00 2001
From: Jaime Arroyo <jaime.arroyo@creublanca.es>
Date: Tue, 2 Jul 2019 13:05:25 +0200
Subject: [PATCH] [12.0][MIG] nsca_client

---
 nsca_client/README.rst              | 73 +++++++++++++++++++----------
 nsca_client/__manifest__.py         |  5 +-
 nsca_client/models/nsca_check.py    | 42 ++++++++---------
 nsca_client/models/nsca_server.py   |  3 +-
 nsca_client/readme/CONFIGURE.rst    | 56 ++++++++++++++++++++++
 nsca_client/readme/CONTRIBUTORS.rst |  3 ++
 nsca_client/readme/DESCRIPTION.rst  |  4 ++
 nsca_client/readme/INSTALL.rst      |  5 ++
 nsca_client/tests/test_nsca.py      |  4 +-
 9 files changed, 145 insertions(+), 50 deletions(-)
 create mode 100644 nsca_client/readme/CONFIGURE.rst
 create mode 100644 nsca_client/readme/CONTRIBUTORS.rst
 create mode 100644 nsca_client/readme/DESCRIPTION.rst
 create mode 100644 nsca_client/readme/INSTALL.rst

diff --git a/nsca_client/README.rst b/nsca_client/README.rst
index 381db2e6a..45cdca841 100644
--- a/nsca_client/README.rst
+++ b/nsca_client/README.rst
@@ -1,16 +1,40 @@
-.. image:: https://img.shields.io/badge/licence-AGPL--3-blue.svg
-   :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
-   :alt: License: AGPL-3
-
 ===========
 NSCA Client
 ===========
 
+.. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+   !! This file is generated by oca-gen-addon-readme !!
+   !! changes will be overwritten.                   !!
+   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
+    :target: https://odoo-community.org/page/development-status
+    :alt: Beta
+.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
+    :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
+    :alt: License: AGPL-3
+.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fserver--tools-lightgray.png?logo=github
+    :target: https://github.com/OCA/server-tools/tree/12.0/nsca_client
+    :alt: OCA/server-tools
+.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
+    :target: https://translation.odoo-community.org/projects/server-tools-12-0/server-tools-12-0-nsca_client
+    :alt: Translate me on Weblate
+.. |badge5| image:: https://img.shields.io/badge/runbot-Try%20me-875A7B.png
+    :target: https://runbot.odoo-community.org/runbot/149/12.0
+    :alt: Try me on Runbot
+
+|badge1| |badge2| |badge3| |badge4| |badge5| 
+
 This is a technical module to send passive alerts to your favorite NSCA daemon
 (Nagios, Shinken...).
 This module is based on the Odoo cron system and requires a NSCA client
 installed on the system to satisfy the ``/usr/sbin/send_nsca`` command.
 
+**Table of contents**
+
+.. contents::
+   :local:
+
 Installation
 ============
 
@@ -30,12 +54,12 @@ To configure this module, you need to:
 
 * Declare your NSCA server in the menu Configuration / Technical / NSCA Client / Servers
 
-.. image:: nsca_client/static/description/server.png
+.. image:: https://raw.githubusercontent.com/OCA/server-tools/12.0/nsca_client/nsca_client/static/description/server.png
    :width: 400 px
 
 * Create NSCA checks in the menu Configuration / Technical / NSCA Client / Checks
 
-.. image:: nsca_client/static/description/check.png
+.. image:: https://raw.githubusercontent.com/OCA/server-tools/12.0/nsca_client/nsca_client/static/description/check.png
    :width: 400 px
 
 * Code the methods which will be called by the NSCA checks.
@@ -80,47 +104,44 @@ E.g:
 On the example, the performance data will use the label ``exceptions`` and the
 value will be the number of exception of mails.
 
-Usage
-=====
-
-.. image:: https://odoo-community.org/website/image/ir.attachment/5784_f2813bd/datas
-   :alt: Try me on Runbot
-   :target: https://runbot.odoo-community.org/runbot/149/11.0
-
 Bug Tracker
 ===========
 
-Bugs are tracked on `GitHub Issues
-<https://github.com/OCA/server-tools/issues>`_. In case of trouble, please
-check there if your issue has already been reported. If you spotted it first,
-help us smashing it by providing a detailed and welcomed feedback.
+Bugs are tracked on `GitHub Issues <https://github.com/OCA/server-tools/issues>`_.
+In case of trouble, please check there if your issue has already been reported.
+If you spotted it first, help us smashing it by providing a detailed and welcomed
+`feedback <https://github.com/OCA/server-tools/issues/new?body=module:%20nsca_client%0Aversion:%2012.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
 
+Do not contact contributors directly about support or help with technical issues.
 
 Credits
 =======
 
-Images
-------
+Authors
+~~~~~~~
 
-* Daniel Foré: `Icon <http://www.iconarchive.com/show/elementary-icons-by-danrabbit/Apps-system-monitor-icon.html>`_ (Elementary theme, GPL).
+* ABF OSIELL
 
 Contributors
-------------
+~~~~~~~~~~~~
 
 * Sébastien Alix <sebastien.alix@osiell.com>
 * Enric Tobella <etobella@creublanca.es>
+* Jaime Arroyo <jaime.arroyo@creublanca.es>
 
-Maintainer
-----------
+Maintainers
+~~~~~~~~~~~
+
+This module is maintained by the OCA.
 
 .. image:: https://odoo-community.org/logo.png
    :alt: Odoo Community Association
    :target: https://odoo-community.org
 
-This module is maintained by the OCA.
-
 OCA, or the Odoo Community Association, is a nonprofit organization whose
 mission is to support the collaborative development of Odoo features and
 promote its widespread use.
 
-To contribute to this module, please visit https://odoo-community.org.
+This module is part of the `OCA/server-tools <https://github.com/OCA/server-tools/tree/12.0/nsca_client>`_ project on GitHub.
+
+You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
diff --git a/nsca_client/__manifest__.py b/nsca_client/__manifest__.py
index 0aebc1cea..ca75b8697 100644
--- a/nsca_client/__manifest__.py
+++ b/nsca_client/__manifest__.py
@@ -3,13 +3,16 @@
 {
     "name": "NSCA Client",
     "summary": "Send passive alerts to monitor your Odoo application.",
-    "version": "11.0.1.0.0",
+    "version": "12.0.1.0.0",
     "category": "Tools",
     "website": "http://github.com/OCA/server-tools",
     "author": "ABF OSIELL, Odoo Community Association (OCA)",
     "license": "AGPL-3",
     "application": False,
     "installable": True,
+    "depends": [
+        'base',
+    ],
     "data": [
         "security/ir.model.access.csv",
         "views/nsca_menu.xml",
diff --git a/nsca_client/models/nsca_check.py b/nsca_client/models/nsca_check.py
index a96bb9f60..480e04f79 100644
--- a/nsca_client/models/nsca_check.py
+++ b/nsca_client/models/nsca_check.py
@@ -9,29 +9,29 @@ _logger = logging.getLogger(__name__)
 
 
 class NscaCheck(models.Model):
-    _name = "nsca.check"
-    _description = u"NSCA Check"
+    _name = 'nsca.check'
+    _description = 'NSCA Check'
     _inherits = {'ir.cron': 'cron_id'}
 
     cron_id = fields.Many2one(
-        'ir.cron', string=u"Cron",
+        'ir.cron', string='Cron',
         required=True, ondelete='cascade', readonly=True)
     server_id = fields.Many2one(
-        'nsca.server', string=u"Server", required=True)
-    service = fields.Char(u"Service", required=True)
-    nsca_model = fields.Char(u"Model")
-    nsca_function = fields.Char(u"Method")
-    nsca_args = fields.Char(u"Arguments")
+        'nsca.server', string='Server', required=True)
+    service = fields.Char('Service', required=True)
+    nsca_model = fields.Char('NSCA Model')
+    nsca_function = fields.Char('Method')
+    nsca_args = fields.Char('Arguments')
     allow_void_result = fields.Boolean(
-        u"Allow void result", default=False,
-        help=u"By default, a CRITICAL message is sent if the method does not "
-             u"return.\nIf checked, no message will be sent in such a case.")
+        'Allow void result', default=False,
+        help='By default, a CRITICAL message is sent if the method does not '
+             'return.\nIf checked, no message will be sent in such a case.')
 
     @api.model
     def default_get(self, fields_list):
-        """Set some default values on the fly, without overriding fields (which
+        '''Set some default values on the fly, without overriding fields (which
         has the side effect to re-create the fields on the current model).
-        """
+        '''
         res = super(NscaCheck, self).default_get(fields_list)
         res['name'] = 'TEMP'  # Required on 'ir.cron', replaced later
         res['interval_number'] = 10
@@ -40,19 +40,19 @@ class NscaCheck(models.Model):
 
     @api.multi
     def _force_values(self):
-        """Force some values:
+        '''Force some values:
             - Compute the name of the NSCA check to be readable
               among the others 'ir.cron' records.
-        """
+        '''
         model = self.env['ir.model'].search([('model', '=', self._name)])
         for check in self:
             vals = {
-                'name': u"%s - %s" % (_(u"NSCA Check"), check.service),
+                'name': '%s - %s' % (_('NSCA Check'), check.service),
                 'model_id': model.id,
                 'state': 'code',
                 'code': 'model._cron_check(%s,)' % check.id,
                 'doall': False,
-                'numbercall': -1
+                'numbercall': -1,
             }
             super(NscaCheck, check).write(vals)
 
@@ -78,14 +78,14 @@ class NscaCheck(models.Model):
     def _cron_check(self, check_id):
         self.env['nsca.server']._check_send_nsca_command()
         check = self.browse(check_id)
-        rc, message, performance = 3, "Unknown", {}
+        rc, message, performance = 3, 'Unknown', {}
         try:
             NscaModel = self.env[check.nsca_model]
             results = {'model': NscaModel}
             safe_eval(
                 'result = model.%s(%s)' % (
                     check.nsca_function, check.nsca_args or ''),
-                results, mode="exec", nocopy=True)
+                results, mode='exec', nocopy=True)
             result = results['result']
             if not result:
                 if check.allow_void_result:
@@ -97,8 +97,8 @@ class NscaCheck(models.Model):
             else:
                 rc, message, performance = result
         except Exception as exc:
-            rc, message = 2, "%s" % exc
-            _logger.warning("%s - %s", check.service, message)
+            rc, message = 2, '%s' % exc
+            _logger.warning('%s - %s', check.service, message)
         check._send_nsca(rc, message, performance)
         return True
 
diff --git a/nsca_client/models/nsca_server.py b/nsca_client/models/nsca_server.py
index 39cc7f9e2..c045c3bec 100644
--- a/nsca_client/models/nsca_server.py
+++ b/nsca_client/models/nsca_server.py
@@ -4,6 +4,7 @@
 
 import psutil
 import os
+import errno
 import shlex
 import subprocess
 import logging
@@ -101,7 +102,7 @@ class NscaServer(models.Model):
             try:
                 os.makedirs(server.config_dir_path)
             except OSError as exception:
-                if exception.errno != os.errno.EEXIST:
+                if exception.errno != errno.EEXIST:
                     raise
             with open(server.config_file_path, 'w') as config_file:
                 if server.password:
diff --git a/nsca_client/readme/CONFIGURE.rst b/nsca_client/readme/CONFIGURE.rst
new file mode 100644
index 000000000..8c4a23d0b
--- /dev/null
+++ b/nsca_client/readme/CONFIGURE.rst
@@ -0,0 +1,56 @@
+To configure this module, you need to:
+
+* Configure your server and a passive service in your monitoring tool
+  (e.g service ``Odoo Mail Queue`` on host ``MY-SERVER``).
+
+* Declare your NSCA server in the menu Configuration / Technical / NSCA Client / Servers
+
+.. image:: nsca_client/static/description/server.png
+   :width: 400 px
+
+* Create NSCA checks in the menu Configuration / Technical / NSCA Client / Checks
+
+.. image:: nsca_client/static/description/check.png
+   :width: 400 px
+
+* Code the methods which will be called by the NSCA checks.
+
+Such methods must return a tuple ``(RC, MESSAGE, PERFORMANCE_DATA)`` where ``RC`` is an integer,
+``MESSAGE`` a unicode string AND ``PERFOMANCE_DATA`` is a dictionary.
+``RC`` values and the corresponding status are:
+
+- 0: OK
+- 1: WARNING
+- 2: CRITICAL
+- 3: UNKNOWN
+
+``PERFORMANCE_DATA`` is not mandatory, so it could be possible to send
+``(RC, MESSAGE)``.
+Each element of ``PERFORMANCE_DATA`` will be a dictionary that could contain:
+
+- value: value of the data (required)
+- max: Max value on the chart
+- min: Minimum value on the chart
+- warn: Warning value on the chart
+- crit: Critical value on the chart
+- uom: Unit of Measure on the chart (s - Seconds, % - Percentage, B - Bytes, c - Continuous)
+
+The key of the dictionary will be used as the performance_data label.
+
+E.g:
+
+.. code-block:: python
+
+    class MailMail(models.Model):
+        _inherit = 'mail.mail'
+
+        @api.model
+        def nsca_check_mails(self):
+            mails = self.search([('state', '=', 'exception')])
+            if mails:
+                return (1, u"%s mails not sent" % len(mails), {
+                  'exceptions': {'value': len(mails)}})
+            return (0, u"OK", {'exceptions': {'value': len(mails)}})
+
+On the example, the performance data will use the label ``exceptions`` and the
+value will be the number of exception of mails.
diff --git a/nsca_client/readme/CONTRIBUTORS.rst b/nsca_client/readme/CONTRIBUTORS.rst
new file mode 100644
index 000000000..6a0c946f9
--- /dev/null
+++ b/nsca_client/readme/CONTRIBUTORS.rst
@@ -0,0 +1,3 @@
+* Sébastien Alix <sebastien.alix@osiell.com>
+* Enric Tobella <etobella@creublanca.es>
+* Jaime Arroyo <jaime.arroyo@creublanca.es>
diff --git a/nsca_client/readme/DESCRIPTION.rst b/nsca_client/readme/DESCRIPTION.rst
new file mode 100644
index 000000000..0f65656d8
--- /dev/null
+++ b/nsca_client/readme/DESCRIPTION.rst
@@ -0,0 +1,4 @@
+This is a technical module to send passive alerts to your favorite NSCA daemon
+(Nagios, Shinken...).
+This module is based on the Odoo cron system and requires a NSCA client
+installed on the system to satisfy the ``/usr/sbin/send_nsca`` command.
diff --git a/nsca_client/readme/INSTALL.rst b/nsca_client/readme/INSTALL.rst
new file mode 100644
index 000000000..966f81584
--- /dev/null
+++ b/nsca_client/readme/INSTALL.rst
@@ -0,0 +1,5 @@
+To use this module, you need to install a NSCA client.
+
+On Debian/Ubuntu::
+
+    $ sudo apt-get install nsca-client
diff --git a/nsca_client/tests/test_nsca.py b/nsca_client/tests/test_nsca.py
index 99cd5b46f..c19f80a83 100644
--- a/nsca_client/tests/test_nsca.py
+++ b/nsca_client/tests/test_nsca.py
@@ -4,6 +4,7 @@
 import mock
 
 from odoo.tests.common import TransactionCase
+from odoo.tools import mute_logger
 
 
 class Popen:
@@ -74,7 +75,8 @@ class TestNsca(TransactionCase):
         })
         with mock.patch('subprocess.Popen') as post:
             post.return_value = Popen
-            self.env['nsca.check']._cron_check(check.id,)
+            with mute_logger('odoo.addons.nsca_client.models.nsca_check'):
+                self.env['nsca.check']._cron_check(check.id,)
             post.assert_called_once()
 
     def test_void_ok(self):