]> arthur.barton.de Git - netdata.git/commitdiff
Merge pull request #1424 from l2isbad/isc_dhcpd_plugin
authorCosta Tsaousis <costa@tsaousis.gr>
Sun, 25 Dec 2016 10:57:55 +0000 (12:57 +0200)
committerGitHub <noreply@github.com>
Sun, 25 Dec 2016 10:57:55 +0000 (12:57 +0200)
Isc dhcpd plugin

18 files changed:
CMakeLists.txt
README.md
charts.d/apcupsd.chart.sh
conf.d/health.d/backend.conf
conf.d/python.d/hddtemp.conf
conf.d/python.d/sensors.conf
configs.signatures
netdata-installer.sh
python.d/freeradius.chart.py
python.d/hddtemp.chart.py
python.d/nginx_log.chart.py
python.d/sensors.chart.py
src/Makefile.am
src/backends.c
src/common.h
src/log.h
src/socket.c [new file with mode: 0644]
src/socket.h [new file with mode: 0644]

index d58e66cbe0ee67dde922cb18f750fb6d4a0d8195..eb56d2a0c9b69baca77a5c71f27c0beeac764d7d 100755 (executable)
@@ -94,7 +94,7 @@ set(NETDATA_SOURCE_FILES
         src/web_client.h
         src/web_server.c
         src/web_server.h
-)
+        src/socket.c src/socket.h)
 
 set(APPS_PLUGIN_SOURCE_FILES
         src/appconfig.c
index 09913462c6dd2410972a0a9252ece4a530f890e6..67af9456338a39aefe0c73d33430ebfd532b7c6f 100644 (file)
--- a/README.md
+++ b/README.md
@@ -54,7 +54,7 @@ disrupting their core function._
    
  - **Highly efficient**<br/>
    collects thousands of metrics per server per second,
-   with just 1% CPU utilization of a single core, a few MB or RAM and no disk I/O at all
+   with just 1% CPU utilization of a single core, a few MB of RAM and no disk I/O at all
    
  - **Sophisticated alarming**<br/>
    supports dynamic thresholds, hysteresis, alarm templates,
index 24905afe912ac178c428eaa0d1a799e8427b481d..46a86101c670d1390819bc61849407ae3613f48f 100755 (executable)
@@ -68,7 +68,7 @@ DIMENSION output_voltage_nominal nominal absolute 1 100
 CHART apcupsd.load '' "UPS Load" "percentage" ups apcupsd.load area $((apcupsd_priority)) $apcupsd_update_every
 DIMENSION load load absolute 1 100
 
-CHART apcupsd.temp '' "UPS Temperature" "Celcius" ups apcupsd.temperature line $((apcupsd_priority + 7)) $apcupsd_update_every
+CHART apcupsd.temp '' "UPS Temperature" "Celsius" ups apcupsd.temperature line $((apcupsd_priority + 7)) $apcupsd_update_every
 DIMENSION temp temp absolute 1 100
 
 CHART apcupsd.time '' "UPS Time Remaining" "Minutes" ups apcupsd.time area $((apcupsd_priority + 2)) $apcupsd_update_every
index ba40a5f12c4bef5e9b4794ef46aa173f22540042..d127c0f8d157224fcde2785b7a48e6984324f8be 100644 (file)
@@ -15,7 +15,7 @@
    alarm: backend_metrics_sent
       on: netdata.backend_metrics
    units: %
-    calc: $sent * 100 / $buffered
+    calc: abs($sent) * 100 / abs($buffered)
    every: 10s
     warn: $this != 100
    delay: down 5m multiplier 1.5 max 1h
@@ -25,7 +25,7 @@
    alarm: backend_metrics_lost
       on: netdata.backend_metrics
    units: metrics
-    calc: $lost
+    calc: abs($lost)
    every: 10s
     crit: $this != 0
    delay: down 5m multiplier 1.5 max 1h
index 0c78449b42eaecdc589a25f812d9a2fb013607c2..f74a09803aa2bb7e89d11611dab36cce14f863d6 100644 (file)
@@ -58,6 +58,7 @@
 #
 #     host: 'IP or HOSTNAME' # the host to connect to
 #     port: PORT             # the port to connect to
+#     fahrenheit: True/False # fahrenheit instead of celsius. Default is False
 #
 
 # By default this module will try to autodetect disks
 localhost:
   name: 'local'
   host: 'localhost'
+  fahrenheit: False
   port: 7634
 
 localipv4:
   name: 'local'
   host: '127.0.0.1'
+  fahrenheit: False
   port: 7634
 
 localipv6:
index 7d895c348c8a21630fdcbcc82558d35c434cae0a..2e9a41338eff008466215e5c5957bfed4595de76 100644 (file)
@@ -52,3 +52,7 @@ types:
 #
 # chip names can be found using the sensors shell command
 # the prefix is matched (anything that starts like that)
+#
+#----------------------------------------------------------------------
+# To change celsius to fahrenheit uncomment line below
+#fahrenheit: True
index 9a99b690e5941c664049b0493df6270145182267..9a9e8653e22c4cc8e12e02678ef32ceabcae9fc8 100644 (file)
@@ -79,6 +79,7 @@ declare -A configs_signatures=(
   ['3cc6255457d4cba881ae0554ae5d9190']='health.d/squid.conf'
   ['3f170e3343cd784983b019163393f5af']='health.d/nginx.conf'
   ['3fc45cc18e884c22482524dff6d27833']='python.d/hddtemp.conf'
+  ['3fcc3c449ce8e0388f9c23ca07cab608']='health.d/backend.conf'
   ['4063a01bffb43b0423425d1ba3004967']='health.d/tcp_resets.conf'
   ['421d5dc6c2fce22d0816b6e6363bea57']='python.d/hddtemp.conf'
   ['42ad0e70b1365b6e7244cc305dbaa529']='health_alarm_notify.conf'
index 2c5a2479b49b381e2d4958f671c502a3592e00d3..aae4e6281143a5214abe1df430f333364fef5062 100755 (executable)
@@ -624,12 +624,12 @@ portable_add_user_to_group() {
     getent group "${groupname}" > /dev/null 2>&1
     [ $? -ne 0 ] && return 1
 
-    # find the users in the docker group
+    # find the user is already in the group
     local users=$(getent group "${groupname}" | cut -d ':' -f 4)
     if [[ ",${users}," =~ ,${username}, ]]
         then
         # username is already there
-        :
+        return 0
     else
         # username is not in group
         echo >&2 "Adding ${username} user to the ${groupname} group ..."
@@ -660,11 +660,13 @@ portable_add_user_to_group() {
 run find ./system/ -type f -a \! -name \*.in -a \! -name Makefile\* -a \! -name \*.conf  -a \! -name \*.service -exec chmod 755 {} \;
 
 NETDATA_ADDED_TO_DOCKER=0
+NETDATA_ADDED_TO_NGINX=0
 if [ ${UID} -eq 0 ]
     then
     portable_add_group netdata
     portable_add_user netdata
     portable_add_user_to_group docker netdata && NETDATA_ADDED_TO_DOCKER=1
+    portable_add_user_to_group nginx  netdata && NETDATA_ADDED_TO_NGINX=1
 
     if [ -d /etc/logrotate.d -a ! -f /etc/logrotate.d/netdata ]
         then
@@ -965,7 +967,7 @@ install_non_systemd_init() {
             run update-rc.d netdata enable && \
             installed_init_d=1
 
-        elif [ "${key}" = "CentOS release 6.8 (Final)" ]
+        elif [ "${key}" = "CentOS release 6.8 (Final)" -o "${key}" = "amzn-2016.09" ]
             then
             run cp system/netdata-init-d /etc/init.d/netdata && \
             run chmod 755 /etc/init.d/netdata && \
@@ -1276,6 +1278,15 @@ if [ $? -eq 0 -a "${NETDATA_ADDED_TO_DOCKER}" = "1" ]
     echo "   gpasswd -d netdata docker"
 fi
 
+getent group nginx > /dev/null
+if [ $? -eq 0 -a "${NETDATA_ADDED_TO_NGINX}" = "1" ]
+    then
+    echo
+    echo "You may also want to remove the netdata user from the nginx group"
+    echo "by running:"
+    echo "   gpasswd -d netdata nginx"
+fi
+
 UNINSTALL
 chmod 750 netdata-uninstaller.sh
 
index 12fb901d2e3a0e12c187830cef4844c27d2bdf3f..335127fd4d8956760444f50a4222fe3e27e4faf3 100644 (file)
@@ -62,8 +62,12 @@ class Service(SimpleService):
         self.acct = self.configuration.get('acct', False)
         self.proxy_auth = self.configuration.get('proxy_auth', False)
         self.proxy_acct = self.configuration.get('proxy_acct', False)
-        self.echo = [''.join([directory, 'echo']) for directory in directories if isfile(''.join([directory, 'echo']))][:1]
-        self.radclient = [''.join([directory, 'radclient']) for directory in directories if isfile(''.join([directory, 'radclient']))][:1]
+        try:
+            self.echo = [''.join([directory, 'echo']) for directory in directories if isfile(''.join([directory, 'echo']))][0]
+            self.radclient = [''.join([directory, 'radclient']) for directory in directories if isfile(''.join([directory, 'radclient']))][0]
+        except IndexError:
+            self.echo = []
+            self.radclient = []
         self.sub_echo = [self.echo, 'Message-Authenticator = 0x00, FreeRADIUS-Statistics-Type = 15, Response-Packet-Type = Access-Accept']
         self.sub_radclient = [self.radclient, '-r', '1', '-t', '1', ':'.join([self.host, self.port]), 'status', self.secret]
     
index 2e7695db540de530aefa10363a2f996b0c49bee6..8a98995be9e96db0dfae604d536e32fbf04775d7 100644 (file)
@@ -1,6 +1,7 @@
 # -*- coding: utf-8 -*-
 # Description: hddtemp netdata python.d module
 # Author: Pawel Krupa (paulfantom)
+# Modified by l2isbad
 
 import os
 from base import SocketService
@@ -21,15 +22,6 @@ retries = 60
 
 ORDER = ['temperatures']
 
-CHARTS = {
-    'temperatures': {
-        'options': ['disks_temp', 'Disks Temperatures', 'Celsius', 'temperatures', 'hddtemp.temperatures', 'line'],
-        'lines': [
-            # lines are created dynamically in `check()` method
-        ]}
-}
-
-
 class Service(SocketService):
     def __init__(self, configuration=None, name=None):
         SocketService.__init__(self, configuration=configuration, name=name)
@@ -38,7 +30,10 @@ class Service(SocketService):
         self.host = "127.0.0.1"
         self.port = 7634
         self.order = ORDER
-        self.definitions = CHARTS
+        self.fahrenheit = ('Fahrenheit', lambda x: x * 9 / 5 + 32)  if self.configuration.get('fahrenheit') else False
+        self.whatever = ('Whatever', lambda x: x * 33 / 22 + 11) if self.configuration.get('whatever') else False
+        self.choice = (choice for choice in [self.fahrenheit, self.whatever] if choice)
+        self.calc = lambda x: x
         self.disks = []
 
     def _get_disks(self):
@@ -82,7 +77,7 @@ class Service(SocketService):
             if not raw[i*5+1] in self.disks:
                 continue
             try:
-                val = int(raw[i*5+3])
+                val = self.calc(int(raw[i*5+3]))
             except ValueError:
                 val = 0
             data[raw[i*5+1].replace("/dev/", "")] = val
@@ -105,9 +100,21 @@ class Service(SocketService):
         if data is None:
             return False
 
+        self.definitions = {
+            'temperatures': {
+            'options': ['disks_temp', 'Disks Temperatures', 'temperatures', 'hddtemp.temperatures', 'line'],
+            'lines': [
+                # lines are created dynamically in `check()` method
+                          ]}
+                      }
+        try:
+            self.choice = next(self.choice)
+        except StopIteration:
+            self.definitions[ORDER[0]]['options'].insert(2, 'Celsius')
+        else:
+            self.calc = self.choice[1]
+            self.definitions[ORDER[0]]['options'].insert(2, self.choice[0])
+
         for name in data:
             self.definitions[ORDER[0]]['lines'].append([name])
-
         return True
-
-
index 16a9d95713416d5a0a4175434d6e795116857409..ef964a5654b66540dbd903eae4f29bb0ae316ca7 100644 (file)
@@ -15,9 +15,11 @@ CHARTS = {
         'options': [None, 'nginx status codes', 'requests/s', 'requests', 'nginx_log.codes', 'stacked'],
         'lines': [
             ["2xx", None, "incremental"],
+            ["5xx", None, "incremental"],
             ["3xx", None, "incremental"],
             ["4xx", None, "incremental"],
-            ["5xx", None, "incremental"]
+            ["1xx", None, "incremental"],
+            ["other", None, "incremental"]
         ]}
 }
 
@@ -33,21 +35,26 @@ class Service(LogService):
         #pattern = r'(?:" )([0-9][0-9][0-9]) ?'
         self.regex = re.compile(pattern)
 
+        self.data = {
+            '1xx': 0,
+            '2xx': 0,
+            '3xx': 0,
+            '4xx': 0,
+            '5xx': 0,
+            'other': 0
+        }
+
     def _get_data(self):
         """
         Parse new log lines
         :return: dict
         """
-        data = {'2xx': 0,
-                '3xx': 0,
-                '4xx': 0,
-                '5xx': 0}
         try:
             raw = self._get_raw_data()
             if raw is None:
                 return None
             elif not raw:
-                return data
+                return self.data
         except (ValueError, AttributeError):
             return None
 
@@ -60,13 +67,16 @@ class Service(LogService):
                 continue
 
             if beginning == '2':
-                data["2xx"] += 1
+                self.data["2xx"] += 1
             elif beginning == '3':
-                data["3xx"] += 1
+                self.data["3xx"] += 1
             elif beginning == '4':
-                data["4xx"] += 1
+                self.data["4xx"] += 1
             elif beginning == '5':
-                data["5xx"] += 1
-
-        return data
+                self.data["5xx"] += 1
+            elif beginning == '1':
+                self.data["1xx"] += 1
+            else:
+                self.data["other"] += 1
 
+        return self.data
index 23bccb97cfb49ee28d6091d3eed15f5ecdc708f2..e83aacfd81c9db1a87ce1f6fb831a6f355a2bf9d 100644 (file)
@@ -77,6 +77,9 @@ class Service(SimpleService):
         SimpleService.__init__(self, configuration=configuration, name=name)
         self.order = []
         self.definitions = {}
+        self.celsius = ('Celsius', lambda x: x)
+        self.fahrenheit = ('Fahrenheit', lambda x: x * 9 / 5 + 32)  if self.configuration.get('fahrenheit') else False
+        self.choice = (choice for choice in [self.fahrenheit, self.celsius] if choice)
         self.chips = []
 
     def _get_data(self):
@@ -94,7 +97,10 @@ class Service(SimpleService):
                         limit = LIMITS[typeName];
                         if val < limit[0] or val > limit[1]:
                             continue
-                    data[prefix + "_" + str(feature.name.decode())] = int(val * 1000)
+                    if 'temp' in str(feature.name.decode()):
+                        data[prefix + "_" + str(feature.name.decode())] = int(self.calc(val) * 1000)
+                    else:
+                        data[prefix + "_" + str(feature.name.decode())] = int(val * 1000)
         except Exception as e:
             self.error(e)
             return None
@@ -121,6 +127,8 @@ class Service(SimpleService):
                             self.order.append(name)
                             chart_def = list(CHARTS[type]['options'])
                             chart_def[1] = chip_name + chart_def[1]
+                            if chart_def[2] == 'Celsius':
+                                chart_def[2] = self.choice[0]
                             self.definitions[name] = {'options': chart_def}
                             self.definitions[name]['lines'] = []
                         line = list(CHARTS[type]['lines'][0])
@@ -134,10 +142,20 @@ class Service(SimpleService):
         except Exception as e:
             self.error(e)
             return False
+        
+        try:
+            self.choice = next(self.choice)
+        except StopIteration:
+            # That can not happen but..
+            self.choice = ('Celsius', lambda x: x)
+            self.calc = self.choice[1]
+        else:
+            self.calc = self.choice[1]
 
         try:
             self._create_definitions()
         except Exception as e:
             self.error(e)
             return False
+
         return True
index f2ddef3d11081e2253675dcc0a8c37b6f709595a..c2918744a215fcdb8a3863f41a6b722fc85c009a 100644 (file)
@@ -45,6 +45,7 @@ netdata_SOURCES = \
        plugin_tc.c plugin_tc.h \
        plugins_d.c plugins_d.h \
        popen.c popen.h \
+       socket.c socket.h \
        sys_fs_cgroup.c \
        procfile.c procfile.h \
        proc_self_mountinfo.c proc_self_mountinfo.h \
index 34e032fa9ed3f046ea1c0e0e8f1cc918f2688d66..a3b2231dbca2dc0ef77597b77b846dae564075fe 100644 (file)
@@ -4,166 +4,6 @@
 #define BACKEND_SOURCE_DATA_AVERAGE      0x00000002
 #define BACKEND_SOURCE_DATA_SUM          0x00000004
 
-int connect_to_socket4(const char *ip, int port, struct timeval *timeout) {
-    int sock;
-
-    debug(D_LISTENER, "IPv4 connecting to ip '%s' port %d", ip, port);
-
-    sock = socket(AF_INET, SOCK_STREAM, 0);
-    if(sock < 0) {
-        error("IPv4 socket() on ip '%s' port %d failed.", ip, port);
-        return -1;
-    }
-
-    if(setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)timeout, sizeof(struct timeval)) < 0)
-        error("Failed to set timeout on the socket to ip '%s' port %d", ip, port);
-
-    struct sockaddr_in name;
-    memset(&name, 0, sizeof(struct sockaddr_in));
-    name.sin_family = AF_INET;
-    name.sin_port = htons(port);
-
-    int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
-    if(ret != 1) {
-        error("Failed to convert '%s' to a valid IPv4 address.", ip);
-        close(sock);
-        return -1;
-    }
-
-    if(connect(sock, (struct sockaddr *) &name, sizeof(name)) < 0) {
-        close(sock);
-        error("IPv4 failed to connect to '%s', port %d", ip, port);
-        return -1;
-    }
-
-    debug(D_LISTENER, "Connected to IPv4 ip '%s' port %d", ip, port);
-    return sock;
-}
-
-int connect_to_socket6(const char *ip, int port, struct timeval *timeout) {
-    int sock = -1;
-    int ipv6only = 1;
-
-    debug(D_LISTENER, "IPv6 connecting to ip '%s' port %d", ip, port);
-
-    sock = socket(AF_INET6, SOCK_STREAM, 0);
-    if (sock < 0) {
-        error("IPv6 socket() on ip '%s' port %d failed.", ip, port);
-        return -1;
-    }
-
-    if(setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)timeout, sizeof(struct timeval)) < 0)
-        error("Failed to set timeout on the socket to ip '%s' port %d", ip, port);
-
-    /* IPv6 only */
-    if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&ipv6only, sizeof(ipv6only)) != 0)
-        error("Cannot set IPV6_V6ONLY on ip '%s' port's %d.", ip, port);
-
-    struct sockaddr_in6 name;
-    memset(&name, 0, sizeof(struct sockaddr_in6));
-    name.sin6_family = AF_INET6;
-    name.sin6_port = htons ((uint16_t) port);
-
-    int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
-    if(ret != 1) {
-        error("Failed to convert IP '%s' to a valid IPv6 address.", ip);
-        close(sock);
-        return -1;
-    }
-
-    name.sin6_scope_id = 0;
-
-    if(connect(sock, (struct sockaddr *)&name, sizeof(name)) < 0) {
-        close(sock);
-        error("IPv6 failed to connect to '%s', port %d", ip, port);
-        return -1;
-    }
-
-    debug(D_LISTENER, "Connected to IPv6 ip '%s' port %d", ip, port);
-    return sock;
-}
-
-
-static inline int connect_to_one(const char *definition, int default_port, struct timeval *timeout) {
-    struct addrinfo hints;
-    struct addrinfo *result = NULL, *rp = NULL;
-
-    char buffer[strlen(definition) + 1];
-    strcpy(buffer, definition);
-
-    char buffer2[10 + 1];
-    snprintfz(buffer2, 10, "%d", default_port);
-
-    char *ip = buffer, *port = buffer2;
-
-    char *e = ip;
-    if(*e == '[') {
-        e = ++ip;
-        while(*e && *e != ']') e++;
-        if(*e == ']') {
-            *e = '\0';
-            e++;
-        }
-    }
-    else {
-        while(*e && *e != ':') e++;
-    }
-
-    if(*e == ':') {
-        port = e + 1;
-        *e = '\0';
-    }
-
-    if(!*ip)
-        return -1;
-
-    if(!*port)
-        port = buffer2;
-
-    memset(&hints, 0, sizeof(struct addrinfo));
-    hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
-    hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
-    hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
-    hints.ai_protocol = 0;          /* Any protocol */
-    hints.ai_canonname = NULL;
-    hints.ai_addr = NULL;
-    hints.ai_next = NULL;
-
-    int r = getaddrinfo(ip, port, &hints, &result);
-    if (r != 0) {
-        error("Cannot resolve host '%s', port '%s': %s\n", ip, port, gai_strerror(r));
-        return -1;
-    }
-
-    int fd = -1;
-    for (rp = result; rp != NULL && fd == -1; rp = rp->ai_next) {
-        char rip[INET_ADDRSTRLEN + INET6_ADDRSTRLEN] = "INVALID";
-        int rport;
-
-        switch (rp->ai_addr->sa_family) {
-            case AF_INET: {
-                struct sockaddr_in *sin = (struct sockaddr_in *) rp->ai_addr;
-                inet_ntop(AF_INET, &sin->sin_addr, rip, INET_ADDRSTRLEN);
-                rport = ntohs(sin->sin_port);
-                fd = connect_to_socket4(rip, rport, timeout);
-                break;
-            }
-
-            case AF_INET6: {
-                struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) rp->ai_addr;
-                inet_ntop(AF_INET6, &sin6->sin6_addr, rip, INET6_ADDRSTRLEN);
-                rport = ntohs(sin6->sin6_port);
-                fd = connect_to_socket6(rip, rport, timeout);
-                break;
-            }
-        }
-    }
-
-    freeaddrinfo(result);
-
-    return fd;
-}
-
 static inline calculated_number backend_calculate_value_from_stored_data(RRDSET *st, RRDDIM *rd, time_t after, time_t before, uint32_t options) {
     time_t first_t = rrdset_first_entry_t(st);
     time_t last_t = rrdset_last_entry_t(st);
@@ -254,11 +94,46 @@ static inline int format_dimension_stored_opentsdb_telnet(BUFFER *b, const char
     return 0;
 }
 
+static inline int process_graphite_response(BUFFER *b) {
+    char sample[1024];
+    const char *s = buffer_tostring(b);
+    char *d = sample, *e = &sample[sizeof(sample) - 1];
+
+    for(; *s && d < e ;s++) {
+        char c = *s;
+        if(unlikely(!isprint(c))) c = ' ';
+        *d++ = c;
+    }
+    *d = '\0';
+
+    info("Received %zu bytes from graphite backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
+    buffer_flush(b);
+    return 0;
+}
+
+static inline int process_opentsdb_response(BUFFER *b) {
+    char sample[1024];
+    const char *s = buffer_tostring(b);
+    char *d = sample, *e = &sample[sizeof(sample) - 1];
+
+    for(; *s && d < e ;s++) {
+        char c = *s;
+        if(unlikely(!isprint(c))) c = ' ';
+        *d++ = c;
+    }
+    *d = '\0';
+
+    info("Received %zu bytes from opentsdb backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
+    buffer_flush(b);
+    return 0;
+}
+
 void *backends_main(void *ptr) {
     (void)ptr;
 
-    BUFFER *b = buffer_create(1);
-    int (*formatter)(BUFFER *b, const char *prefix, RRDHOST *host, const char *hostname, RRDSET *st, RRDDIM *rd, time_t after, time_t before, uint32_t options);
+    BUFFER *b = buffer_create(1), *response = buffer_create(1);
+    int (*backend_request_formatter)(BUFFER *b, const char *prefix, RRDHOST *host, const char *hostname, RRDSET *st, RRDDIM *rd, time_t after, time_t before, uint32_t options) = NULL;
+    int (*backend_response_checker)(BUFFER *b) = NULL;
 
     info("BACKEND thread created with task id %d", gettid());
 
@@ -311,22 +186,31 @@ void *backends_main(void *ptr) {
     if(!strcmp(type, "graphite") || !strcmp(type, "graphite:plaintext")) {
         default_port = 2003;
         if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
-            formatter = format_dimension_collected_graphite_plaintext;
+            backend_request_formatter = format_dimension_collected_graphite_plaintext;
         else
-            formatter = format_dimension_stored_graphite_plaintext;
+            backend_request_formatter = format_dimension_stored_graphite_plaintext;
+
+        backend_response_checker = process_graphite_response;
     }
     else if(!strcmp(type, "opentsdb") || !strcmp(type, "opentsdb:telnet")) {
         default_port = 4242;
         if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
-            formatter = format_dimension_collected_opentsdb_telnet;
+            backend_request_formatter = format_dimension_collected_opentsdb_telnet;
         else
-            formatter = format_dimension_stored_opentsdb_telnet;
+            backend_request_formatter = format_dimension_stored_opentsdb_telnet;
+
+        backend_response_checker = process_opentsdb_response;
     }
     else {
         error("Unknown backend type '%s'", type);
         goto cleanup;
     }
 
+    if(backend_request_formatter == NULL || backend_response_checker == NULL) {
+        error("backend is misconfigured - disabling it.");
+        goto cleanup;
+    }
+
     if(timeoutms < 1) {
         error("BACKED invalid timeout %ld ms given. Assuming %d ms.", timeoutms, frequency * 2 * 1000);
         timeoutms = frequency * 2 * 1000;
@@ -344,7 +228,9 @@ void *backends_main(void *ptr) {
             chart_lost_metrics = 0,
             chart_sent_metrics = 0,
             chart_buffered_bytes = 0,
+            chart_received_bytes = 0,
             chart_sent_bytes = 0,
+            chart_receptions = 0,
             chart_transmission_successes = 0,
             chart_transmission_failures = 0,
             chart_data_lost_events = 0,
@@ -355,33 +241,43 @@ void *backends_main(void *ptr) {
     RRDSET *chart_metrics = rrdset_find("netdata.backend_metrics");
     if(!chart_metrics) {
         chart_metrics = rrdset_create("netdata", "backend_metrics", NULL, "backend", NULL, "Netdata Buffered Metrics", "metrics", 130600, frequency, RRDSET_TYPE_LINE);
-        rrddim_add(chart_metrics, "buffered", NULL,   1, 1, RRDDIM_ABSOLUTE);
-        rrddim_add(chart_metrics, "lost",     NULL,   1, 1, RRDDIM_ABSOLUTE);
-        rrddim_add(chart_metrics, "sent",     NULL,   1, 1, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_metrics, "buffered", NULL,  1, 1, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_metrics, "lost",     NULL,  1, 1, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_metrics, "sent",     NULL,  1, 1, RRDDIM_ABSOLUTE);
     }
 
     RRDSET *chart_bytes = rrdset_find("netdata.backend_bytes");
     if(!chart_bytes) {
         chart_bytes = rrdset_create("netdata", "backend_bytes", NULL, "backend", NULL, "Netdata Backend Data Size", "KB", 130610, frequency, RRDSET_TYPE_AREA);
-        rrddim_add(chart_bytes, "buffered", NULL,  1, 1024, RRDDIM_ABSOLUTE);
-        rrddim_add(chart_bytes, "lost",     NULL,  1, 1024, RRDDIM_ABSOLUTE);
-        rrddim_add(chart_bytes, "sent",     NULL,  1, 1024, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_bytes, "buffered", NULL, 1, 1024, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_bytes, "lost",     NULL, 1, 1024, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_bytes, "sent",     NULL, 1, 1024, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_bytes, "received", NULL, 1, 1024, RRDDIM_ABSOLUTE);
     }
 
     RRDSET *chart_ops = rrdset_find("netdata.backend_ops");
     if(!chart_ops) {
         chart_ops = rrdset_create("netdata", "backend_ops", NULL, "backend", NULL, "Netdata Backend Operations", "operations", 130630, frequency, RRDSET_TYPE_LINE);
-        rrddim_add(chart_ops, "write",     NULL,  1, 1, RRDDIM_ABSOLUTE);
-        rrddim_add(chart_ops, "discard",   NULL,  1, 1, RRDDIM_ABSOLUTE);
-        rrddim_add(chart_ops, "reconnect", NULL,  1, 1, RRDDIM_ABSOLUTE);
-        rrddim_add(chart_ops, "failure",   NULL,  1, 1, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_ops, "write",     NULL, 1, 1, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_ops, "discard",   NULL, 1, 1, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_ops, "reconnect", NULL, 1, 1, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_ops, "failure",   NULL, 1, 1, RRDDIM_ABSOLUTE);
+        rrddim_add(chart_ops, "read",      NULL, 1, 1, RRDDIM_ABSOLUTE);
     }
 
+    /*
+     * this is misleading - we can only measure the time we need to send data
+     * this time is not related to the time required for the data to travel to
+     * the backend database and the time that server needed to process them
+     *
+     * issue #1432 and https://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-2.html
+     *
     RRDSET *chart_latency = rrdset_find("netdata.backend_latency");
     if(!chart_latency) {
         chart_latency = rrdset_create("netdata", "backend_latency", NULL, "backend", NULL, "Netdata Backend Latency", "ms", 130620, frequency, RRDSET_TYPE_AREA);
         rrddim_add(chart_latency, "latency",   NULL,  1, 1000, RRDDIM_ABSOLUTE);
     }
+    */
 
     RRDSET *chart_rusage = rrdset_find("netdata.backend_thread_cpu");
     if(!chart_rusage) {
@@ -433,7 +329,7 @@ void *backends_main(void *ptr) {
             RRDDIM *rd;
             for(rd = st->dimensions; rd ;rd = rd->next) {
                 if(rd->last_collected_time.tv_sec >= after)
-                    chart_buffered_metrics += formatter(b, prefix, &localhost, hostname, st, rd, after, before, options);
+                    chart_buffered_metrics += backend_request_formatter(b, prefix, &localhost, hostname, st, rd, after, before, options);
             }
 
             pthread_rwlock_unlock(&st->rwlock);
@@ -443,9 +339,12 @@ void *backends_main(void *ptr) {
         if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
             error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
 
+        // ------------------------------------------------------------------------
+
         chart_buffered_bytes = (collected_number)buffer_strlen(b);
 
         // reset the monitoring chart counters
+        chart_received_bytes =
         chart_sent_bytes =
         chart_sent_metrics =
         chart_lost_metrics =
@@ -462,7 +361,42 @@ void *backends_main(void *ptr) {
         //fprintf(stderr, "after = %lu, before = %lu\n", after, before);
 
         // ------------------------------------------------------------------------
-        // connect to a backend server
+        // if we are connected, receive a response, without blocking
+
+        if(likely(sock != -1)) {
+            errno = 0;
+
+            // loop through to collect all data
+            while(sock != -1 && errno != EWOULDBLOCK) {
+                buffer_need_bytes(response, 4096);
+
+                ssize_t r = recv(sock, &response->buffer[response->len], response->size - response->len, MSG_DONTWAIT);
+                if(likely(r > 0)) {
+                    // we received some data
+                    response->len += r;
+                    chart_received_bytes += r;
+                    chart_receptions++;
+                }
+                else if(r == 0) {
+                    error("Backend '%s' closed the socket", destination);
+                    close(sock);
+                    sock = -1;
+                }
+                else {
+                    // failed to receive data
+                    if(errno != EAGAIN && errno != EWOULDBLOCK) {
+                        error("Cannot receive data from backend '%s'.", destination);
+                    }
+                }
+            }
+
+            // if we received data, process them
+            if(buffer_strlen(response))
+                backend_response_checker(response);
+        }
+
+        // ------------------------------------------------------------------------
+        // if we are not connected, connect to a backend server
 
         if(unlikely(sock == -1)) {
             usec_t start_ut = now_realtime_usec();
@@ -482,7 +416,7 @@ void *backends_main(void *ptr) {
                 char buf[e - s + 1];
                 strncpyz(buf, s, e - s);
                 chart_backend_reconnects++;
-                sock = connect_to_one(buf, default_port, &timeout);
+                sock = connect_to(buf, default_port, &timeout);
                 if(sock != -1) break;
                 s = e;
             }
@@ -492,7 +426,7 @@ void *backends_main(void *ptr) {
         if(unlikely(netdata_exit)) break;
 
         // ------------------------------------------------------------------------
-        // send our buffer to the backend server
+        // if we are connected, send our buffer to the backend server
 
         if(likely(sock != -1)) {
             size_t len = buffer_strlen(b);
@@ -501,6 +435,7 @@ void *backends_main(void *ptr) {
 #ifdef MSG_NOSIGNAL
             flags += MSG_NOSIGNAL;
 #endif
+
             ssize_t written = send(sock, buffer_tostring(b), len, flags);
             chart_backend_latency += now_realtime_usec() - start_ut;
             if(written != -1 && (size_t)written == len) {
@@ -561,6 +496,7 @@ void *backends_main(void *ptr) {
         // update the monitoring charts
 
         if(chart_ops->counter_done) rrdset_next(chart_ops);
+        rrddim_set(chart_ops, "read",         chart_receptions);
         rrddim_set(chart_ops, "write",        chart_transmission_successes);
         rrddim_set(chart_ops, "discard",      chart_data_lost_events);
         rrddim_set(chart_ops, "failure",      chart_transmission_failures);
@@ -577,11 +513,14 @@ void *backends_main(void *ptr) {
         rrddim_set(chart_bytes, "buffered",   chart_buffered_bytes);
         rrddim_set(chart_bytes, "lost",       chart_lost_bytes);
         rrddim_set(chart_bytes, "sent",       chart_sent_bytes);
+        rrddim_set(chart_bytes, "received",   chart_received_bytes);
         rrdset_done(chart_bytes);
 
+        /*
         if(chart_latency->counter_done) rrdset_next(chart_latency);
         rrddim_set(chart_latency, "latency",  chart_backend_latency);
         rrdset_done(chart_latency);
+        */
 
         getrusage(RUSAGE_THREAD, &thread);
         if(chart_rusage->counter_done) rrdset_next(chart_rusage);
@@ -599,6 +538,9 @@ cleanup:
     if(sock != -1)
         close(sock);
 
+    buffer_free(b);
+    buffer_free(response);
+
     info("BACKEND thread exiting");
 
     pthread_exit(NULL);
index 26fd61d68611c5032c233263c09cc6227e585640..d0084f6c0045754f09d517e69c5b1a1f8da27fce 100644 (file)
@@ -60,6 +60,8 @@
 #include <netdb.h>
 #endif
 
+#include <net/if.h>
+
 #include <poll.h>
 #include <signal.h>
 #include <syslog.h>
 #include "plugin_tc.h"
 #include "plugins_d.h"
 
+#include "socket.h"
+
 #include "eval.h"
 #include "health.h"
 
index b7323fcf47bd5e73ebe3542e32ddb378ff10f536..92ffe6f1edcb8c9b92d571ae7d0ef0e863934834 100644 (file)
--- a/src/log.h
+++ b/src/log.h
@@ -25,6 +25,7 @@
 #define D_REGISTRY          0x00200000
 #define D_VARIABLES         0x00400000
 #define D_HEALTH            0x00800000
+#define D_CONNECT_TO        0x01000000
 #define D_SYSTEM            0x80000000
 
 //#define DEBUG (D_WEB_CLIENT_ACCESS|D_LISTENER|D_RRD_STATS)
diff --git a/src/socket.c b/src/socket.c
new file mode 100644 (file)
index 0000000..643811e
--- /dev/null
@@ -0,0 +1,179 @@
+#include "common.h"
+
+// connect_to()
+//
+// definition format:
+//
+//    [PROTOCOL:]IP[%INTERFACE][:PORT]
+//
+// PROTOCOL  = tcp or udp
+// IP        = IPv4 or IPv6 IP or hostname, optionally enclosed in [] (required for IPv6)
+// INTERFACE = for IPv6 only, the network interface to use
+// PORT      = port number or service name
+
+int connect_to(const char *definition, int default_port, struct timeval *timeout) {
+    struct addrinfo hints;
+    struct addrinfo *ai_head = NULL, *ai = NULL;
+
+    char buffer[strlen(definition) + 1];
+    strcpy(buffer, definition);
+
+    char default_service[10 + 1];
+    snprintfz(default_service, 10, "%d", default_port);
+
+    char *host = buffer, *service = default_service, *interface = "";
+    int protocol = IPPROTO_TCP, socktype = SOCK_STREAM;
+    uint32_t scope_id = 0;
+
+    if(strncmp(host, "tcp:", 4) == 0) {
+        host += 4;
+        protocol = IPPROTO_TCP;
+        socktype = SOCK_STREAM;
+    }
+    else if(strncmp(host, "udp:", 4) == 0) {
+        host += 4;
+        protocol = IPPROTO_UDP;
+        socktype = SOCK_DGRAM;
+    }
+
+    char *e = host;
+    if(*e == '[') {
+        e = ++host;
+        while(*e && *e != ']') e++;
+        if(*e == ']') {
+            *e = '\0';
+            e++;
+        }
+    }
+    else {
+        while(*e && *e != ':' && *e != '%') e++;
+    }
+
+    if(*e == '%') {
+        *e = '\0';
+        e++;
+        interface = e;
+        while(*e && *e != ':') e++;
+    }
+
+    if(*e == ':') {
+        *e = '\0';
+        e++;
+        service = e;
+    }
+
+    debug(D_CONNECT_TO, "Attempting connection to host = '%s', service = '%s', interface = '%s', protocol = %d (tcp = %d, udp = %d)", host, service, interface, protocol, IPPROTO_TCP, IPPROTO_UDP);
+
+    if(!*host) {
+        error("Definition '%s' does not specify a host.", definition);
+        return -1;
+    }
+
+    if(*interface) {
+        scope_id = if_nametoindex(interface);
+        if(!scope_id)
+            error("Cannot find a network interface named '%s'. Continuing with limiting the network interface", interface);
+    }
+
+    if(!*service)
+        service = default_service;
+
+    memset(&hints, 0, sizeof(hints));
+    hints.ai_family   = PF_UNSPEC;   /* Allow IPv4 or IPv6 */
+    hints.ai_socktype = socktype;
+    hints.ai_protocol = protocol;
+
+    int ai_err = getaddrinfo(host, service, &hints, &ai_head);
+    if (ai_err != 0) {
+        error("Cannot resolve host '%s', port '%s': %s", host, service, gai_strerror(ai_err));
+        return -1;
+    }
+
+    int fd = -1;
+    for (ai = ai_head; ai != NULL && fd == -1; ai = ai->ai_next) {
+
+        if (ai->ai_family == PF_INET6) {
+            struct sockaddr_in6 *pSadrIn6 = (struct sockaddr_in6 *) ai->ai_addr;
+            if(pSadrIn6->sin6_scope_id == 0) {
+                pSadrIn6->sin6_scope_id = scope_id;
+            }
+        }
+
+        char hostBfr[NI_MAXHOST + 1];
+        char servBfr[NI_MAXSERV + 1];
+
+        getnameinfo(ai->ai_addr,
+                ai->ai_addrlen,
+                hostBfr,
+                sizeof(hostBfr),
+                servBfr,
+                sizeof(servBfr),
+                NI_NUMERICHOST | NI_NUMERICSERV);
+
+        debug(D_CONNECT_TO, "Address info: host = '%s', service = '%s', ai_flags = 0x%02X, ai_family = %d (PF_INET = %d, PF_INET6 = %d), ai_socktype = %d (SOCK_STREAM = %d, SOCK_DGRAM = %d), ai_protocol = %d (IPPROTO_TCP = %d, IPPROTO_UDP = %d), ai_addrlen = %lu (sockaddr_in = %lu, sockaddr_in6 = %lu)",
+                hostBfr,
+                servBfr,
+                (unsigned int)ai->ai_flags,
+                ai->ai_family,
+                PF_INET,
+                PF_INET6,
+                ai->ai_socktype,
+                SOCK_STREAM,
+                SOCK_DGRAM,
+                ai->ai_protocol,
+                IPPROTO_TCP,
+                IPPROTO_UDP,
+                (unsigned long)ai->ai_addrlen,
+                (unsigned long)sizeof(struct sockaddr_in),
+                (unsigned long)sizeof(struct sockaddr_in6));
+
+        switch (ai->ai_addr->sa_family) {
+            case PF_INET: {
+                struct sockaddr_in *pSadrIn = (struct sockaddr_in *)ai->ai_addr;
+                debug(D_CONNECT_TO, "ai_addr = sin_family: %d (AF_INET = %d, AF_INET6 = %d), sin_addr: '%s', sin_port: '%s'",
+                        pSadrIn->sin_family,
+                        AF_INET,
+                        AF_INET6,
+                        hostBfr,
+                        servBfr);
+                break;
+            }
+
+            case PF_INET6: {
+                struct sockaddr_in6 *pSadrIn6 = (struct sockaddr_in6 *) ai->ai_addr;
+                debug(D_CONNECT_TO,"ai_addr = sin6_family: %d (AF_INET = %d, AF_INET6 = %d), sin6_addr: '%s', sin6_port: '%s', sin6_flowinfo: %u, sin6_scope_id: %u",
+                        pSadrIn6->sin6_family,
+                        AF_INET,
+                        AF_INET6,
+                        hostBfr,
+                        servBfr,
+                        pSadrIn6->sin6_flowinfo,
+                        pSadrIn6->sin6_scope_id);
+                break;
+            }
+
+            default: {
+                debug(D_CONNECT_TO, "Unknown protocol family %d.", ai->ai_family);
+                continue;
+            }
+        }
+
+        fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
+        if(fd != -1) {
+            if(setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)timeout, sizeof(struct timeval)) < 0)
+                error("Failed to set timeout on the socket to ip '%s' port '%s'", hostBfr, servBfr);
+
+            if(connect(fd, ai->ai_addr, ai->ai_addrlen) < 0) {
+                error("Failed to connect to '%s', port '%s'", hostBfr, servBfr);
+                close(fd);
+                fd = -1;
+            }
+
+            debug(D_CONNECT_TO, "Connected to '%s' on port '%s'.", hostBfr, servBfr);
+        }
+    }
+
+    freeaddrinfo(ai_head);
+
+    return fd;
+}
diff --git a/src/socket.h b/src/socket.h
new file mode 100644 (file)
index 0000000..791c0ce
--- /dev/null
@@ -0,0 +1,10 @@
+//
+// Created by costa on 24/12/2016.
+//
+
+#ifndef NETDATA_SOCKET_H
+#define NETDATA_SOCKET_H
+
+extern int connect_to(const char *definition, int default_port, struct timeval *timeout);
+
+#endif //NETDATA_SOCKET_H