]> arthur.barton.de Git - netdata.git/blobdiff - python.d/python_modules/base.py
MySQLService class added
[netdata.git] / python.d / python_modules / base.py
index e86635f959b49b639f941e7f792e6e7f03773875..0482b9b8059de1c344142118e4f24e861184c091 100644 (file)
 # using ".encode()" in one thread can block other threads as well (only in python2)
 
 import time
-# import sys
 import os
 import socket
 import select
+import threading
+import msg
+import ssl
+from subprocess import Popen, PIPE
+from sys import exc_info
+
 try:
     import urllib.request as urllib2
 except ImportError:
     import urllib2
 
-from subprocess import Popen, PIPE
+try:
+    import MySQLdb
+    PYMYSQL = True
+except ImportError:
+    try:
+        import pymysql as MySQLdb
+        PYMYSQL = True
+    except ImportError:
+        PYMYSQL = False
 
-import threading
-import msg
+try:
+    PATH = os.getenv('PATH').split(':')
+except AttributeError:
+    PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'.split(':')
 
 
 # class BaseService(threading.Thread):
@@ -61,6 +76,7 @@ class SimpleService(threading.Thread):
         self.__first_run = True
         self.order = []
         self.definitions = {}
+        self._data_from_check = dict()
         if configuration is None:
             self.error("BaseService: no configuration parameters supplied. Cannot create Service.")
             raise RuntimeError
@@ -116,21 +132,10 @@ class SimpleService(threading.Thread):
         Return value presents exit status of update()
         :return: boolean
         """
-        t_start = time.time()
-        timetable = self.timetable
+        t_start = float(time.time())
         chart_name = self.chart_name
 
-        # check if it is time to execute job update() function
-        if timetable['next'] > t_start:
-            self.debug(chart_name, "will be run in", str(int((timetable['next'] - t_start) * 1000)), "ms")
-            return True
-
-        since_last = int((t_start - timetable['last']) * 1000000)
-        self.debug(chart_name,
-                   "ready to run, after", str(int((t_start - timetable['last']) * 1000)),
-                   "ms (update_every:", str(timetable['freq'] * 1000),
-                   "ms, latency:", str(int((t_start - timetable['next']) * 1000)), "ms")
-
+        since_last = int((t_start - self.timetable['last']) * 1000000)
         if self.__first_run:
             since_last = 0
 
@@ -138,14 +143,10 @@ class SimpleService(threading.Thread):
             self.error("update function failed.")
             return False
 
-        t_end = time.time()
-        self.timetable['next'] = t_end - (t_end % timetable['freq']) + timetable['freq']
-
         # draw performance graph
-        run_time = str(int((t_end - t_start) * 1000))
-        # noinspection SqlNoDataSourceInspection
+        run_time = int((time.time() - t_start) * 1000)
         print("BEGIN netdata.plugin_pythond_%s %s\nSET run_time = %s\nEND\n" %
-              (self.chart_name, str(since_last), run_time))
+              (self.chart_name, str(since_last), str(run_time)))
 
         self.debug(chart_name, "updated in", str(run_time), "ms")
         self.timetable['last'] = t_start
@@ -158,26 +159,48 @@ class SimpleService(threading.Thread):
         Exits when job failed or timed out.
         :return: None
         """
-        self.timetable['last'] = time.time()
-        self.debug("starting data collection - update frequency: " + str(self.update_every) + ", retries allowed: " + str(self.retries))
+        step = float(self.timetable['freq'])
+        penalty = 0
+        self.timetable['last'] = float(time.time() - step)
+        self.debug("starting data collection - update frequency:", str(step), " retries allowed:", str(self.retries))
         while True:  # run forever, unless something is wrong
+            now = float(time.time())
+            next = self.timetable['next'] = now - (now % step) + step + penalty
+
+            # it is important to do this in a loop
+            # sleep() is interruptable
+            while now < next:
+                self.debug("sleeping for", str(next - now), "secs to reach frequency of", str(step), "secs, now:", str(now), " next:", str(next), " penalty:", str(penalty))
+                time.sleep(next - now)
+                now = float(time.time())
+
+            # do the job
             try:
                 status = self._run_once()
             except Exception as e:
-                self.alert("internal error - aborting data collection: " + str(e))
-                return
+                status = False
 
-            if status:  # handle retries if update failed
-                time.sleep(self.timetable['next'] - time.time())
+            if status:
+                # it is good
                 self.retries_left = self.retries
+                penalty = 0
             else:
+                # it failed
                 self.retries_left -= 1
                 if self.retries_left <= 0:
-                    self.alert("failed to collect data - no more retries allowed - aborting data collection")
-                    return
+                    if penalty == 0:
+                        penalty = float(self.retries * step) / 2
+                    else:
+                        penalty *= 1.5
+
+                    if penalty > 600:
+                        penalty = 600
+
+                    self.retries_left = self.retries
+                    self.alert("failed to collect data for " + str(self.retries) + " times - increasing penalty to " + str(penalty) + " sec and trying again")
+
                 else:
-                    self.error("failed to collect data. " + str(self.retries_left) + " retries left.")
-                    time.sleep(self.timetable['freq'])
+                    self.error("failed to collect data - " + str(self.retries_left) + " retries left - penalty: " + str(penalty) + " sec")
 
     # --- CHART ---
 
@@ -313,7 +336,10 @@ class SimpleService(threading.Thread):
         """
         Upload new data to netdata.
         """
-        print(self._data_stream)
+        try:
+            print(self._data_stream)
+        except Exception as e:
+            msg.fatal('cannot send data to netdata:', str(e))
         self._data_stream = ""
 
     # --- ERROR HANDLING ---
@@ -375,7 +401,7 @@ class SimpleService(threading.Thread):
         Create charts
         :return: boolean
         """
-        data = self._get_data()
+        data = self._data_from_check or self._get_data()
         if data is None:
             self.debug("failed to receive data during create().")
             return False
@@ -421,6 +447,19 @@ class SimpleService(threading.Thread):
 
         return updated
 
+    @staticmethod
+    def find_binary(binary):
+        try:
+            if isinstance(binary, str):
+                binary = os.path.basename(binary)
+                return next(('/'.join([p, binary]) for p in PATH
+                            if os.path.isfile('/'.join([p, binary]))
+                            and os.access('/'.join([p, binary]), os.X_OK)))
+            else:
+                return None
+        except StopIteration:
+            return None
+
 
 class UrlService(SimpleService):
     # TODO add support for https connections
@@ -433,7 +472,17 @@ class UrlService(SimpleService):
 
     def __add_openers(self):
         # TODO add error handling
-        self.opener = urllib2.build_opener()
+        if self.ss_cert:
+            try:
+                ctx = ssl.create_default_context()
+                ctx.check_hostname = False
+                ctx.verify_mode = ssl.CERT_NONE
+                self.opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx))
+            except Exception as error:
+                self.error(str(error))
+                self.opener = urllib2.build_opener()
+        else:
+            self.opener = urllib2.build_opener()
 
         # Proxy handling
         # TODO currently self.proxies isn't parsed from configuration file
@@ -479,7 +528,7 @@ class UrlService(SimpleService):
             return None
 
         try:
-            raw = f.read().decode('utf-8')
+            raw = f.read().decode('utf-8', 'ignore')
         except Exception as e:
             self.error(str(e))
         finally:
@@ -508,7 +557,7 @@ class UrlService(SimpleService):
             self.password = str(self.configuration['pass'])
         except (KeyError, TypeError):
             pass
-
+        self.ss_cert = self.configuration.get('ss_cert')
         self.__add_openers()
 
         test = self._get_data()
@@ -574,32 +623,33 @@ class SocketService(SimpleService):
         self.__socket_config = res
         return True
 
-    def _connect2unixsocket(self, path=None):
+    def _connect2unixsocket(self):
         """
         Connect to a unix socket, given its filename
         :return: boolean
         """
-        if path is None:
+        if self.unix_socket is None:
             self.error("cannot connect to unix socket 'None'")
             return False
 
         try:
-            self.debug("attempting DGRAM unix socket '" + str(path) + "'")
+            self.debug("attempting DGRAM unix socket '" + str(self.unix_socket) + "'")
             self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
-            self._sock.connect(path)
-            self.debug("connected DGRAM unix socket '" + str(path) + "'")
+            self._sock.connect(self.unix_socket)
+            self.debug("connected DGRAM unix socket '" + str(self.unix_socket) + "'")
             return True
         except socket.error as e:
-            self.error("Failed to connect DGRAM unix socket '" + str(path) + "':", str(e))
+            self.debug("Failed to connect DGRAM unix socket '" + str(self.unix_socket) + "':", str(e))
 
         try:
-            self.debug("attempting STREAM unix socket '" + str(path) + "'")
+            self.debug("attempting STREAM unix socket '" + str(self.unix_socket) + "'")
             self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-            self._sock.connect(path)
-            self.debug("connected STREAM unix socket '" + str(path) + "'")
+            self._sock.connect(self.unix_socket)
+            self.debug("connected STREAM unix socket '" + str(self.unix_socket) + "'")
             return True
         except socket.error as e:
-            self.error("Failed to connect STREAM unix socket '" + str(path) + "':", str(e))
+            self.debug("Failed to connect STREAM unix socket '" + str(self.unix_socket) + "':", str(e))
+            self.error("Failed to connect to unix socket '" + str(self.unix_socket) + "':", str(e))
             self._sock = None
             return False
 
@@ -611,7 +661,7 @@ class SocketService(SimpleService):
         """
         try:
             if self.unix_socket is not None:
-                _connect2unixsocket(self.unix_socket)
+                self._connect2unixsocket()
 
             else:
                 if self.__socket_config is not None:
@@ -675,7 +725,7 @@ class SocketService(SimpleService):
                 break
 
             if buf is None or len(buf) == 0:  # handle server disconnect
-                if len(data) == 0:
+                if data == "":
                     self._socketerror("unexpectedly disconnected")
                 else:
                     self.debug("server closed the connection")
@@ -683,7 +733,7 @@ class SocketService(SimpleService):
                 break
 
             self.debug("received data:", str(buf))
-            data += buf.decode(errors='ignore')
+            data += buf.decode('utf-8', 'ignore')
             if self._check_raw_data(data):
                 break
 
@@ -818,63 +868,200 @@ class LogService(SimpleService):
 
 
 class ExecutableService(SimpleService):
-    bad_substrings = ('&', '|', ';', '>', '<')
 
     def __init__(self, configuration=None, name=None):
-        self.command = ""
         SimpleService.__init__(self, configuration=configuration, name=name)
+        self.command = None
 
     def _get_raw_data(self):
         """
         Get raw data from executed command
-        :return: str
+        :return: <list>
         """
         try:
             p = Popen(self.command, stdout=PIPE, stderr=PIPE)
-        except Exception as e:
-            self.error("Executing command", self.command, "resulted in error:", str(e))
+        except Exception as error:
+            self.error("Executing command", self.command, "resulted in error:", str(error))
             return None
-        data = []
+        data = list()
         for line in p.stdout.readlines():
-            data.append(str(line.decode()))
+            data.append(line.decode())
 
-        if len(data) == 0:
-            self.error("No data collected.")
-            return None
-
-        return data
+        return data or None
 
     def check(self):
         """
         Parse basic configuration, check if command is whitelisted and is returning values
-        :return: boolean
+        :return: <boolean>
         """
-        if self.name is not None or self.name != str(None):
-            self.name = ""
+        # Preference: 1. "command" from configuration file 2. "command" from plugin (if specified)
+        if 'command' in self.configuration:
+            self.command = self.configuration['command']
+
+        # "command" must be: 1.not None 2. type <str>
+        if not (self.command and isinstance(self.command, str)):
+            self.error('Command is not defined or command type is not <str>')
+            return False
+
+        # Split "command" into: 1. command <str> 2. options <list>
+        command, opts = self.command.split()[0], self.command.split()[1:]
+
+        # Check for "bad" symbols in options. No pipes, redirects etc. TODO: what is missing?
+        bad_opts = set(''.join(opts)) & set(['&', '|', ';', '>', '<'])
+        if bad_opts:
+            self.error("Bad command argument(s): %s" % bad_opts)
+            return False
+
+        # Find absolute path ('echo' => '/bin/echo')
+        if '/' not in command:
+            command = self.find_binary(command)
+            if not command:
+                self.error('Can\'t locate "%s" binary in PATH(%s)' % (self.command, PATH))
+                return False
+        # Check if binary exist and executable
         else:
-            self.name = str(self.name)
+            if not (os.path.isfile(command) and os.access(command, os.X_OK)):
+                self.error('"%s" is not a file or not executable' % command)
+                return False
+
+        self.command = [command] + opts if opts else [command]
+
         try:
-            self.command = str(self.configuration['command'])
-        except (KeyError, TypeError):
-            self.info("No command specified. Using: '" + self.command + "'")
-        command = self.command.split(' ')
+            data = self._get_data()
+        except Exception as error:
+            self.error('_get_data() failed. Command: %s. Error: %s' % (self.command, error))
+            return False
 
-        for arg in command[1:]:
-            if any(st in arg for st in self.bad_substrings):
-                self.error("Bad command argument:" + " ".join(self.command[1:]))
-                return False
+        if isinstance(data, dict) and data:
+            # We need this for create() method. No reason to execute get_data() again if result is not empty dict()
+            self._data_from_check = data
+            return True
+        else:
+            self.error("Command", str(self.command), "returned no data")
+            return False
+
+
+class MySQLService(SimpleService):
+
+    def __init__(self, configuration=None, name=None):
+        SimpleService.__init__(self, configuration=configuration, name=name)
+        self.__connection = None
+        self.conn_properties = dict()
+        self.queries = dict()
+
+    def __connect(self):
+        try:
+            connection = MySQLdb.connect(connect_timeout=self.update_every, **self.conn_properties)
+        except (MySQLdb.MySQLError, TypeError) as error:
+            return None, str(error)
+        else:
+            return connection, None
+
+    def check(self):
+        def get_connection_properties(conf):
+            properties = dict()
+            if 'user' in conf and conf['user']:
+                properties['user'] = conf['user']
+            if 'pass' in conf and conf['pass']:
+                properties['passwd'] = conf['pass']
+            if 'socket' in conf and conf['socket']:
+                properties['unix_socket'] = conf['socket']
+            elif 'host' in conf and conf['host']:
+                properties['host'] = conf['host']
+                properties['port'] = int(conf['port']) if conf.get('port') else 3306
+            elif 'my.cnf' in conf and conf['my.cnf']:
+                properties['read_default_file'] = conf['my.cnf']
+
+            return properties or None
+
+        def is_valid_queries_dict(raw_queries, log_error):
+            """
+            :param raw_queries: dict:
+            :param log_error: function:
+            :return: dict or None
+
+            raw_queries is valid when: type <dict> and not empty after is_valid_query(for all queries)
+            """
+            def is_valid_query(query):
+                return all([isinstance(query, str),
+                            query.startswith(('SELECT', 'select', 'SHOW', 'show'))])
+
+            if isinstance(raw_queries, dict) and raw_queries:
+                valid_queries = dict([(n, q) for n, q in raw_queries.items() if is_valid_query(q)])
+                bad_queries = set(raw_queries) - set(valid_queries)
+
+                if bad_queries:
+                    log_error('Removed query(s): %s' % bad_queries)
+                return valid_queries
+            else:
+                log_error('Unsupported "queries" format. Must be not empty <dict>')
+                return None
 
-        # test command and search for it in /usr/sbin or /sbin when failed
-        base = command[0].split('/')[-1]
-        if self._get_raw_data() is None:
-            for prefix in ['/sbin/', '/usr/sbin/']:
-                command[0] = prefix + base
-                if os.path.isfile(command[0]):
-                    break
-
-        self.command = command
-        if self._get_data() is None or len(self._get_data()) == 0:
-            self.error("Command", self.command, "returned no data")
+        if not PYMYSQL:
+            self.error('MySQLdb or PyMySQL module is needed to use mysql.chart.py plugin')
             return False
 
-        return True
+        # Check if "self.queries" exist, not empty and all queries are in valid format
+        self.queries = is_valid_queries_dict(self.queries, self.error)
+        if not self.queries:
+            return None
+
+        # Get connection properties
+        self.conn_properties = get_connection_properties(self.configuration)
+        if not self.conn_properties:
+            self.error('Connection properties are missing')
+            return False
+
+        # Create connection to the database
+        self.__connection, error = self.__connect()
+        if error:
+            self.error('Can\'t establish connection to MySQL: %s' % error)
+            return False
+
+        try:
+            data = self._get_data() 
+        except Exception as error:
+            self.error('_get_data() failed. Error: %s' % error)
+            return False
+
+        if isinstance(data, dict) and data:
+            # We need this for create() method
+            self._data_from_check = data
+            return True
+        else:
+            self.error("_get_data() returned no data or type is not <dict>")
+            return False
+    
+    def _get_raw_data(self, description=None):
+        """
+        Get raw data from MySQL server
+        :return: dict: fetchall() or (fetchall(), description)
+        """
+
+        if not self.__connection:
+            self.__connection, error = self.__connect()
+            if error:
+                return None
+
+        raw_data = dict()
+        try:
+            with self.__connection as cursor:
+                for name, query in self.queries.items():
+                    try:
+                        cursor.execute(query)
+                    except (MySQLdb.ProgrammingError, MySQLdb.OperationalError) as error:
+                        if exc_info()[0] == MySQLdb.OperationalError and 'denied' not in str(error):
+                            raise RuntimeError
+                        self.error('Removed query: %s[%s]. Error: %s'
+                                   % (name, query, error))
+                        self.queries.pop(name)
+                        continue
+                    else:
+                        raw_data[name] = (cursor.fetchall(), cursor.description) if description else cursor.fetchall()
+            self.__connection.commit()
+        except (MySQLdb.MySQLError, RuntimeError, TypeError, AttributeError):
+            self.__connection.close()
+            self.__connection = None
+            return None
+        else:
+            return raw_data or None