]> arthur.barton.de Git - netdata.git/commitdiff
Merge branch 'master' into ab-debian
authorAlexander Barton <alex@barton.de>
Mon, 13 Feb 2017 13:23:05 +0000 (14:23 +0100)
committerAlexander Barton <alex@barton.de>
Mon, 13 Feb 2017 13:23:05 +0000 (14:23 +0100)
* master: (88 commits)
  fixed typo in installer and other minor improvements
  updated configs.signatures
  compatibility fixes at the installer
  fix lxc-attach not exiting after starting netdata
  colorful netdata-installer.sh; splitted certain functions for adding makeself; netdata-uninstaller.sh and netdata-updater.sh are now generated even when netdata-installer is called with --dont-start-it
  Fix license name
  Fix license name
  Support older autoconf versions
  when version.txt and internal version differ, use the internal one
  properly show version and check version using the internal version string too
  do not compile netdata twice on travis
  information at web_log.conf
  show netdata version at the dashboard
  Update /charts at API definition.
  web_log plugin: support for additional log format added
  properly reset charts after max time of refreshes; fixes #1631
  do not discard old data on algorithm mismatch
  improved dashboard information about web_log charts
  updated configs.signatures
  web_log fixes and improvements
  ...

40 files changed:
.codeclimate.yml
.travis.yml
CMakeLists.txt
Makefile.am
charts.d/nut.chart.sh
conf.d/Makefile.am
conf.d/charts.d/nut.conf
conf.d/health.d/web_log.conf [new file with mode: 0644]
conf.d/python.d.conf
conf.d/python.d/web_log.conf [new file with mode: 0644]
configs.signatures
configure.ac
installer/functions.sh [new file with mode: 0644]
netdata-installer.sh
packaging/packaging.functions
packaging/update-tags
plugins.d/fping.plugin
plugins.d/python.d.plugin
python.d/Makefile.am
python.d/gunicorn_log.chart.py [deleted file]
python.d/nginx_log.chart.py [deleted file]
python.d/web_log.chart.py [new file with mode: 0644]
src/apps_plugin.c
src/common.c
src/common.h
src/freebsd_sysctl.c
src/health.c
src/main.c
src/main.h
src/rrd.c
src/rrd2json.c
src/web_buffer_svg.c
web/Makefile.am
web/dashboard.js
web/dashboard_info.js
web/index.html
web/lib/gauge-1.3.2.min.js [new file with mode: 0644]
web/lib/gauge-d5260c3.min.js [deleted file]
web/netdata-swagger.json
web/netdata-swagger.yaml

index 91e0babae88d9a16d1f68e0673b531e25712f0e1..02b4526478771fe1894b684de1efcf7e41727103 100644 (file)
@@ -13,6 +13,8 @@ engines:
     checks:
       Similar code:
         enabled: false
+      Identical code:
+        enabled: false
   eslint:
     enabled: true
     checks:
@@ -28,6 +30,8 @@ engines:
         enabled: false
       no-alert:
         enabled: false
+      no-undef-init:
+        enabled: false
   fixme:
     enabled: false
   phpmd:
index 5968c1251f39ec53bf81d4505cd3a18c09e65ac1..b7e04bfba79f65ee00d33bcc0c544767941a6c6b 100644 (file)
@@ -2,6 +2,9 @@ dist: precise
 #
 # C includes autotools and make by default
 language: c
+os:
+  - linux
+  - osx
 compiler:
  - gcc
  - clang
@@ -19,6 +22,8 @@ addons:
 before_install:
  - eval "$(ssh-agent -s)"
  - ./.travis/decrypt-if-have-key decb6f6387c4
+ - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew update ; fi
+ - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew install gpg fakeroot ossp-uuid xz; fi
 #
 # Run
 before_script:
@@ -28,9 +33,7 @@ before_script:
 script:
    # make release packages
  - fakeroot ./packaging/git-build
-   # default build
- - ./autogen.sh && ./configure && make -j4
-   # test installer
+   # test build and installer
  - fakeroot ./netdata-installer.sh --install $HOME --dont-wait --dont-start-it
 #
 # Deploy as required
@@ -46,6 +49,6 @@ deploy:
     file_glob: true
     file: "netdata*.tar.*"
     on:
-      condition: $CC = gcc
+      condition: $CC = gcc && $TRAVIS_OS_NAME
       repo: firehol/netdata
       tags: true
index 19acbd5adb36837c86b43258f710c99081658072..04c4415e0d611ba4a110d2fca39060a5d0ba91ac 100755 (executable)
@@ -101,7 +101,28 @@ set(NETDATA_SOURCE_FILES
         src/registry_person.c
         src/registry_person.h
         src/registry_machine.c
-        src/registry_machine.h src/registry_internals.c src/registry_init.c src/registry_db.c src/registry_log.c src/proc_uptime.c src/sys_devices_system_edac_mc.c src/plugin_proc_diskspace.c src/plugin_proc_diskspace.h src/simple_pattern.c src/simple_pattern.h src/inlined.h src/adaptive_resortable_list.h src/adaptive_resortable_list.c)
+        src/registry_machine.h
+        src/registry_internals.c
+        src/registry_init.c
+        src/registry_db.c
+        src/registry_log.c
+        src/proc_uptime.c
+        src/sys_devices_system_edac_mc.c
+        src/plugin_proc_diskspace.c
+        src/plugin_proc_diskspace.h
+        src/simple_pattern.c
+        src/simple_pattern.h
+        src/inlined.h
+        src/adaptive_resortable_list.h
+        src/adaptive_resortable_list.c
+        src/plugin_freebsd.c
+        src/plugin_freebsd.h
+        src/macos_fw.c
+        src/macos_mach_smi.c
+        src/macos_sysctl.c
+        src/plugin_macos.c
+        src/plugin_macos.h
+        )
 
 set(APPS_PLUGIN_SOURCE_FILES
         src/appconfig.c
index ab77bc7342711b6a60b7e435812717b8a74c1dd6..e78bbbbd5e69aee62a72df7034c14a3a68f6d073 100644 (file)
@@ -60,4 +60,5 @@ dist_noinst_SCRIPTS= \
        coverity-scan.sh \
        docker-build.sh \
        netdata-installer.sh \
+       installer/functions.sh \
        $(NULL)
index e0b1b4cf981bedbb6e0a8de8c59cecb414d1c77d..6137639f982621277caa6fe21fce46133ef400eb 100644 (file)
@@ -2,7 +2,7 @@
 
 # netdata
 # real-time performance and health monitoring, done right!
-# (C) 2016 Costa Tsaousis <costa@tsaousis.gr>
+# (C) 2016-2017 Costa Tsaousis <costa@tsaousis.gr>
 # GPL v3+
 #
 
@@ -13,8 +13,13 @@ nut_ups=
 # how frequently to collect UPS data
 nut_update_every=2
 
+# how much time in seconds, to wait for nut to respond
 nut_timeout=2
 
+# set this to 1, to enable another chart showing the number
+# of UPS clients connected to upsd
+nut_clients_chart=0
+
 # the priority of nut related to other charts
 nut_priority=90000
 
@@ -26,6 +31,12 @@ nut_get_all() {
 
 nut_get() {
        run -t $nut_timeout upsc "$1"
+
+       if [ "${nut_clients_chart}" -eq "1" ]
+               then
+               printf "ups.connected_clients: "
+               run -t $nut_timeout upsc -c "$1" | wc -l
+       fi
 }
 
 nut_check() {
@@ -97,6 +108,15 @@ DIMENSION load load absolute 1 100
 CHART nut_$x.temp '' "UPS Temperature" "temperature" ups nut.temperature line $((nut_priority + 7)) $nut_update_every
 DIMENSION temp temp absolute 1 100
 EOF
+
+       if [ "${nut_clients_chart}" = "1" ]
+               then
+               cat <<EOF2
+CHART nut_$x.clients '' "UPS Connected Clients" "clients" ups nut.clients area $((nut_priority + 8)) $nut_update_every
+DIMENSION clients '' absolute 1 1
+EOF2
+       fi
+
        done
 
        return 0
@@ -131,6 +151,8 @@ BEGIN {
        output_voltage = 0;
        load = 0;
        temp = 0;
+       client = 0;
+       do_clients = ${nut_clients_chart};
 }
 /^battery.charge: .*/                  { battery_charge = \$2 * 100 };
 /^battery.voltage: .*/                 { battery_voltage = \$2 * 100 };
@@ -146,6 +168,7 @@ BEGIN {
 /^output.voltage: .*/                  { output_voltage = \$2 * 100 };
 /^ups.load: .*/                                        { load = \$2 * 100 };
 /^ups.temperature: .*/                 { temp = \$2 * 100 };
+/^ups.connected_clients: .*/   { clients = \$2 };
 END {
        print \"BEGIN nut_$x.charge $1\";
        print \"SET battery_charge = \" battery_charge;
@@ -184,6 +207,12 @@ END {
        print \"BEGIN nut_$x.temp $1\";
        print \"SET temp = \" temp;
        print \"END\"
+
+       if(do_clients) {
+               print \"BEGIN nut_$x.clients $1\";
+               print \"SET clients = \" clients;
+               print \"END\"
+       }
 }"
                [ $? -ne 0 ] && unset nut_ids[$i] && error "failed to get values for '$i', disabling it."
        done
index acca5a4db978a0f4c99e9a569518701b3edb19c7..c746a909d56e1b6994201238e22dbf375047a837 100644 (file)
@@ -33,7 +33,6 @@ dist_pythonconfig_DATA = \
     python.d/exim.conf \
     python.d/fail2ban.conf \
     python.d/freeradius.conf \
-    python.d/gunicorn_log.conf \
     python.d/haproxy.conf \
     python.d/hddtemp.conf \
     python.d/ipfs.conf \
@@ -42,7 +41,6 @@ dist_pythonconfig_DATA = \
     python.d/memcached.conf \
     python.d/mysql.conf \
     python.d/nginx.conf \
-    python.d/nginx_log.conf \
     python.d/ovpn_status_log.conf \
     python.d/phpfpm.conf \
     python.d/postfix.conf \
@@ -54,42 +52,50 @@ dist_pythonconfig_DATA = \
     python.d/smartd_log.conf \
     python.d/tomcat.conf \
     python.d/varnish.conf \
+    python.d/web_log.conf \
     $(NULL)
 
 healthconfigdir=$(configdir)/health.d
+
 dist_healthconfig_DATA = \
     health.d/apache.conf \
     health.d/backend.conf \
     health.d/bind_rndc.conf \
-    health.d/cpu.conf \
-    health.d/disks.conf \
     health.d/elasticsearch.conf \
-    health.d/entropy.conf \
     health.d/fping.conf \
     health.d/haproxy.conf \
-    health.d/ipc.conf \
     health.d/ipfs.conf \
     health.d/isc_dhcpd.conf \
     health.d/mdstat.conf \
     health.d/memcached.conf \
-    health.d/memory.conf \
     health.d/mysql.conf \
     health.d/named.conf \
-    health.d/net.conf \
-    health.d/netfilter.conf \
     health.d/nginx.conf \
     health.d/postgres.conf \
-    health.d/qos.conf \
-    health.d/ram.conf \
     health.d/redis.conf \
     health.d/retroshare.conf \
-    health.d/softnet.conf \
     health.d/squid.conf \
+    health.d/varnish.conf \
+    health.d/web_log.conf \
+    $(NULL)
+
+if LINUX
+dist_healthconfig_DATA += \
+    health.d/cpu.conf \
+    health.d/disks.conf \
+    health.d/entropy.conf \
+    health.d/ipc.conf \
+    health.d/memory.conf \
+    health.d/net.conf \
+    health.d/netfilter.conf \
+    health.d/qos.conf \
+    health.d/ram.conf \
+    health.d/softnet.conf \
     health.d/swap.conf \
     health.d/tcp_resets.conf \
     health.d/udp_errors.conf \
-    health.d/varnish.conf \
     $(NULL)
+endif LINUX
 
 chartsconfigdir=$(configdir)/charts.d
 dist_chartsconfig_DATA = \
index 2844849de0fbfc2622a3b11dd4b7c494ea30e04f..a836692d89cb134a0fabb68a18e59954233fbfb3 100644 (file)
@@ -2,7 +2,7 @@
 
 # netdata
 # real-time performance and health monitoring, done right!
-# (C) 2016 Costa Tsaousis <costa@tsaousis.gr>
+# (C) 2016-2017 Costa Tsaousis <costa@tsaousis.gr>
 # GPL v3+
 
 # a space separated list of UPS names
 # how much time in seconds, to wait for nut to respond
 #nut_timeout=2
 
+# set this to 1, to enable another chart showing the number
+# of UPS clients connected to upsd
+#nut_clients_chart=1
+
 # the data collection frequency
 # if unset, will inherit the netdata update frequency
 #nut_update_every=2
diff --git a/conf.d/health.d/web_log.conf b/conf.d/health.d/web_log.conf
new file mode 100644 (file)
index 0000000..c8d0c11
--- /dev/null
@@ -0,0 +1,169 @@
+
+# make sure we can collect web log data
+
+template: last_collected_secs
+      on: web_log.response_codes
+families: *
+    calc: $now - $last_collected_t
+   units: seconds ago
+   every: 10s
+    warn: $this > (($status >= $WARNING)  ? ($update_every) : ( 5 * $update_every))
+    crit: $this > (($status == $CRITICAL) ? ($update_every) : (60 * $update_every))
+   delay: down 5m multiplier 1.5 max 1h
+    info: number of seconds since the last successful data collection
+      to: webmaster
+
+
+# -----------------------------------------------------------------------------
+# high level response code alarms
+
+# the following alarms trigger only when there are enough data.
+# we assume there are enough data when:
+#
+#  $1m_requests > 120
+#
+# i.e. when there are at least 120 requests during the last minute
+
+template: 1m_requests
+      on: web_log.response_codes
+families: *
+  lookup: sum -1m unaligned
+    calc: ($this == 0)?(1):($this)
+   units: requests
+   every: 10s
+    info: the sum of all HTTP requests over the last minute
+
+template: 1m_2xx
+      on: web_log.response_codes
+families: *
+  lookup: sum -1m unaligned of 2xx
+    calc: ($this == 0)?(1):($this)
+   units: requests
+   every: 10s
+    info: the sum of successful HTTP requests over the last minute
+
+template: 1m_successful
+      on: web_log.response_codes
+families: *
+    calc: $1m_2xx * 100 / $1m_requests
+   units: %
+   every: 10s
+    warn: ($1m_requests > 120) ? ($this < (($status >= $WARNING ) ? ( 98 ) : ( 95 )) ) : ( 0 )
+    crit: ($1m_requests > 120) ? ($this < (($status == $CRITICAL) ? ( 95 ) : ( 90 )) ) : ( 0 )
+   delay: down 15m multiplier 1.5 max 1h
+    info: the ratio of successful HTTP responses (2xx) over the last minute
+      to: webmaster
+
+template: 1m_redirects
+      on: web_log.detailed_response_codes
+families: *
+  lookup: sum -1m unaligned of 301,303,307,308
+    calc: $this * 100 / $1m_requests
+   units: %
+   every: 10s
+    warn: ($1m_requests > 120) ? ($this > (($status >= $WARNING ) ? ( 1 ) : ( 2 )) ) : ( 0 )
+    crit: ($1m_requests > 120) ? ($this > (($status == $CRITICAL) ? ( 2 ) : ( 5 )) ) : ( 0 )
+   delay: down 15m multiplier 1.5 max 1h
+    info: the ratio of HTTP redirects (301, 303, 307, 308) over the last minute
+      to: webmaster
+
+template: 1m_bad_requests
+      on: web_log.response_codes
+families: *
+  lookup: sum -1m unaligned of 4xx
+    calc: $this * 100 / $1m_requests
+   units: %
+   every: 10s
+    warn: ($1m_requests > 120) ? ($this > (($status >= $WARNING)  ? ( 1 ) : (  5 )) ) : ( 0 )
+    crit: ($1m_requests > 120) ? ($this > (($status == $CRITICAL) ? ( 5 ) : ( 10 )) ) : ( 0 )
+   delay: down 15m multiplier 1.5 max 1h
+    info: the ratio of HTTP bad requests (4xx) over the last minute
+      to: webmaster
+
+template: 1m_internal_errors
+      on: web_log.response_codes
+families: *
+  lookup: sum -1m unaligned of 5xx
+    calc: $this * 100 / $1m_requests
+   units: %
+   every: 10s
+    warn: ($1m_requests > 120) ? ($this > (($status >= $WARNING)  ? ( 1 ) : ( 2 )) ) : ( 0 )
+    crit: ($1m_requests > 120) ? ($this > (($status == $CRITICAL) ? ( 2 ) : ( 5 )) ) : ( 0 )
+   delay: down 15m multiplier 1.5 max 1h
+    info: the ratio of HTTP internal server errors (5xx), over the last minute
+      to: webmaster
+
+
+# -----------------------------------------------------------------------------
+# web slow
+
+# the following alarms trigger only when there are enough data.
+# we assume there are enough data when:
+#
+#  $1m_requests > 120
+#
+# i.e. when there are at least 120 requests during the last minute
+
+template: 10m_response_time
+      on: web_log.response_time
+families: *
+  lookup: average -10m unaligned of avg
+   units: ms
+   every: 30s
+    info: the average time to respond to HTTP requests, over the last 10 minutes
+
+template: web_slow
+      on: web_log.response_time
+families: *
+  lookup: average -1m unaligned of avg
+   units: ms
+   every: 10s
+   green: 500
+     red: 1000
+    warn: ($1m_requests > 120) ? ($this > $green && $this > ($10m_response_time * 2) ) : ( 0 )
+    crit: ($1m_requests > 120) ? ($this > $red   && $this > ($10m_response_time * 4) ) : ( 0 )
+   delay: down 15m multiplier 1.5 max 1h
+    info: the average time to respond to HTTP requests, over the last 1 minute
+      to: webmaster
+
+# -----------------------------------------------------------------------------
+# web too many or too few requests
+
+# the following alarms trigger only when there are enough data.
+# we assume there are enough data when:
+#
+#  $5m_2xx_last > 120
+#
+# i.e. when there were at least 120 requests during the 5 minutes starting
+#      at -10m and ending at -5m
+
+template: 5m_2xx_last
+      on: web_log.response_codes
+families: *
+  lookup: average -5m at -5m unaligned of 2xx
+   units: requests
+   every: 30s
+    info: average successful HTTP requests over the last 5 minutes
+
+template: 5m_2xx_now
+      on: web_log.response_codes
+families: *
+  lookup: average -5m unaligned of 2xx
+   units: requests
+   every: 30s
+    info: average successful HTTP requests over the last 5 minutes
+
+template: 5m_requests_ratio
+      on: web_log.response_codes
+families: *
+    calc: ($5m_2xx_last > 0)?($5m_2xx_now * 100 / $5m_2xx_last):(100)
+   units: %
+   every: 30s
+    warn: ($5m_2xx_last > 120) ? ($this > 200 OR $this < 50) : (0)
+    crit: ($5m_2xx_last > 120) ? ($this > 400 OR $this < 25) : (0)
+   delay: down 15m multiplier 1.5 max 1h
+options: no-clear-notification
+    info: the percentage of web requests over the last 5 minutes, \
+          compared with the previous 5 minutes
+      to: webmaster
+
index 7e4fa801f49ec75844256771bdc22593515392cb..96cb4d831f1e58791e0e3e9ecdbf2d26669697a3 100644 (file)
@@ -22,24 +22,45 @@ log_interval: 3600
 # The default for all modules is enabled (yes).
 # Setting any of these to no will disable it.
 
-# apache: yes
 # apache_cache: yes
+# apache: yes
+# bind_rndc: yes
 # cpufreq: yes
+# cpuidle: yes
 # dovecot: yes
+# elasticsearch: yes
+
+# this is just an example
 example: no
+
 # exim: yes
+# fail2ban: yes
+# freeradius: yes
+
+# gunicorn_log has been replaced by web_log
+gunicorn_log: no
+
+# haproxy: yes
 # hddtemp: yes
 # ipfs: yes
 # isc_dhcpd: yes
+# mdstat: yes
 # memcached: yes
 # mysql: yes
 # nginx: yes
-# nginx_log: yes
+
+# nginx_log has been replaced by web_log
+nginx_log: no
+
+# ovpn_status_log: yes
 # phpfpm: yes
 # postfix: yes
+# postgres: yes
 # redis: yes
+# retroshare: yes
 # sensors: yes
+# smartd_log: yes
 # squid: yes
 # tomcat: yes
-# freeradius: yes
-# ovpn_status_log: yes
+# varnish: yes
+# web_log: yes
diff --git a/conf.d/python.d/web_log.conf b/conf.d/python.d/web_log.conf
new file mode 100644 (file)
index 0000000..3b67a8c
--- /dev/null
@@ -0,0 +1,143 @@
+# netdata python.d.plugin configuration for web log
+#
+# 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: 5
+
+# ----------------------------------------------------------------------
+# 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.
+
+# ----------------------------------------------------------------------
+# PLUGIN CONFIGURATION
+#
+# 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: 5       # the JOB's number of restoration attempts
+#
+# Additionally to the above, web_log also supports the following:
+#
+#     path: 'PATH'                        # the path to web server log file
+#     detailed_response_codes: yes/no     # Default: yes. Additional chart where response codes are not grouped
+#     all_time : yes/no                   # Default: yes. All time unique client IPs chart (50000 addresses ~ 400KB)
+#     categories:                         # requests per url chart configuration
+#          cacti: 'cacti.*'               # name(dimension): REGEX to match
+#          observium: 'observium.*'       # name(dimension): REGEX to match
+#          stub_status: 'stub_status'     # name(dimension): REGEX to match
+
+# ----------------------------------------------------------------------
+# WEB SERVER CONFIGURATION
+#
+# Make sure the web server log directory and the web server log files
+# can be read by user 'netdata'.
+#
+# To enable the timings chart and the requests size dimension, the
+# web server needs to log them. This is how to add them:
+#
+# nginx:
+#   log_format netdata '$remote_addr - $remote_user [$time_local] '
+#                      '"$request" $status $body_bytes_sent '
+#                      '$request_length $request_time '
+#                      '"$http_referer" "$http_user_agent"';
+#   access_log /var/log/nginx/access.log netdata;
+#
+# apache (you need mod_logio enabled):
+#   LogFormat "%h %l %u %t \"%r\" %>s %O %I %D \"%{Referer}i\" \"%{User-Agent}i\"" vhost_netdata
+#   LogFormat "%h %l %u %t \"%r\" %>s %O %I %D \"%{Referer}i\" \"%{User-Agent}i\"" netdata
+#   CustomLog "/var/log/apache2/access.log" netdata
+
+# ----------------------------------------------------------------------
+# AUTO-DETECTION JOBS
+# only one of them per web server will run (when they have the same name)
+
+
+# -------------------------------------------
+# nginx log on various distros
+
+# debian, arch
+nginx_log:
+  name: 'nginx'
+  path: '/var/log/nginx/access.log'
+
+# gentoo
+nginx_log2:
+  name: 'nginx'
+  path: '/var/log/nginx/localhost.access_log'
+
+
+# -------------------------------------------
+# apache log on various distros
+
+# debian
+apache_log:
+  name: 'apache'
+  path: '/var/log/apache2/access.log'
+
+# gentoo
+apache_log2:
+  name: 'apache'
+  path: '/var/log/apache2/access_log'
+
+# arch
+apache_log3:
+  name: 'apache'
+  path: '/var/log/httpd/access_log'
+
+# debian
+apache_vhosts_log:
+  name: 'apache_vhosts'
+  path: '/var/log/apache2/other_vhosts_access.log'
+
+
+# -------------------------------------------
+# gunicorn log on various distros
+
+gunicorn_log:
+  name: 'gunicorn'
+  path: '/var/log/gunicorn/access.log'
+
+gunicorn_log2:
+  name: 'gunicorn'
+  path: '/var/log/gunicorn/gunicorn-access.log'
index 7941280eabed1d9969b82943a28c2c67481c64d8..82cad14a01437db27ea1e994aa98e1e9546d6e67 100644 (file)
@@ -1,6 +1,7 @@
 declare -A configs_signatures=(
   ['0056936ce99788ed9ae1c611c87aa6d8']='apps_groups.conf'
   ['0102351817595a85d01ebd54a5f2f36b']='python.d/ovpn_status_log.conf'
+  ['01302e01162d465614276de43fad7546']='python.d.conf'
   ['02fa10fa85ab88e9723998de48d1aca0']='health.d/disks.conf'
   ['036dc300bd7b0e0ef229b9822686d63e']='python.d/isc_dhcpd.conf'
   ['0388b873d0d7e47c19005b7241db77d8']='python.d/tomcat.conf'
@@ -9,6 +10,8 @@ declare -A configs_signatures=(
   ['043f0a35dde85837fabeb85b990a41c1']='health.d/swap.conf'
   ['0529b679d3c0e7e6332753c7f6484731']='health.d/net.conf'
   ['057d12aaff0467e64529e839a258806b']='health.d/entropy.conf'
+  ['059d98d0c562e1c81653d1e64673deab']='python.d/web_log.conf'
+  ['05a8f39f134850c1e8d6267dbe706273']='health.d/web_log.conf'
   ['061c45b0e34170d357e47883166ecf40']='python.d/nginx.conf'
   ['074df527cc70b5f38c0714f08f20e57c']='health.d/apache.conf'
   ['08042325ab27256b938575deafee8ecf']='python.d/nginx.conf'
@@ -145,10 +148,12 @@ declare -A configs_signatures=(
   ['5e6fd588ef6934cf04ddb5e662aa02ea']='health.d/postgres.conf'
   ['5eb670b6fe39da5fec2523d910b0dd1e']='health.d/cpu.conf'
   ['5f05d4b248ab2637ada319b4e8c4e4c3']='python.d/varnish.conf'
+  ['5f109df927d5f20409c81f4bfca0c83e']='python.d/web_log.conf'
   ['5ff1bcaa58695754e2f6980bfe19f579']='health.d/entropy.conf'
   ['61b7ed36f35e7bd930f5f7f91694a112']='charts.d/postfix.conf'
   ['621f10b257a11add5ff5aff41e9662e3']='health.d/memcached.conf'
   ['623771eecb3c277fc728b5304793f93b']='health.d/cpu.conf'
+  ['632c28d714c87a4969d11cf36a5edaa8']='health.d/web_log.conf'
   ['636d032928ea0f4741eab264fb49c099']='apps_groups.conf'
   ['6398ef37a15cb6a0bc921f58948d2b39']='health.d/softnet.conf'
   ['64070d856ab1b47a18ec871e49bbc13b']='python.d/squid.conf'
@@ -157,6 +162,7 @@ declare -A configs_signatures=(
   ['64c48f9726ab987baec9c617a9fef7a6']='health.d/nginx.conf'
   ['64ffc1b6878c81b87564b0f48642c790']='health.d/elasticsearch.conf'
   ['650b5fc9da23b25ee7ee1481e4aa2851']='health_alarm_notify.conf'
+  ['653e0c014c8fcfb4db6cd3351d87d720']='python.d.conf'
   ['6546909d10cc5efcef9dd873bea85956']='python.d/mysql.conf'
   ['65c6933a17fb6b7f8e6baeab73431c17']='charts.d/apcupsd.conf'
   ['6608c6546b3c6bde084fc1d34b1163c1']='health.d/retroshare.conf'
@@ -167,16 +173,19 @@ declare -A configs_signatures=(
   ['6a47af861ad3dd112124c37fbf09672b']='apps_groups.conf'
   ['6b39de5d85db45115db236347a6896d4']='health.d/named.conf'
   ['6b917300747e7e8314844237e2462261']='python.d/apache_cache.conf'
+  ['6bb278bd9e171c4cb5c0fe639231288b']='python.d/web_log.conf'
   ['6bf0de6e3b251b765b10a71d8c5c319d']='python.d/apache.conf'
   ['6c9f2f0abe49a6f1a69db052ebcef1bf']='python.d/elasticsearch.conf'
   ['6ca08ea2a238cad26578b8b85edae160']='health.d/udp_errors.conf'
   ['6cba40e32a7e98a98c31a209913839cc']='python.d/nginx_log.conf'
   ['6d02c2dd0863e09ad9dbba53e3b58116']='health.d/mysql.conf'
   ['6ea958ca521e0514af57c08b518d8c5c']='health.d/backend.conf'
+  ['6f303ccfdc21c7b122758cea8c15e249']='python.d.conf'
   ['70105b1744a8e13f49083d7f1981aea2']='python.d/ipfs.conf'
   ['707a63f53f4b32e01d134ae90ba94aad']='health_alarm_notify.conf'
   ['707a63f53f4b32e01d134ae90ba94aad']='health_email_recipients.conf'
   ['70d82dabecb09a1da4684f293abef0c9']='health_alarm_notify.conf'
+  ['729b3e24a72f7d566fd429617d51a21b']='health.d/web_log.conf'
   ['73125ae64d5c6e9361944cd9bd14844e']='python.d/exim.conf'
   ['731a1fcfe9b2da1b9d685056a59541b8']='python.d/hddtemp.conf'
   ['73a8e10dfe4183aca751e9e2a80dabe3']='node.d.conf'
@@ -236,6 +245,7 @@ declare -A configs_signatures=(
   ['99b6030ce25c8fee4598179c0f95fb0b']='health.d/redis.conf'
   ['99c1617448abbdc493976ab9bda5ce02']='apps_groups.conf'
   ['9a8a459a3841b78d4c6ef07428ad2fe1']='health.d/entropy.conf'
+  ['9b6eee7f2febb29efac2b7ea9fcab9be']='charts.d/nut.conf'
   ['9c0185ceff15415bc59b2ce2c1f04367']='apps_groups.conf'
   ['9c8ddfa810d83ae58c8614ee5229e66b']='health.d/disks.conf'
   ['9c981c75bdf4b1637f7113e7e45eb2bf']='health.d/memcached.conf'
@@ -293,6 +303,7 @@ declare -A configs_signatures=(
   ['b8969be5b3ceb4a99477937119bd4323']='python.d.conf'
   ['b8b87574fd496a66ede884c5336493bd']='python.d/phpfpm.conf'
   ['b915126262d08aa9da81de539a58a3fb']='python.d/redis.conf'
+  ['ba11ea2d2f632b2de4b1224bcdc54f07']='python.d/smartd_log.conf'
   ['bb51112d01ff20053196a57632df8962']='apps_groups.conf'
   ['bba2f3886587f137ea08a6e63dd3d376']='python.d.conf'
   ['bda5517ea01640cfdfa0a27549619d6a']='health.d/memcached.conf'
@@ -346,6 +357,7 @@ declare -A configs_signatures=(
   ['df7e8044902b5e155fad8430c2ddcfa8']='health.d/fping.conf'
   ['dfd5431b11cf2f3852a40d390c1d5a92']='python.d/varnish.conf'
   ['e0242003fd2e3f9ac1b9314e802ada79']='python.d/hddtemp.conf'
+  ['e0ba3bc216ffc9933b4741dbb6b1f8c8']='health.d/web_log.conf'
   ['e0e96cc47ed61d6492416be5236cd4d3']='python.d/apache_cache.conf'
   ['e2f3388c06726154c10ec22bad5bc7ec']='fping.conf'
   ['e3023092e3b2bbb5351e0fe6682f4fe9']='health_alarm_notify.conf'
@@ -356,6 +368,7 @@ declare -A configs_signatures=(
   ['e734c5951a8764d4d9de046dd7cf7407']='health.d/softnet.conf'
   ['e7bc22a1942cffbd2b1b0cfd119ee328']='health.d/ipfs.conf'
   ['e8ec8046c7007af6ca3e8c51e62c99f8']='health.d/disks.conf'
+  ['eaa7beb935cae9c48a40fb934eb105a7']='health.d/web_log.conf'
   ['eb5168f0b516bc982aac45e59da6e52e']='health.d/nginx.conf'
   ['eb748d6fb69d11b0d29c5794657e206c']='health.d/qos.conf'
   ['ebd0612ccc5807524ebb2b647e3e56c9']='apps_groups.conf'
@@ -364,12 +377,14 @@ declare -A configs_signatures=(
   ['ee5343881744e6a97e6ee5cdd329cfb8']='health.d/retroshare.conf'
   ['ef1861bf5725d91e773cbdba05687597']='python.d.conf'
   ['ef9916ea144878a9f37cbb6b1b29da10']='health.d/squid.conf'
+  ['f1446cb3f1a905ee06defa2aa15ee806']='python.d/web_log.conf'
   ['f2f1b8656f5011e965ac45b818cf668d']='apps_groups.conf'
   ['f42df9f13abfae2426519c6728b34882']='charts.d/example.conf'
   ['f4c5d88c34d3fb853498124177cc77f1']='python.d.conf'
   ['f5736e0b2945182cb659cb0713eff923']='apps_groups.conf'
   ['f66e5236ba1245bb2e5fd99191f114c6']='charts.d/hddtemp.conf'
   ['f6c6656f900ff52d159dca12d624016a']='python.d/postgres.conf'
+  ['f7401a6e7c7d4fe2e0e2be7f7f523275']='health.d/web_log.conf'
   ['f7a99e94231beda85c6254912d8d31c1']='python.d/tomcat.conf'
   ['f82924563e41d99cdae5431f0af69155']='python.d.conf'
   ['f8c30f22df92765e2c0fab3c8174e2fc']='health.d/memcached.conf'
index fd9b0cd1c001f032f0788892b8ff2eb9f8f02e36..1dffbe0f304133bdd1a205da6e3d72c0f2b699d5 100644 (file)
@@ -7,12 +7,16 @@ define([VERSION_MAJOR], [1])
 define([VERSION_MINOR], [5])
 define([VERSION_FIX], [1])
 define([VERSION_NUMBER], VERSION_MAJOR[.]VERSION_MINOR[.]VERSION_FIX)
-define([VERSION_SUFFIX], [_master])
+define([VERSION_SUFFIX], [_rolling])
 
 dnl Set to "1" for a first RPM release of a new version
 PACKAGE_RPM_RELEASE="0.0.$(echo VERSION_SUFFIX | sed s/^_//)"
 
-AC_INIT([netdata], VERSION_NUMBER[]VERSION_SUFFIX)
+# We do not use m4_esyscmd_s to support older autoconf.
+define([VERSION_STRING], m4_esyscmd(git describe 2>/dev/null | sed 's/^v//' | tr -d '\n'))
+m4_ifval(VERSION_STRING, [], [define([VERSION_STRING], VERSION_NUMBER)])
+
+AC_INIT([netdata], VERSION_STRING[]VERSION_SUFFIX)
 
 AM_MAINTAINER_MODE([disable])
 if test x"$USE_MAINTAINER_MODE" = xyes; then
@@ -59,11 +63,13 @@ darwin*)
        LDFLAGS="${LDFLAGS} -framework CoreFoundation -framework IOKit"
        ;;
 *)
+       build_target=linux
        ;;
 esac
 
 AM_CONDITIONAL([FREEBSD], [test x$build_target = xfreebsd])
 AM_CONDITIONAL([MACOS], [test x$build_target = xmacos])
+AM_CONDITIONAL([LINUX], [test x$build_target = xlinux])
 
 AC_ARG_ENABLE(
        [plugin-nfacct],
@@ -143,6 +149,7 @@ AC_CHECK_SIZEOF([void *])
 AC_CANONICAL_HOST
 AC_HEADER_MAJOR
 AC_HEADER_RESOLV
+AC_CHECK_HEADERS_ONCE([sys/prctl.h])
 
 AC_CHECK_LIB([cap], [cap_get_proc, cap_set_proc],
        [AC_CHECK_HEADER(
diff --git a/installer/functions.sh b/installer/functions.sh
new file mode 100644 (file)
index 0000000..02b061d
--- /dev/null
@@ -0,0 +1,318 @@
+# no shebang necessary - this is a library to be sourced
+
+# -----------------------------------------------------------------------------
+# checking the availability of commands
+
+which_cmd() {
+    which "${1}" 2>/dev/null || \
+        command -v "${1}" 2>/dev/null
+}
+
+check_cmd() {
+    which_cmd "${1}" >/dev/null 2>&1 && return 0
+    return 1
+}
+
+
+# -----------------------------------------------------------------------------
+
+setup_terminal() {
+    # Is stderr on the terminal? If not, then fail
+    test -t 2 || return 1
+
+    if check_cmd tput
+    then
+        if [ $(( $(tput colors 2>/dev/null) )) -ge 8 ]
+        then
+            # Enable colors
+            TPUT_RESET="$(tput sgr 0)"
+            TPUT_BLACK="$(tput setaf 0)"
+            TPUT_RED="$(tput setaf 1)"
+            TPUT_GREEN="$(tput setaf 2)"
+            TPUT_YELLOW="$(tput setaf 3)"
+            TPUT_BLUE="$(tput setaf 4)"
+            TPUT_PURPLE="$(tput setaf 5)"
+            TPUT_CYAN="$(tput setaf 6)"
+            TPUT_WHITE="$(tput setaf 7)"
+            TPUT_BGBLACK="$(tput setab 0)"
+            TPUT_BGRED="$(tput setab 1)"
+            TPUT_BGGREEN="$(tput setab 2)"
+            TPUT_BGYELLOW="$(tput setab 3)"
+            TPUT_BGBLUE="$(tput setab 4)"
+            TPUT_BGPURPLE="$(tput setab 5)"
+            TPUT_BGCYAN="$(tput setab 6)"
+            TPUT_BGWHITE="$(tput setab 7)"
+            TPUT_BOLD="$(tput bold)"
+            TPUT_DIM="$(tput dim)"
+            TPUT_UNDERLINED="$(tput smul)"
+            TPUT_BLINK="$(tput blink)"
+            TPUT_INVERTED="$(tput rev)"
+            TPUT_STANDOUT="$(tput smso)"
+            TPUT_BELL="$(tput bel)"
+            TPUT_CLEAR="$(tput clear)"
+        fi
+    fi
+
+    return 0
+}
+setup_terminal
+
+progress() {
+    echo >&2 " --- ${TPUT_DIM}${TPUT_BOLD}${*}${TPUT_RESET} --- "
+}
+
+# -----------------------------------------------------------------------------
+
+netdata_banner() {
+    local   l1="  ^"                                                                            \
+            l2="  |.-.   .-.   .-.   .-.   .-.   .-.   .-.   .-.   .-.   .-.   .-.   .-.   .-"  \
+            l3="  |   '-'   '-'   '-'   '-'   '-'   '-'   '-'   '-'   '-'   '-'   '-'   '-'  "  \
+            l4="  +----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+--->" \
+            sp="                                                                              " \
+            netdata="netdata" start end msg="${*}" chartcolor="${TPUT_DIM}"
+
+    [ ${#msg} -lt ${#netdata} ] && msg="${msg}${sp:0:$(( ${#netdata} - ${#msg}))}"
+    [ ${#msg} -gt $(( ${#l2} - 20 )) ] && msg="${msg:0:$(( ${#l2} - 23 ))}..."
+
+    start="$(( ${#l2} / 2 - 4 ))"
+    [ $(( start + ${#msg} + 4 )) -gt ${#l2} ] && start=$((${#l2} - ${#msg} - 4))
+    end=$(( ${start} + ${#msg} + 4 ))
+
+    echo >&2
+    echo >&2 "${chartcolor}${l1}${TPUT_RESET}"
+    echo >&2 "${chartcolor}${l2:0:start}${sp:0:2}${TPUT_RESET}${TPUT_BOLD}${TPUT_GREEN}${netdata}${TPUT_RESET}${chartcolor}${sp:0:$((end - start - 2 - ${#netdata}))}${l2:end:$((${#l2} - end))}${TPUT_RESET}"
+    echo >&2 "${chartcolor}${l3:0:start}${sp:0:2}${TPUT_RESET}${TPUT_BOLD}${TPUT_CYAN}${msg}${TPUT_RESET}${chartcolor}${sp:0:2}${l3:end:$((${#l2} - end))}${TPUT_RESET}"
+    echo >&2 "${chartcolor}${l4}${TPUT_RESET}"
+    echo >&2
+}
+
+# -----------------------------------------------------------------------------
+# portable service command
+
+service_cmd="$(which_cmd service)"
+systemctl_cmd="$(which_cmd systemctl)"
+service() {
+    local cmd="${1}" action="${2}"
+
+    if [ ! -z "${service_cmd}" ]
+    then
+        run "${service_cmd}" "${cmd}" "${action}"
+        return $?
+    elif [ ! -z "${systemctl_cmd}" ]
+    then
+        run "${systemctl_cmd}" "${action}" "${cmd}"
+        return $?
+    fi
+    return 1
+}
+
+# -----------------------------------------------------------------------------
+
+run_ok() {
+    printf >&2 "${TPUT_BGGREEN}${TPUT_WHITE}${TPUT_BOLD} OK ${TPUT_RESET} ${*} \n\n"
+}
+
+run_failed() {
+    printf >&2 "${TPUT_BGRED}${TPUT_WHITE}${TPUT_BOLD} FAILED ${TPUT_RESET} ${*} \n\n"
+}
+
+run_logfile="/dev/null"
+run() {
+    local user="${USER}" dir="$(basename "${PWD}")" info info_console
+
+    if [ "${UID}" = "0" ]
+        then
+        info="[root ${dir}]# "
+        info_console="[${TPUT_DIM}${dir}${TPUT_RESET}]# "
+    else
+        info="[${user} ${dir}]$ "
+        info_console="[${TPUT_DIM}${dir}${TPUT_RESET}]$ "
+    fi
+
+    printf >> "${run_logfile}" "${info}"
+    printf >> "${run_logfile}" "%q " "${@}"
+    printf >> "${run_logfile}" " ... "
+
+    printf >&2 "${info_console}${TPUT_BOLD}${TPUT_YELLOW}"
+    printf >&2 "%q " "${@}"
+    printf >&2 "${TPUT_RESET}\n"
+
+    "${@}"
+
+    local ret=$?
+    if [ ${ret} -ne 0 ]
+        then
+        run_failed
+        printf >> "${run_logfile}" "FAILED with exit code ${ret}\n"
+    else
+        run_ok
+        printf >> "${run_logfile}" "OK\n"
+    fi
+
+    return ${ret}
+}
+
+portable_add_user() {
+    local username="${1}"
+
+    getent passwd "${username}" > /dev/null 2>&1
+    [ $? -eq 0 ] && echo >&2 "User '${username}' already exists." && return 0
+
+    echo >&2 "Adding ${username} user account ..."
+
+    local nologin="$(which nologin 2>/dev/null || command -v nologin 2>/dev/null || echo '/bin/false')"
+
+    # Linux
+    if check_cmd useradd
+    then
+        run useradd -r -g "${username}" -c "${username}" -s "${nologin}" -d / "${username}" && return 0
+    fi
+
+    # FreeBSD
+    if check_cmd pw
+    then
+        run pw useradd "${username}" -d / -g "${username}" -s "${nologin}" && return 0
+    fi
+
+    # BusyBox
+    if check_cmd adduser
+    then
+        run adduser -D -G "${username}" "${username}" && return 0
+    fi
+
+    echo >&2 "Failed to add ${username} user account !"
+
+    return 1
+}
+
+portable_add_group() {
+    local groupname="${1}"
+
+    getent group "${groupname}" > /dev/null 2>&1
+    [ $? -eq 0 ] && echo >&2 "Group '${groupname}' already exists." && return 0
+
+    echo >&2 "Adding ${groupname} user group ..."
+
+    # Linux
+    if check_cmd groupadd
+    then
+        run groupadd -r "${groupname}" && return 0
+    fi
+
+    # FreeBSD
+    if check_cmd pw
+    then
+        run pw groupadd "${groupname}" && return 0
+    fi
+
+    # BusyBox
+    if check_cmd addgroup
+    then
+        run addgroup "${groupname}" && return 0
+    fi
+
+    echo >&2 "Failed to add ${groupname} user group !"
+    return 1
+}
+
+portable_add_user_to_group() {
+    local groupname="${1}" username="${2}"
+
+    getent group "${groupname}" > /dev/null 2>&1
+    [ $? -ne 0 ] && echo >&2 "Group '${groupname}' does not exist." && return 1
+
+    # 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
+        echo >&2 "User '${username}' is already in group '${groupname}'."
+        return 0
+    else
+        # username is not in group
+        echo >&2 "Adding ${username} user to the ${groupname} group ..."
+
+        # Linux
+        if check_cmd usermod
+        then
+            run usermod -a -G "${groupname}" "${username}" && return 0
+        fi
+
+        # FreeBSD
+        if check_cmd pw
+        then
+            run pw groupmod "${groupname}" -m "${username}" && return 0
+        fi
+
+        # BusyBox
+        if check_cmd addgroup
+        then
+            run addgroup "${username}" "${groupname}" && return 0
+        fi
+
+        echo >&2 "Failed to add user ${username} to group ${groupname} !"
+        return 1
+    fi
+}
+
+iscontainer() {
+    # man systemd-detect-virt
+    local cmd=$(which_cmd systemd-detect-virt)
+    if [ ! -z "${cmd}" -a -x "${cmd}" ]
+        then
+        "${cmd}" --container >/dev/null 2>&1 && return 0
+    fi
+
+    # /proc/1/sched exposes the host's pid of our init !
+    # http://stackoverflow.com/a/37016302
+    local pid=$( cat /proc/1/sched | head -n 1 | { IFS='(),#:' read name pid th threads; echo $pid; } )
+    local p=$(( pid + 0 ))
+    [ ${pid} -ne 1 ] && return 0
+
+    # lxc sets environment variable 'container'
+    [ ! -z "${container}" ] && return 0
+
+    # docker creates /.dockerenv
+    # http://stackoverflow.com/a/25518345
+    [ -f "/.dockerenv" ] && return 0
+
+    # ubuntu and debian supply /bin/running-in-container
+    # https://www.apt-browse.org/browse/ubuntu/trusty/main/i386/upstart/1.12.1-0ubuntu4/file/bin/running-in-container
+    if [ -x "/bin/running-in-container" ]
+        then
+        "/bin/running-in-container" >/dev/null 2>&1 && return 0
+    fi
+
+    return 1
+}
+
+issystemd() {
+    local pids p myns ns systemctl
+
+    # if the directory /etc/systemd/system does not exit, it is not systemd
+    [ ! -d /etc/systemd/system ] && return 1
+
+    # if there is no systemctl command, it is not systemd
+    systemctl=$(which systemctl 2>/dev/null || command -v systemctl 2>/dev/null)
+    [ -z "${systemctl}" -o ! -x "${systemctl}" ] && return 1
+
+    # if pid 1 is systemd, it is systemd
+    [ "$(basename $(readlink /proc/1/exe) 2>/dev/null)" = "systemd" ] && return 0
+
+    # if systemd is not running, it is not systemd
+    pids=$(pidof systemd 2>/dev/null)
+    [ -z "${pids}" ] && return 1
+
+    # check if the running systemd processes are not in our namespace
+    myns="$(readlink /proc/self/ns/pid 2>/dev/null)"
+    for p in ${pids}
+    do
+        ns="$(readlink /proc/${p}/ns/pid 2>/dev/null)"
+
+        # if pid of systemd is in our namespace, it is systemd
+        [ ! -z "${myns}" && "${myns}" = "${ns}" ] && return 0
+    done
+
+    # else, it is not systemd
+    return 1
+}
index 9b080caed1d641ca43d26c39714e16ec2217662a..95a02b5ffd6fb3cf37baba296ea2d1ce8c43e1de 100755 (executable)
@@ -10,13 +10,33 @@ if [ "${netdata_source_dir}" != "${installer_dir}" -a "${installer_dir}" != "."
     echo >&2 "Warninng: you are currently in '${netdata_source_dir}' but the installer is in '${installer_dir}'."
 fi
 
+
+# -----------------------------------------------------------------------------
 # reload the user profile
+
 [ -f /etc/profile ] && . /etc/profile
 
 # make sure /etc/profile does not change our current directory
 cd "${netdata_source_dir}" || exit 1
 
+
+# -----------------------------------------------------------------------------
+# load the required functions
+
+if [ -f "${installer_dir}/installer/functions.sh" ]
+    then
+    source "${installer_dir}/installer/functions.sh" || exit 1
+else
+    source "${netdata_source_dir}/installer/functions.sh" || exit 1
+fi
+
+# make sure we save all commands we run
+run_logfile="netdata-installer.log"
+
+
+# -----------------------------------------------------------------------------
 # fix PKG_CHECK_MODULES error
+
 if [ -d /usr/share/aclocal ]
 then
         ACLOCAL_PATH=${ACLOCAL_PATH-/usr/share/aclocal}
@@ -29,7 +49,7 @@ umask 002
 # Be nice on production environments
 renice 19 $$ >/dev/null 2>/dev/null
 
-processors=$(grep ^processor </proc/cpuinfo | wc -l)
+processors=$(grep ^processor </proc/cpuinfo 2>/dev/null | wc -l)
 [ $(( processors )) -lt 1 ] && processors=1
 
 # you can set CFLAGS before running installer
@@ -46,45 +66,7 @@ printf "\n" >>netdata-installer.log
 REINSTALL_PWD="${PWD}"
 REINSTALL_COMMAND="$(printf "%q " "$0" "${@}"; printf "\n")"
 
-banner() {
-    local   l1="  ^"                                                                      \
-            l2="  |.-.   .-.   .-.   .-.   .-.   .-.   .-.   .-.   .-.   .-.   .-.   .-.   .-"  \
-            l3="  |   '-'   '-'   '-'   '-'   '-'   '-'   '-'   '-'   '-'   '-'   '-'   '-'  "  \
-            l4="  +----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+--->" \
-            sp="                                                                        " \
-            netdata="netdata" start end msg="${*}"
-
-    [ ${#msg} -lt ${#netdata} ] && msg="${msg}${sp:0:$(( ${#netdata} - ${#msg}))}"
-    [ ${#msg} -gt $(( ${#l2} - 20 )) ] && msg="${msg:0:$(( ${#l2} - 23 ))}..."
-
-    start="$(( ${#l2} / 2 - 4 ))"
-    [ $(( start + ${#msg} + 4 )) -gt ${#l2} ] && start=$((${#l2} - ${#msg} - 4))
-    end=$(( ${start} + ${#msg} + 4 ))
-
-    echo >&2
-    echo >&2 "${l1}"
-    echo >&2 "${l2:0:start}${sp:0:2}${netdata}${sp:0:$((end - start - 2 - ${#netdata}))}${l2:end:$((${#l2} - end))}"
-    echo >&2 "${l3:0:start}${sp:0:2}${msg}${sp:0:2}${l3:end:$((${#l2} - end))}"
-    echo >&2 "${l4}"
-    echo >&2
-}
-
-service="$(which service 2>/dev/null || command -v service 2>/dev/null)"
-systemctl="$(which systemctl 2>/dev/null || command -v systemctl 2>/dev/null)"
-service() {
-    local cmd="${1}" action="${2}"
-
-    if [ ! -z "${service}" ]
-    then
-        run "${service}" "${cmd}" "${action}"
-        return $?
-    elif [ ! -z "${systemctl}" ]
-    then
-        run "${systemctl}" "${action}" "${cmd}"
-        return $?
-    fi
-    return 1
-}
+setcap="$(which setcap 2>/dev/null || command -v setcap 2>/dev/null)"
 
 ME="$0"
 DONOTSTART=0
@@ -93,7 +75,7 @@ NETDATA_PREFIX=
 LIBS_ARE_HERE=0
 
 usage() {
-    banner "installer command line options"
+    netdata_banner "installer command line options"
     cat <<USAGE
 
 ${ME} <installer options>
@@ -219,66 +201,74 @@ do
     fi
 done
 
-banner "real-time performance monitoring, done right!"
-cat <<BANNER
+netdata_banner "real-time performance monitoring, done right!"
+cat <<BANNER1
 
   You are about to build and install netdata to your system.
 
   It will be installed at these locations:
 
-   - the daemon    at ${NETDATA_PREFIX}/usr/sbin/netdata
-   - config files  at ${NETDATA_PREFIX}/etc/netdata
-   - web files     at ${NETDATA_PREFIX}/usr/share/netdata
-   - plugins       at ${NETDATA_PREFIX}/usr/libexec/netdata
-   - cache files   at ${NETDATA_PREFIX}/var/cache/netdata
-   - db files      at ${NETDATA_PREFIX}/var/lib/netdata
-   - log files     at ${NETDATA_PREFIX}/var/log/netdata
-   - pid file      at ${NETDATA_PREFIX}/var/run
+   - the daemon     at ${TPUT_CYAN}${NETDATA_PREFIX}/usr/sbin/netdata${TPUT_RESET}
+   - config files   in ${TPUT_CYAN}${NETDATA_PREFIX}/etc/netdata${TPUT_RESET}
+   - web files      in ${TPUT_CYAN}${NETDATA_PREFIX}/usr/share/netdata${TPUT_RESET}
+   - plugins        in ${TPUT_CYAN}${NETDATA_PREFIX}/usr/libexec/netdata${TPUT_RESET}
+   - cache files    in ${TPUT_CYAN}${NETDATA_PREFIX}/var/cache/netdata${TPUT_RESET}
+   - db files       in ${TPUT_CYAN}${NETDATA_PREFIX}/var/lib/netdata${TPUT_RESET}
+   - log files      in ${TPUT_CYAN}${NETDATA_PREFIX}/var/log/netdata${TPUT_RESET}
+BANNER1
+
+[ "${UID}" -eq 0 ] && cat <<BANNER2
+   - pid file       at ${TPUT_CYAN}${NETDATA_PREFIX}/var/run/netdata.pid${TPUT_RESET}
+   - logrotate file at ${TPUT_CYAN}/etc/logrotate.d/netdata${TPUT_RESET}
+BANNER2
+
+cat <<BANNER3
 
   This installer allows you to change the installation path.
   Press Control-C and run the same command with --help for help.
 
-BANNER
+BANNER3
 
 if [ "${UID}" -ne 0 ]
     then
     if [ -z "${NETDATA_PREFIX}" ]
         then
-        banner "wrong command line options!"
+        netdata_banner "wrong command line options!"
         cat <<NONROOTNOPREFIX
-
-Sorry! This will fail!
-
-You are attempting to install netdata as non-root, but you plan to install it
-in system paths.
-
-Please set an installation prefix, like this:
-
-    $0 ${@} --install /tmp
-
-or, run the installer as root:
-
-    sudo $0 ${@}
-
-We suggest to install it as root, or certain data collectors will not be able
-to work. Netdata drops root privileges when running. So, if you plan to keep
-it, install it as root to get the full functionality.
-
+  
+  ${TPUT_RED}${TPUT_BOLD}Sorry! This will fail!${TPUT_RESET}
+  
+  You are attempting to install netdata as non-root, but you plan
+  to install it in system paths.
+  
+  Please set an installation prefix, like this:
+  
+      $0 ${@} --install /tmp
+  
+  or, run the installer as root:
+  
+      sudo $0 ${@}
+  
+  We suggest to install it as root, or certain data collectors will
+  not be able to work. Netdata drops root privileges when running.
+  So, if you plan to keep it, install it as root to get the full
+  functionality.
+  
 NONROOTNOPREFIX
         exit 1
 
     else
         cat <<NONROOT
-
-IMPORTANT:
-You are about to install netdata as a non-root user.
-Netdata will work, but a few data collection modules that
-require root access will fail.
-
-If you installing permanently on your system, run the
-installer like this:
-
-    sudo $0 ${@}
+  ${TPUT_RED}${TPUT_BOLD}IMPORTANT${TPUT_RESET}:
+  You are about to install netdata as a non-root user.
+  Netdata will work, but a few data collection modules that
+  require root access will fail.
+  
+  If you installing netdata permanently on your system, run
+  the installer like this:
+  
+     ${TPUT_YELLOW}${TPUT_BOLD}sudo $0 ${@}${TPUT_RESET}
 
 NONROOT
     fi
@@ -317,7 +307,7 @@ then
     then
         echo "Will skip autoreconf step"
     else
-        banner "autotools v2.60 required"
+        netdata_banner "autotools v2.60 required"
         cat <<"EOF"
 
 -------------------------------------------------------------------------------
@@ -344,14 +334,14 @@ if [ ${DONOTWAIT} -eq 0 ]
     then
     if [ ! -z "${NETDATA_PREFIX}" ]
         then
-        read -p "Press ENTER to build and install netdata to '${NETDATA_PREFIX}' > "
+        eval "read >&2 -ep \$'\001${TPUT_BOLD}${TPUT_GREEN}\002Press ENTER to build and install netdata to \'\001${TPUT_CYAN}\002${NETDATA_PREFIX}\001${TPUT_YELLOW}\002\'\001${TPUT_RESET}\002 > ' -e -r REPLY"
     else
-        read -p "Press ENTER to build and install netdata to your system > "
+        eval "read >&2 -ep \$'\001${TPUT_BOLD}${TPUT_GREEN}\002Press ENTER to build and install netdata to your system\001${TPUT_RESET}\002 > ' -e -r REPLY"
     fi
 fi
 
 build_error() {
-    banner "sorry, it failed to build..."
+    netdata_banner "sorry, it failed to build..."
     cat <<EOF
 
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -386,31 +376,6 @@ EOF
     exit 1
 }
 
-run() {
-    printf >>netdata-installer.log "# "
-    printf >>netdata-installer.log "%q " "${@}"
-    printf >>netdata-installer.log " ... "
-
-    printf >&2 "\n"
-    printf >&2 ":-----------------------------------------------------------------------------\n"
-    printf >&2 "Running command (in $(pwd)):\n"
-    printf >&2 "\n"
-    printf >&2 "%q " "${@}"
-    printf >&2 "\n"
-
-    "${@}"
-
-    local ret=$?
-    if [ ${ret} -ne 0 ]
-        then
-        printf >>netdata-installer.log "FAILED!\n"
-    else
-        printf >>netdata-installer.log "OK\n"
-    fi
-
-    return ${ret}
-}
-
 if [ ${LIBS_ARE_HERE} -eq 1 ]
     then
     shift
@@ -423,6 +388,11 @@ fi
 
 trap build_error EXIT
 
+
+# -----------------------------------------------------------------------------
+echo >&2
+progress "Run autotools to configure the build environment"
+
 if [ "$have_autotools" ]
 then
     run ./autogen.sh || exit 1
@@ -438,23 +408,19 @@ run ./configure \
 # remove the build_error hook
 trap - EXIT
 
-if [ -f src/netdata ]
-    then
-    echo >&2 "Cleaning a possibly old compilation ..."
-    run make clean
-fi
+# -----------------------------------------------------------------------------
+progress "Cleanup compilation directory"
+
+[ -f src/netdata ] && run make clean
+
+# -----------------------------------------------------------------------------
+progress "Compile netdata"
 
-echo >&2 "Compiling netdata ..."
 run make -j${processors} || exit 1
 
-if [ "${BASH_VERSINFO[0]}" -ge "4" ]
-then
-    declare -A configs_signatures=()
-    if [ -f "configs.signatures" ]
-        then
-        source "configs.signatures" || echo >&2 "ERROR: Failed to load configs.signatures !"
-    fi
-fi
+
+# -----------------------------------------------------------------------------
+progress "Migrate configuration files for node.d.plugin and charts.d.plugin"
 
 # migrate existing configuration files
 # for node.d and charts.d
@@ -497,6 +463,18 @@ if [ -d "${NETDATA_PREFIX}/etc/netdata" ]
     done
 fi
 
+# -----------------------------------------------------------------------------
+progress "Backup existing netdata configuration before installing it"
+
+if [ "${BASH_VERSINFO[0]}" -ge "4" ]
+then
+    declare -A configs_signatures=()
+    if [ -f "configs.signatures" ]
+        then
+        source "configs.signatures" || echo >&2 "ERROR: Failed to load configs.signatures !"
+    fi
+fi
+
 # backup user configurations
 installer_backup_suffix="${PID}.${RANDOM}"
 for x in $(find "${NETDATA_PREFIX}/etc/netdata/" -name '*.conf' -type f)
@@ -509,7 +487,8 @@ do
         if [ -z "${md5sum}" -o ! -x "${md5sum}" ]
             then
             # we don't have md5sum - keep it
-            cp -p "${x}" "${x}.installer_backup.${installer_backup_suffix}"
+            echo >&2 "File '${TPUT_CYAN}${x}${TPUT_RESET}' ${TPUT_RET}is not known to distribution${TPUT_RESET}. Keeping it."
+            run cp -p "${x}" "${x}.installer_backup.${installer_backup_suffix}"
         else
             # find it relative filename
             f="${x/*\/etc\/netdata\//}"
@@ -528,15 +507,15 @@ do
                 if [ "${configs_signatures[${md5}]}" = "${f}" ]
                 then
                     # it is a stock version - don't keep it
-                    echo >&2 "File '${x}' is stock version."
+                    echo >&2 "File '${TPUT_CYAN}${x}${TPUT_RESET}' is stock version."
                 else
                     # edited by user - keep it
-                    echo >&2 "File '${x}' has been edited by user."
-                    cp -p "${x}" "${x}.installer_backup.${installer_backup_suffix}"
+                    echo >&2 "File '${TPUT_CYAN}${x}${TPUT_RESET}' ${TPUT_RED} has been edited by user${TPUT_RESET}. Keeping it."
+                    run cp -p "${x}" "${x}.installer_backup.${installer_backup_suffix}"
                 fi
             else
-                echo >&2 "File '${x}' cannot be check for custom edits."
-                cp -p "${x}" "${x}.installer_backup.${installer_backup_suffix}"
+                echo >&2 "File '${TPUT_CYAN}${x}${TPUT_RESET}' ${TPUT_RET}cannot be checked for custom edits${TPUT_RESET}. Keeping it."
+                run cp -p "${x}" "${x}.installer_backup.${installer_backup_suffix}"
             fi
         fi
 
@@ -546,194 +525,77 @@ do
     fi
 done
 
-echo >&2 "Installing netdata ..."
+
+# -----------------------------------------------------------------------------
+progress "Install netdata"
+
 run make install || exit 1
 
-# restore user configurations
+
+# -----------------------------------------------------------------------------
+progress "Restore user edited netdata configuration files"
+
 for x in $(find "${NETDATA_PREFIX}/etc/netdata/" -name '*.conf' -type f)
 do
     if [ -f "${x}.installer_backup.${installer_backup_suffix}" ]
         then
-        cp -p "${x}.installer_backup.${installer_backup_suffix}" "${x}"
-        rm -f "${x}.installer_backup.${installer_backup_suffix}"
+        run cp -p "${x}.installer_backup.${installer_backup_suffix}" "${x}" && \
+            run rm -f "${x}.installer_backup.${installer_backup_suffix}"
     fi
 done
 
-echo >&2 "Fixing permissions ..."
-
-check_cmd() {
-    which "${1}" >/dev/null 2>&1 && return 0
-    command -v "${1}" >/dev/null 2>&1 && return 0
-    return 1
-}
-
-portable_add_user() {
-    local username="${1}"
-
-    getent passwd "${username}" > /dev/null 2>&1
-    [ $? -eq 0 ] && return 0
-
-    echo >&2 "Adding ${username} user account ..."
-
-    local nologin="$(which nologin 2>/dev/null || command -v nologin 2>/dev/null || echo '/bin/false')"
-
-    # Linux
-    if check_cmd useradd
-    then
-        run useradd -r -g "${username}" -c "${username}" -s "${nologin}" -d / "${username}" && return 0
-    fi
-
-    # FreeBSD
-    if check_cmd pw
-    then
-        run pw useradd "${username}" -d / -g "${username}" -s "${nologin}" && return 0
-    fi
-
-    # BusyBox
-    if check_cmd adduser
-    then
-        run adduser -D -G "${username}" "${username}" && return 0
-    fi
-
-    echo >&2 "Failed to add ${username} user account !"
-
-    return 1
-}
-
-portable_add_group() {
-    local groupname="${1}"
-
-    getent group "${groupname}" > /dev/null 2>&1
-    [ $? -eq 0 ] && return 0
-
-    echo >&2 "Adding ${groupname} user group ..."
-
-    # Linux
-    if check_cmd groupadd
-    then
-        run groupadd -r "${groupname}" && return 0
-    fi
-
-    # FreeBSD
-    if check_cmd pw
-    then
-        run pw groupadd "${groupname}" && return 0
-    fi
-
-    # BusyBox
-    if check_cmd addgroup
-    then
-        run addgroup "${groupname}" && return 0
-    fi
-
-    echo >&2 "Failed to add ${groupname} user group !"
-    return 1
-}
-
-portable_add_user_to_group() {
-    local groupname="${1}" username="${2}"
-
-    getent group "${groupname}" > /dev/null 2>&1
-    [ $? -ne 0 ] && return 1
-
-    # 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 ..."
-
-        # Linux
-        if check_cmd usermod
-        then
-            run usermod -a -G "${groupname}" "${username}" && return 0
-        fi
-
-        # FreeBSD
-        if check_cmd pw
-        then
-            run pw groupmod "${groupname}" -m "${username}" && return 0
-        fi
-
-        # BusyBox
-        if check_cmd addgroup
-        then
-            run addgroup "${username}" "${groupname}" && return 0
-        fi
-
-        echo >&2 "Failed to add user ${username} to group ${groupname} !"
-        return 1
-    fi
-}
-
-iscontainer() {
-    # man systemd-detect-virt
-    local cmd=$(which systemd-detect-virt 2>/dev/null || command -v systemd-detect-virt 2>/dev/null)
-    if [ ! -z "${cmd}" -a -x "${cmd}" ]
-        then
-        "${cmd}" --container >/dev/null 2>&1 && return 0
-    fi
-
-    # /proc/1/sched exposes the host's pid of our init !
-    # http://stackoverflow.com/a/37016302
-    local pid=$( cat /proc/1/sched | head -n 1 | { IFS='(),#:' read name pid th threads; echo $pid; } )
-    local p=$(( pid + 0 ))
-    [ ${pid} -ne 1 ] && return 0
-
-    # lxc sets environment variable 'container'
-    [ ! -z "${container}" ] && return 0
 
-    # docker creates /.dockerenv
-    # http://stackoverflow.com/a/25518345
-    [ -f "/.dockerenv" ] && return 0
+# -----------------------------------------------------------------------------
+progress "Fix generated files permissions"
 
-    # ubuntu and debian supply /bin/running-in-container
-    # https://www.apt-browse.org/browse/ubuntu/trusty/main/i386/upstart/1.12.1-0ubuntu4/file/bin/running-in-container
-    if [ -x "/bin/running-in-container" ]
-        then
-        "/bin/running-in-container" >/dev/null 2>&1 && return 0
-    fi
+run find ./system/ -type f -a \! -name \*.in -a \! -name Makefile\* -a \! -name \*.conf -a \! -name \*.service -a \! -name \*.logrotate -exec chmod 755 {} \;
 
-    return 1
-}
 
-run find ./system/ -type f -a \! -name \*.in -a \! -name Makefile\* -a \! -name \*.conf -a \! -name \*.service -a \! -name \*.logrotate -exec chmod 755 {} \;
+# -----------------------------------------------------------------------------
+progress "Add user netdata to required user groups"
 
 NETDATA_ADDED_TO_DOCKER=0
 NETDATA_ADDED_TO_NGINX=0
 NETDATA_ADDED_TO_VARNISH=0
 NETDATA_ADDED_TO_HAPROXY=0
+NETDATA_ADDED_TO_ADM=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
+    portable_add_user_to_group docker   netdata && NETDATA_ADDED_TO_DOCKER=1
+    portable_add_user_to_group nginx    netdata && NETDATA_ADDED_TO_NGINX=1
     portable_add_user_to_group varnish  netdata && NETDATA_ADDED_TO_VARNISH=1
     portable_add_user_to_group haproxy  netdata && NETDATA_ADDED_TO_HAPROXY=1
+    portable_add_user_to_group adm      netdata && NETDATA_ADDED_TO_ADM=1
+    run_ok
+else
+    run_failed "The installer does not run as root."
+fi
 
+# -----------------------------------------------------------------------------
+progress "Install logrotate configuration for netdata"
+
+if [ ${UID} -eq 0 ]
+    then
     if [ -d /etc/logrotate.d -a ! -f /etc/logrotate.d/netdata ]
         then
-        echo >&2 "Adding netdata logrotate configuration ..."
         run cp system/netdata.logrotate /etc/logrotate.d/netdata
     fi
     
     if [ -f /etc/logrotate.d/netdata ]
         then
-        echo >&2 "Fixing netdata logrotate permissions ..."
         run chmod 644 /etc/logrotate.d/netdata
     fi
 fi
 
 
 # -----------------------------------------------------------------------------
-# load options from the configuration file
+progress "Read installation options from netdata.conf"
 
 # create an empty config if it does not exist
-[ ! -f "${NETDATA_PREFIX}/etc/netdata/netdata.conf" ] && touch "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
+[ ! -f "${NETDATA_PREFIX}/etc/netdata/netdata.conf" ] && \
+    touch "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
 
 # function to extract values from the config file
 config_option() {
@@ -786,17 +648,14 @@ NETDATA_RUN_DIR="${NETDATA_PREFIX}/var/run"
 
 
 # -----------------------------------------------------------------------------
-# prepare the directories
+progress "Fix permissions of netdata directories (using user '${NETDATA_USER}')"
 
-# this is needed if NETDATA_PREFIX is not empty
 if [ ! -d "${NETDATA_RUN_DIR}" ]
     then
-    mkdir -p "${NETDATA_RUN_DIR}" || exit 1
+    # this is needed if NETDATA_PREFIX is not empty
+    run mkdir -p "${NETDATA_RUN_DIR}" || exit 1
 fi
 
-echo >&2
-echo >&2 "Fixing directories (user: ${NETDATA_USER})..."
-
 # --- conf dir ----
 
 for x in "python.d" "charts.d" "node.d"
@@ -853,8 +712,11 @@ if [ ${UID} -eq 0 ]
     setcap_ret=1
     if ! iscontainer
         then
-        run setcap cap_dac_read_search,cap_sys_ptrace+ep "${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin"
-        setcap_ret=$?
+        if [ ! -z "${setcap}" ]
+            then
+            run setcap cap_dac_read_search,cap_sys_ptrace+ep "${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin"
+            setcap_ret=$?
+        fi
 
         if [ ${setcap_ret} -eq 0 ]
             then
@@ -881,33 +743,82 @@ fi
 
 # --- fix #1292 bug ---
 
-[ -d "${NETDATA_PREFIX}/usr/libexec" ] && run chmod a+rX "${NETDATA_PREFIX}/usr/libexec"
+[ -d "${NETDATA_PREFIX}/usr/libexec" ]       && run chmod a+rX "${NETDATA_PREFIX}/usr/libexec"
 [ -d "${NETDATA_PREFIX}/usr/share/netdata" ] && run chmod a+rX "${NETDATA_PREFIX}/usr/share/netdata"
 
 
+
 # -----------------------------------------------------------------------------
-# check if we can re-start netdata
+progress "Install netdata at system init"
 
-if [ ${DONOTSTART} -eq 1 ]
-    then
-    if [ ! -s "${NETDATA_PREFIX}/etc/netdata/netdata.conf" ]
+installed_init_d=0
+install_non_systemd_init() {
+    [ "${UID}" != 0 ] && return 1
+
+    local key="unknown"
+    if [ -f /etc/os-release ]
         then
-        echo >&2 "Generating empty config file in: ${NETDATA_PREFIX}/etc/netdata/netdata.conf"
-        echo "# Get config from http://127.0.0.1:${NETDATA_PORT}/netdata.conf" >"${NETDATA_PREFIX}/etc/netdata/netdata.conf"
+        source /etc/os-release || return 1
+        key="${ID}-${VERSION_ID}"
 
-        if [ "${UID}" -eq 0 ]
+    elif [ -f /etc/centos-release ]
+        then
+        key=$(</etc/centos-release)
+    fi
+
+    if [ -d /etc/init.d -a ! -f /etc/init.d/netdata ]
+        then
+        if [ "${key}" = "gentoo" ]
             then
-            chown "${NETDATA_USER}" "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
+            run cp system/netdata-openrc /etc/init.d/netdata && \
+            run chmod 755 /etc/init.d/netdata && \
+            run rc-update add netdata default && \
+            installed_init_d=1
+        
+        elif [ "${key}" = "ubuntu-12.04" -o "${key}" = "ubuntu-14.04" -o "${key}" = "debian-7" ]
+            then
+            run cp system/netdata-lsb /etc/init.d/netdata && \
+            run chmod 755 /etc/init.d/netdata && \
+            run update-rc.d netdata defaults && \
+            run update-rc.d netdata enable && \
+            installed_init_d=1
+
+        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 && \
+            run chkconfig netdata on && \
+            installed_init_d=1
         fi
-        chmod 0644 "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
     fi
-    banner "is installed now!"
-    echo >&2 "  enjoy real-time performance and health monitoring..."
-    exit 0
+
+    return 0
+}
+
+if [ "${UID}" -eq 0 ]
+    then
+
+    if issystemd
+    then
+        # systemd is running on this system
+
+        if [ ! -f /etc/systemd/system/netdata.service ]
+        then
+            echo >&2 "Installing systemd service..."
+            run cp system/netdata.service /etc/systemd/system/netdata.service && \
+                run systemctl daemon-reload && \
+                run systemctl enable netdata
+        fi
+    else
+        install_non_systemd_init
+    fi
 fi
 
+
 # -----------------------------------------------------------------------------
-# stop a running netdata
+# check if we can re-start netdata
+
+started=0
 
 isnetdata() {
     if [ -d /proc/self ]
@@ -957,7 +868,7 @@ stop_all_netdata() {
 
     myns="$(readlink /proc/self/ns/pid 2>/dev/null)"
 
-    echo >&2 "Stopping a (possibly) running netdata..."
+    # echo >&2 "Stopping a (possibly) running netdata (namespace '${myns}')..."
 
     for p in $(cat "${NETDATA_RUN_DIR}/netdata.pid" 2>/dev/null) \
         $(cat /var/run/netdata.pid 2>/dev/null) \
@@ -973,111 +884,25 @@ stop_all_netdata() {
     done
 }
 
-# -----------------------------------------------------------------------------
-# check for systemd
-
-issystemd() {
-    local pids p myns ns systemctl
-
-    # if the directory /etc/systemd/system does not exit, it is not systemd
-    [ ! -d /etc/systemd/system ] && return 1
-
-    # if there is no systemctl command, it is not systemd
-    systemctl=$(which systemctl 2>/dev/null || command -v systemctl 2>/dev/null)
-    [ -z "${systemctl}" -o ! -x "${systemctl}" ] && return 1
-
-    # if pid 1 is systemd, it is systemd
-    [ "$(basename $(readlink /proc/1/exe) 2>/dev/null)" = "systemd" ] && return 0
-
-    # if systemd is not running, it is not systemd
-    pids=$(pidof systemd 2>/dev/null)
-    [ -z "${pids}" ] && return 1
-
-    # check if the running systemd processes are not in our namespace
-    myns="$(readlink /proc/self/ns/pid 2>/dev/null)"
-    for p in ${pids}
-    do
-        ns="$(readlink /proc/${p}/ns/pid 2>/dev/null)"
-
-        # if pid of systemd is in our namespace, it is systemd
-        [ ! -z "${myns}" && "${myns}" = "${ns}" ] && return 0
-    done
-
-    # else, it is not systemd
-    return 1
-}
-
-installed_init_d=0
-install_non_systemd_init() {
-    [ "${UID}" != 0 ] && return 1
-
-    local key="unknown"
-    if [ -f /etc/os-release ]
-        then
-        source /etc/os-release || return 1
-        key="${ID}-${VERSION_ID}"
-
-    elif [ -f /etc/centos-release ]
-        then
-        key=$(</etc/centos-release)
-    fi
-
-    if [ -d /etc/init.d -a ! -f /etc/init.d/netdata ]
+if [ ${DONOTSTART} -eq 1 ]
+    then
+    if [ ! -s "${NETDATA_PREFIX}/etc/netdata/netdata.conf" ]
         then
-        if [ "${key}" = "gentoo" ]
-            then
-            run cp system/netdata-openrc /etc/init.d/netdata && \
-            run chmod 755 /etc/init.d/netdata && \
-            run rc-update add netdata default && \
-            installed_init_d=1
-        
-        elif [ "${key}" = "ubuntu-12.04" -o "${key}" = "ubuntu-14.04" -o "${key}" = "debian-7" ]
-            then
-            run cp system/netdata-lsb /etc/init.d/netdata && \
-            run chmod 755 /etc/init.d/netdata && \
-            run update-rc.d netdata defaults && \
-            run update-rc.d netdata enable && \
-            installed_init_d=1
+        echo "# Get config from http://127.0.0.1:${NETDATA_PORT}/netdata.conf" >"${NETDATA_PREFIX}/etc/netdata/netdata.conf"
 
-        elif [ "${key}" = "CentOS release 6.8 (Final)" -o "${key}" = "amzn-2016.09" ]
+        if [ "${UID}" -eq 0 ]
             then
-            run cp system/netdata-init-d /etc/init.d/netdata && \
-            run chmod 755 /etc/init.d/netdata && \
-            run chkconfig netdata on && \
-            installed_init_d=1
+            chown "${NETDATA_USER}" "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
         fi
+        chmod 0644 "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
     fi
 
-    return 0
-}
-
-started=0
-if [ "${UID}" -eq 0 ]
-    then
+else
 
-    if issystemd
-    then
-        # systemd is running on this system
+    progress "Start netdata"
 
-        if [ ! -f /etc/systemd/system/netdata.service ]
+    if [ "${UID}" -eq 0 ]
         then
-            echo >&2 "Installing systemd service..."
-            run cp system/netdata.service /etc/systemd/system/netdata.service && \
-                run systemctl daemon-reload && \
-                run systemctl enable netdata
-        else
-            service netdata stop
-        fi
-
-        stop_all_netdata
-        service netdata restart && started=1
-    else
-        install_non_systemd_init
-    fi
-
-    if [ ${started} -eq 0 ]
-    then
-        # check if we can use the system service
         service netdata stop
         stop_all_netdata
         service netdata restart && started=1
@@ -1086,89 +911,88 @@ if [ "${UID}" -eq 0 ]
             service netdata start && started=1
         fi
     fi
-fi
 
-if [ ${started} -eq 0 ]
-then
-    # still not started...
+    if [ ${started} -eq 0 ]
+    then
+        # still not started...
 
-    stop_all_netdata
+        stop_all_netdata
+
+        echo >&2 "Starting netdata..."
+        run ${NETDATA_PREFIX}/usr/sbin/netdata -P ${NETDATA_RUN_DIR}/netdata.pid "${@}"
+        if [ $? -ne 0 ]
+            then
+            echo >&2
+            echo >&2 "SORRY! FAILED TO START NETDATA!"
+            exit 1
+        else
+            echo >&2 "OK. NetData Started!"
+        fi
 
-    echo >&2 "Starting netdata..."
-    run ${NETDATA_PREFIX}/usr/sbin/netdata -P ${NETDATA_RUN_DIR}/netdata.pid "${@}"
-    if [ $? -ne 0 ]
-        then
         echo >&2
-        echo >&2 "SORRY! FAILED TO START NETDATA!"
-        exit 1
-    else
-        echo >&2 "OK. NetData Started!"
     fi
 
-    echo >&2
-fi
-
-# -----------------------------------------------------------------------------
-# save a config file, if it is not already there
+    # -----------------------------------------------------------------------------
+    # save a config file, if it is not already there
 
-if [ ! -s "${NETDATA_PREFIX}/etc/netdata/netdata.conf" ]
-    then
-    echo >&2
-    echo >&2 "-------------------------------------------------------------------------------"
-    echo >&2
-    echo >&2 "Downloading default configuration from netdata..."
-    sleep 5
-
-    # remove a possibly obsolete download
-    [ -f "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" ] && rm "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new"
+    if [ ! -s "${NETDATA_PREFIX}/etc/netdata/netdata.conf" ]
+        then
+        echo >&2
+        echo >&2 "-------------------------------------------------------------------------------"
+        echo >&2
+        echo >&2 "Downloading default configuration from netdata..."
+        sleep 5
 
-    # disable a proxy to get data from the local netdata
-    export http_proxy=
-    export https_proxy=
+        # remove a possibly obsolete download
+        [ -f "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" ] && rm "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new"
 
-    # try wget
-    wget 2>/dev/null -O "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" "http://localhost:${NETDATA_PORT}/netdata.conf"
-    ret=$?
+        # disable a proxy to get data from the local netdata
+        export http_proxy=
+        export https_proxy=
 
-    # try curl
-    if [ ${ret} -ne 0 -o ! -s "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" ]
-        then
-        curl -s -o "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" "http://localhost:${NETDATA_PORT}/netdata.conf"
+        # try wget
+        wget 2>/dev/null -O "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" "http://localhost:${NETDATA_PORT}/netdata.conf"
         ret=$?
-    fi
 
-    if [ ${ret} -eq 0 -a -s "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" ]
-        then
-        mv "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
-        echo >&2 "New configuration saved for you to edit at ${NETDATA_PREFIX}/etc/netdata/netdata.conf"
+        # try curl
+        if [ ${ret} -ne 0 -o ! -s "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" ]
+            then
+            curl -s -o "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" "http://localhost:${NETDATA_PORT}/netdata.conf"
+            ret=$?
+        fi
 
-        if [ "${UID}" -eq 0 ]
+        if [ ${ret} -eq 0 -a -s "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" ]
             then
-            chown "${NETDATA_USER}" "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
+            mv "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
+            echo >&2 "New configuration saved for you to edit at ${NETDATA_PREFIX}/etc/netdata/netdata.conf"
+
+            if [ "${UID}" -eq 0 ]
+                then
+                chown "${NETDATA_USER}" "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
+            fi
+            chmod 0664 "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
+        else
+            echo >&2 "Cannnot download configuration from netdata daemon using url 'http://localhost:${NETDATA_PORT}/netdata.conf'"
+            [ -f "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" ] && rm "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new"
         fi
-        chmod 0664 "${NETDATA_PREFIX}/etc/netdata/netdata.conf"
-    else
-        echo >&2 "Cannnot download configuration from netdata daemon using url 'http://localhost:${NETDATA_PORT}/netdata.conf'"
-        [ -f "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new" ] && rm "${NETDATA_PREFIX}/etc/netdata/netdata.conf.new"
     fi
 fi
 
 # -----------------------------------------------------------------------------
-# Check for KSM
+progress "Check KSM (kernel memory deduper)"
 
 ksm_is_available_but_disabled() {
     cat <<KSM1
 
--------------------------------------------------------------------------------
-Memory de-duplication instructions
+${TPUT_BOLD}Memory de-duplication instructions${TPUT_RESET}
 
 You have kernel memory de-duper (called Kernel Same-page Merging,
 or KSM) available, but it is not currently enabled.
 
 To enable it run:
 
-echo 1 >/sys/kernel/mm/ksm/run
-echo 1000 >/sys/kernel/mm/ksm/sleep_millisecs
+    ${TPUT_YELLOW}${TPUT_BOLD}echo 1 >/sys/kernel/mm/ksm/run${TPUT_RESET}
+    ${TPUT_YELLOW}${TPUT_BOLD}echo 1000 >/sys/kernel/mm/ksm/sleep_millisecs${TPUT_RESET}
 
 If you enable it, you will save 40-60% of netdata memory.
 
@@ -1178,8 +1002,7 @@ KSM1
 ksm_is_not_available() {
     cat <<KSM2
 
--------------------------------------------------------------------------------
-Memory de-duplication not present in your kernel
+${TPUT_BOLD}Memory de-duplication not present in your kernel${TPUT_RESET}
 
 It seems you do not have kernel memory de-duper (called Kernel Same-page
 Merging, or KSM) available.
@@ -1202,14 +1025,13 @@ else
 fi
 
 # -----------------------------------------------------------------------------
-# Check for version.txt
+progress "Check version.txt"
 
 if [ ! -s web/version.txt ]
     then
     cat <<VERMSG
 
--------------------------------------------------------------------------------
-Version update check warning
+${TPUT_BOLD}Version update check warning${TPUT_RESET}
 
 The way you downloaded netdata, we cannot find its version. This means the
 Update check on the dashboard, will not work.
@@ -1223,14 +1045,13 @@ VERMSG
 fi
 
 # -----------------------------------------------------------------------------
-# apps.plugin warning
+progress "Check apps.plugin"
 
 if [ "${UID}" -ne 0 ]
     then
     cat <<SETUID_WARNING
 
--------------------------------------------------------------------------------
-apps.plugin needs privileges
+${TPUT_BOLD}apps.plugin needs privileges${TPUT_RESET}
 
 Since you have installed netdata as a normal user, to have apps.plugin collect
 all the needed data, you have to give it the access rights it needs, by running
@@ -1238,14 +1059,14 @@ either of the following sets of commands:
 
 To run apps.plugin with escalated capabilities:
 
-    sudo chown root:${NETDATA_USER} "${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin"
-    sudo chmod 0750 "${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin"
-    sudo setcap cap_dac_read_search,cap_sys_ptrace+ep "${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin"
+    ${TPUT_YELLOW}${TPUT_BOLD}sudo chown root:${NETDATA_USER} \"${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin\"${TPUT_RESET}
+    ${TPUT_YELLOW}${TPUT_BOLD}sudo chmod 0750 \"${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin\"${TPUT_RESET}
+    ${TPUT_YELLOW}${TPUT_BOLD}sudo setcap cap_dac_read_search,cap_sys_ptrace+ep \"${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin\"${TPUT_RESET}
 
 or, to run apps.plugin as root:
 
-    sudo chown root "${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin"
-    sudo chmod 4755 "${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin"
+    ${TPUT_YELLOW}${TPUT_BOLD}sudo chown root \"${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin\"${TPUT_RESET}
+    ${TPUT_YELLOW}${TPUT_BOLD}sudo chmod 4755 \"${NETDATA_PREFIX}/usr/libexec/netdata/plugins.d/apps.plugin\"${TPUT_RESET}
 
 apps.plugin is performing a hard-coded function of data collection for all
 running processes. It cannot be instructed from the netdata daemon to perform
@@ -1255,7 +1076,7 @@ SETUID_WARNING
 fi
 
 # -----------------------------------------------------------------------------
-# Keep un-install info
+progress "Generate netdata-uninstaller.sh"
 
 cat >netdata-uninstaller.sh <<UNINSTALL
 #!/usr/bin/env bash
@@ -1377,37 +1198,40 @@ if [ $? -eq 0 -a "${NETDATA_ADDED_TO_HAPROXY}" = "1" ]
     echo "   gpasswd -d netdata haproxy"
 fi
 
+getent group adm > /dev/null
+if [ $? -eq 0 -a "${NETDATA_ADDED_TO_ADM}" = "1" ]
+    then
+    echo
+    echo "You may also want to remove the netdata user from the adm group"
+    echo "by running:"
+    echo "   gpasswd -d netdata adm"
+fi
+
 
 UNINSTALL
 chmod 750 netdata-uninstaller.sh
 
 # -----------------------------------------------------------------------------
+progress "Basic netdata instructions"
 
 cat <<END
 
-
--------------------------------------------------------------------------------
-
-OK. NetData is installed and it is running.
-
--------------------------------------------------------------------------------
-
-By default netdata listens on all IPs on port ${NETDATA_PORT},
+netdata by default listens on all IPs on port ${NETDATA_PORT},
 so you can access it with:
 
-http://this.machine.ip:${NETDATA_PORT}/
+  ${TPUT_CYAN}${TPUT_BOLD}http://this.machine.ip:${NETDATA_PORT}/${TPUT_RESET}
 
 To stop netdata, just kill it, with:
 
-  killall netdata
+  ${TPUT_YELLOW}${TPUT_BOLD}killall netdata${TPUT_RESET}
 
 To start it, just run it:
 
-  ${NETDATA_PREFIX}/usr/sbin/netdata
+  ${TPUT_YELLOW}${TPUT_BOLD}${NETDATA_PREFIX}/usr/sbin/netdata${TPUT_RESET}
 
 
 END
-echo >&2 "Uninstall script generated: ./netdata-uninstaller.sh"
+echo >&2 "Uninstall script generated: ${TPUT_RED}${TPUT_BOLD}./netdata-uninstaller.sh${TPUT_RESET}"
 
 if [ -d .git ]
     then
@@ -1523,13 +1347,32 @@ update && exit 0
 REINSTALL
     chmod 755 netdata-updater.sh.new
     mv -f netdata-updater.sh.new netdata-updater.sh
-    echo >&2 "Update script generated   : ./netdata-updater.sh"
+    echo >&2 "Update script generated   : ${TPUT_GREEN}${TPUT_BOLD}./netdata-updater.sh${TPUT_RESET}"
+    echo >&2
+    echo >&2 "${TPUT_DIM}${TPUT_BOLD}netdata-updater.sh${TPUT_RESET}${TPUT_DIM} can work from cron. It will trigger an email from cron"
+    echo >&2 "only if it fails (it does not print anything if it can update netdata).${TPUT_RESET}"
+    if [ "${UID}" -eq 0 -a -d "/etc/cron.daily" -a ! -f "/etc/cron.daily/netdata-updater.sh" ]
+        then
+        echo >&2 "${TPUT_DIM}Run this to automatically check and install netdata updates once per day:${TPUT_RESET}"
+        echo >&2
+        echo >&2 "${TPUT_YELLOW}${TPUT_BOLD}ln -s ${PWD}/netdata-updater.sh /etc/cron.daily/netdata-updater.sh${TPUT_RESET}"
+    fi
 elif [ -f "netdata-updater.sh" ]
     then
     rm "netdata-updater.sh"
 fi
 
-banner "is installed and running now!"
+# -----------------------------------------------------------------------------
+echo >&2
+progress "We are done!"
+
+if [ ${started} -eq 1 ]
+    then
+    netdata_banner "is installed and running now!"
+else
+    netdata_banner "is installed now!"
+fi
+
 echo >&2 "  enjoy real-time performance and health monitoring..."
 echo >&2 
 exit 0
index 4694772b278da680d82fc276b5b707aec428b362..d74fbfeac2597ae3908655c1e36990157028c1fb 100644 (file)
@@ -102,8 +102,10 @@ get_changelog_version() {
 get_configure_ac_version() {
   get_staged_file configure.ac
   local v=`sed -n \
-         -e '/define(\[VERSION_\(MINOR\|FIX\)/s/.*\[\([^[]*\)\].*/.\1/p' \
-         -e '/define(\[VERSION_\(MAJOR\|SUFFIX\)/s/.*\[\([^[]*\)\].*/\1/p' \
+         -e '/define(\[VERSION_MAJOR/s/.*\[\([^[]*\)\].*/\1/p' \
+         -e '/define(\[VERSION_MINOR/s/.*\[\([^[]*\)\].*/.\1/p' \
+         -e '/define(\[VERSION_FIX/s/.*\[\([^[]*\)\].*/.\1/p' \
+         -e '/define(\[VERSION_SUFFIX/s/.*\[\([^[]*\)\].*/\1/p' \
          $MYTMP/files/configure.ac | tr -d '\n'`
   if [ ! "$v" ]; then v="No version in configure.ac!"; fi
   echo "$v"
index 6823fce1cbd1c5936835b3b3f0cfe36ad9984b19..f2d641b3b940b655315c21c0537441042abf9d13 100755 (executable)
@@ -135,7 +135,7 @@ then
   fi
 
   echo "Resetting suffix in configure.ac:"
-  sed -i -e 's/define(\[VERSION_SUFFIX\], \[.*])/define([VERSION_SUFFIX], [_master])/' configure.ac
+  sed -i -e 's/define(\[VERSION_SUFFIX\], \[.*])/define([VERSION_SUFFIX], [_rolling])/' configure.ac
   sed -i -e 's:^PACKAGE_RPM_RELEASE=.*:PACKAGE_RPM_RELEASE="0.0.$(echo VERSION_SUFFIX | sed s/^_//)":' configure.ac
 
   echo "Committing new configure.ac:"
index d523f4474b52d01c008af15b015986b6395ec81b..232c00630f6992a29ce296c5bc14679077516470 100755 (executable)
@@ -22,20 +22,39 @@ if [ "${1}" = "install" ]
         "${@}" || exit 1
     }
 
+    download() {
+        local curl="$(which curl 2>/dev/null || command -v curl 2>/dev/null)"
+        [ ! -z "${curl}" ] && run curl -s -L "${1}" && return 0
+
+        local wget="$(which wget 2>/dev/null || command -v wget 2>/dev/null)"
+        [ ! -z "${wget}" ] && run wget -q -O - "${1}" && return 0
+
+        echo >&2 "Cannot find 'curl' or 'wget' in this system." && exit 1
+    }
+
     [ ! -d /usr/src ] && run mkdir -p /usr/src
     [ ! -d /usr/local/bin ] && run mkdir -p /usr/local/bin
 
     run cd /usr/src
 
-    if [ -d fping-ktsaou.git ]
+    if [ -d fping-3.15 ]
         then
-        run cd fping-ktsaou.git
-        run git pull
-    else
-        run git clone https://github.com/ktsaou/fping.git fping-ktsaou.git
-        run cd fping-ktsaou.git
+        run rm -rf fping-3.15 || exit 1
     fi
 
+    download 'https://github.com/schweikert/fping/archive/3.15.tar.gz' | run tar -zxvpf -
+    [ $? -ne 0 ] && exit 1
+    run cd fping-3.15 || exit 1
+
+    #if [ -d fping-ktsaou.git ]
+    #    then
+    #    run cd fping-ktsaou.git
+    #    run git pull
+    #else
+    #    run git clone https://github.com/ktsaou/fping.git fping-ktsaou.git
+    #    run cd fping-ktsaou.git
+    #fi
+
     run ./autogen.sh
     run ./configure --prefix=/usr/local
     run make clean
index b4e6473a6223f09764aa60449e07c73763c73378..126041ab13a55df1bc6a2b959c42e10e8d200e28 100755 (executable)
@@ -67,6 +67,26 @@ try:
 except ImportError:
     msg.fatal('Cannot find yaml library')
 
+try:
+    from collections import OrderedDict
+    ORDERED = True
+    DICT = OrderedDict
+    msg.info('YAML output is ordered')
+except ImportError:
+    ORDERED = False
+    DICT = dict
+    msg.info('YAML output is unordered')
+else:
+    def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
+        class OrderedLoader(Loader):
+            pass
+        def construct_mapping(loader, node):
+           loader.flatten_mapping(node)
+           return object_pairs_hook(loader.construct_pairs(node))
+        OrderedLoader.add_constructor(
+            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
+            construct_mapping)
+        return yaml.load(stream, OrderedLoader)
 
 class PythonCharts(object):
     """
@@ -235,7 +255,7 @@ class PythonCharts(object):
         # check if there are dict in config dict
         many_jobs = False
         for name in config:
-            if type(config[name]) is dict:
+            if isinstance(config[name], DICT):
                 many_jobs = True
                 break
 
@@ -420,7 +440,10 @@ def read_config(path):
     """
     try:
         with open(path, 'r') as stream:
-            config = yaml.load(stream)
+            if ORDERED:
+                config = ordered_load(stream, yaml.SafeLoader)
+            else:
+                config = yaml.load(stream)
     except (OSError, IOError):
         msg.error(str(path), "is not a valid configuration file")
         return None
@@ -477,7 +500,7 @@ def run():
     global DEBUG_FLAG, TRACE_FLAG, BASE_CONFIG
 
     # read configuration file
-    disabled = []
+    disabled = ['nginx_log', 'gunicorn_log']
     configfile = CONFIG_DIR + "python.d.conf"
     msg.PROGRAM = PROGRAM
     msg.info("reading configuration file:", configfile)
index b6ed315742062146143e4df62779fde5066dcf28..d0c581654e49aebd6aa611d8087ceecebf2ef120 100644 (file)
@@ -19,7 +19,6 @@ dist_python_SCRIPTS = \
     exim.chart.py \
     fail2ban.chart.py \
     freeradius.chart.py \
-    gunicorn_log.chart.py \
     haproxy.chart.py \
     hddtemp.chart.py \
     ipfs.chart.py \
@@ -28,7 +27,6 @@ dist_python_SCRIPTS = \
     memcached.chart.py \
     mysql.chart.py \
     nginx.chart.py \
-    nginx_log.chart.py \
     ovpn_status_log.chart.py \
     phpfpm.chart.py \
     postfix.chart.py \
@@ -40,6 +38,7 @@ dist_python_SCRIPTS = \
     smartd_log.chart.py \
     tomcat.chart.py \
     varnish.chart.py \
+    web_log.chart.py \
     python-modules-installer.sh \
     $(NULL)
 
diff --git a/python.d/gunicorn_log.chart.py b/python.d/gunicorn_log.chart.py
deleted file mode 100644 (file)
index 9459636..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-# -*- coding: utf-8 -*-
-# Description: nginx log netdata python.d module
-# Author: Pawel Krupa (paulfantom)
-# Modified for Gunicorn by: Jeff Willette (deltaskelta)
-
-from base import LogService 
-import re
-
-priority = 60000
-retries = 60
-# update_every = 3
-
-ORDER = ['codes']
-CHARTS = {
-    'codes': {
-        'options': [None, 'gunicorn status codes', 'requests/s', 'requests', 'gunicorn_log.codes', 'stacked'],
-        'lines': [
-            ["2xx", None, "incremental"],
-            ["3xx", None, "incremental"],
-            ["4xx", None, "incremental"],
-            ["5xx", None, "incremental"]
-        ]}
-}
-
-
-class Service(LogService):
-    def __init__(self, configuration=None, name=None):
-        LogService.__init__(self, configuration=configuration, name=name)
-        if len(self.log_path) == 0:
-            self.log_path = "/var/log/gunicorn/access.log"
-        self.order = ORDER
-        self.definitions = CHARTS
-        pattern = r'" ([0-9]{3}) '
-        #pattern = r'(?:" )([0-9][0-9][0-9]) ?'
-        self.regex = re.compile(pattern)
-
-    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
-        except (ValueError, AttributeError):
-            return None
-
-        regex = self.regex
-        for line in raw:
-            code = regex.search(line)
-            try:
-                beginning = code.group(1)[0]
-            except AttributeError:
-                continue
-
-            if beginning == '2':
-                data["2xx"] += 1
-            elif beginning == '3':
-                data["3xx"] += 1
-            elif beginning == '4':
-                data["4xx"] += 1
-            elif beginning == '5':
-                data["5xx"] += 1
-
-        return data
diff --git a/python.d/nginx_log.chart.py b/python.d/nginx_log.chart.py
deleted file mode 100644 (file)
index ef964a5..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-# -*- coding: utf-8 -*-
-# Description: nginx log netdata python.d module
-# Author: Pawel Krupa (paulfantom)
-
-from base import LogService
-import re
-
-priority = 60000
-retries = 60
-# update_every = 3
-
-ORDER = ['codes']
-CHARTS = {
-    'codes': {
-        '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"],
-            ["1xx", None, "incremental"],
-            ["other", None, "incremental"]
-        ]}
-}
-
-
-class Service(LogService):
-    def __init__(self, configuration=None, name=None):
-        LogService.__init__(self, configuration=configuration, name=name)
-        if len(self.log_path) == 0:
-            self.log_path = "/var/log/nginx/access.log"
-        self.order = ORDER
-        self.definitions = CHARTS
-        pattern = r'" ([0-9]{3}) ?'
-        #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
-        """
-        try:
-            raw = self._get_raw_data()
-            if raw is None:
-                return None
-            elif not raw:
-                return self.data
-        except (ValueError, AttributeError):
-            return None
-
-        regex = self.regex
-        for line in raw:
-            code = regex.search(line)
-            try:
-                beginning = code.group(1)[0]
-            except AttributeError:
-                continue
-
-            if beginning == '2':
-                self.data["2xx"] += 1
-            elif beginning == '3':
-                self.data["3xx"] += 1
-            elif beginning == '4':
-                self.data["4xx"] += 1
-            elif beginning == '5':
-                self.data["5xx"] += 1
-            elif beginning == '1':
-                self.data["1xx"] += 1
-            else:
-                self.data["other"] += 1
-
-        return self.data
diff --git a/python.d/web_log.chart.py b/python.d/web_log.chart.py
new file mode 100644 (file)
index 0000000..4e77edf
--- /dev/null
@@ -0,0 +1,404 @@
+# -*- coding: utf-8 -*-
+# Description: web log netdata python.d module
+# Author: l2isbad
+
+from base import LogService
+import re
+import bisect
+from os import access, R_OK
+from os.path import getsize
+from collections import namedtuple
+from copy import deepcopy
+try:
+    from itertools import zip_longest
+except ImportError:
+    from itertools import izip_longest as zip_longest
+
+priority = 60000
+retries = 60
+
+ORDER = ['response_codes', 'bandwidth', 'response_time', 'requests_per_url', 'http_method', 'requests_per_ipproto',
+         'clients', 'clients_all']
+CHARTS = {
+    'response_codes': {
+        'options': [None, 'Response Codes', 'requests/s', 'responses', 'web_log.response_codes', 'stacked'],
+        'lines': [
+            ['2xx', '2xx', 'incremental'],
+            ['5xx', '5xx', 'incremental'],
+            ['3xx', '3xx', 'incremental'],
+            ['4xx', '4xx', 'incremental'],
+            ['1xx', '1xx', 'incremental'],
+            ['0xx', 'other', 'incremental'],
+            ['unmatched', 'unmatched', 'incremental']
+        ]},
+    'bandwidth': {
+        'options': [None, 'Bandwidth', 'KB/s', 'bandwidth', 'web_log.bandwidth', 'area'],
+        'lines': [
+            ['resp_length', 'received', 'incremental', 1, 1024],
+            ['bytes_sent', 'sent', 'incremental', -1, 1024]
+        ]},
+    'response_time': {
+        'options': [None, 'Processing Time', 'milliseconds', 'timings', 'web_log.response_time', 'area'],
+        'lines': [
+            ['resp_time_min', 'min', 'incremental', 1, 1000],
+            ['resp_time_max', 'max', 'incremental', 1, 1000],
+            ['resp_time_avg', 'avg', 'incremental', 1, 1000]
+        ]},
+    'clients': {
+        'options': [None, 'Current Poll Unique Client IPs', 'unique ips', 'clients', 'web_log.clients', 'stacked'],
+        'lines': [
+            ['unique_cur_ipv4', 'ipv4', 'incremental', 1, 1],
+            ['unique_cur_ipv6', 'ipv6', 'incremental', 1, 1]
+        ]},
+    'clients_all': {
+        'options': [None, 'All Time Unique Client IPs', 'unique ips', 'clients', 'web_log.clients_all', 'stacked'],
+        'lines': [
+            ['unique_tot_ipv4', 'ipv4', 'absolute', 1, 1],
+            ['unique_tot_ipv6', 'ipv6', 'absolute', 1, 1]
+        ]},
+    'http_method': {
+        'options': [None, 'Requests Per HTTP Method', 'requests/s', 'http methods', 'web_log.http_method', 'stacked'],
+        'lines': [
+        ]},
+    'requests_per_ipproto': {
+        'options': [None, 'Requests Per IP Protocol', 'requests/s', 'ip protocols', 'web_log.requests_per_ipproto',
+                    'stacked'],
+        'lines': [
+            ['req_ipv4', 'ipv4', 'incremental', 1, 1],
+            ['req_ipv6', 'ipv6', 'incremental', 1, 1]
+        ]}
+}
+
+NAMED_URL_PATTERN = namedtuple('URL_PATTERN', ['description', 'pattern'])
+
+
+class Service(LogService):
+    def __init__(self, configuration=None, name=None):
+        LogService.__init__(self, configuration=configuration, name=name)
+        # Variables from module configuration file
+        self.log_path = self.configuration.get('path')
+        self.detailed_response_codes = self.configuration.get('detailed_response_codes', True)
+        self.all_time = self.configuration.get('all_time', True)
+        self.url_pattern = self.configuration.get('categories')  # dict
+        self.regex = None  # will be assigned in 'find_regex' method
+        self.resp_time_func = None  # will be assigned in 'find_regex' method
+        self._get_data = None  # will be assigned in 'check' method.
+        self.order = None  # will be assigned in 'create_*_method' method.
+        self.definitions = None  # will be assigned in 'create_*_method' method.
+        self.detailed_chart = None  # will be assigned in 'create_*_method' method.
+        self.http_method_chart = None  # will be assigned in 'create_*_method' method.
+        # sorted list of unique IPs
+        self.unique_all_time = list()
+        # if there is no new logs this dict  returned to netdata
+        self.data = {'bytes_sent': 0, 'resp_length': 0, 'resp_time_min': 0,
+                     'resp_time_max': 0, 'resp_time_avg': 0, 'unique_cur_ipv4': 0,
+                     'unique_cur_ipv6': 0, '2xx': 0, '5xx': 0, '3xx': 0, '4xx': 0,
+                     '1xx': 0, '0xx': 0, 'unmatched': 0, 'req_ipv4': 0, 'req_ipv6': 0,
+                     'unique_tot_ipv4': 0, 'unique_tot_ipv6': 0}
+
+    def check(self):
+        if not self.log_path:
+            self.error('log path is not specified')
+            return False
+
+        # log_path must be readable
+        if not access(self.log_path, R_OK):
+            self.error('%s not readable or not exist' % self.log_path)
+            return False
+
+        # log_path file should not be empty
+        if not getsize(self.log_path):
+            self.error('%s is empty' % self.log_path)
+            return False
+
+        # Read last line (or first if there is only one line)
+        with open(self.log_path, 'rb') as logs:
+            logs.seek(-2, 2)
+            while logs.read(1) != b'\n':
+                logs.seek(-2, 1)
+                if logs.tell() == 0:
+                    break
+            last_line = logs.readline().decode(encoding='utf-8')
+
+        # Parse last line
+        regex_name = self.find_regex(last_line)
+        if not regex_name:
+            self.error('Can\'t parse %s' % self.log_path)
+            return False
+
+        if regex_name.startswith('acs_'):
+            self.create_access_charts(regex_name)
+            if regex_name == 'acs_default':
+                self.info('Not all data collected. You need to modify LogFormat.')
+            self._get_data = self._get_access_data
+            self.info('Used regex: %s' % regex_name)
+            return True
+        else:
+            # If it's not access_logs.. Not used at the moment
+            return False
+
+    def find_regex(self, last_line):
+        """
+        :param last_line: str: literally last line from log file
+        :return: regex_name
+        It's sad but different web servers has different logs formats
+        We need to find appropriate regex for current log file
+        All logic is do a regex search through the string for all patterns
+        until we find something or fail.
+        """
+        # REGEX: 1.IPv4 address 2.HTTP method 3. URL 4. Response code
+        # 5. Bytes sent 6. Response length 7. Response process time
+        acs_default = re.compile(r'([\da-f.:]+)'
+                                 r' -.*?"([A-Z]+)'
+                                 r' (.*?)"'
+                                 r' ([1-9]\d{2})'
+                                 r' (\d+|-)')
+
+        acs_apache_ext_insert = re.compile(r'([\da-f.:]+)'
+                                           r' -.*?"([A-Z]+)'
+                                           r' (.*?)"'
+                                           r' ([1-9]\d{2})'
+                                           r' (\d+|-)'
+                                           r' (\d+)'
+                                           r' (\d+) ')
+
+        acs_apache_ext_append = re.compile(r'([\da-f.:]+)'
+                                           r' -.*?"([A-Z]+)'
+                                           r' (.*?)"'
+                                           r' ([1-9]\d{2})'
+                                           r' (\d+|-)'
+                                           r' .*?'
+                                           r' (\d+)'
+                                           r' (\d+)'
+                                           r'(?: |$)')
+
+        acs_nginx_ext_insert = re.compile(r'([\da-f.:]+)'
+                                          r' -.*?"([A-Z]+)'
+                                          r' (.*?)"'
+                                          r' ([1-9]\d{2})'
+                                          r' (\d+)'
+                                          r' (\d+)'
+                                          r' (\d\.\d+) ')
+
+        acs_nginx_ext_append = re.compile(r'([\da-f.:]+)'
+                                          r' -.*?"([A-Z]+)'
+                                          r' (.*?)"'
+                                          r' ([1-9]\d{2})'
+                                          r' (\d+)'
+                                          r' .*?'
+                                          r' (\d+)'
+                                          r' (\d\.\d+)')
+
+        r_regex = [acs_apache_ext_insert, acs_apache_ext_append, acs_nginx_ext_insert,
+                   acs_nginx_ext_append, acs_default]
+        r_function = [lambda x: x, lambda x: x, lambda x: x * 1000000, lambda x: x * 1000000, lambda x: x]
+        r_name = ['acs_apache_ext_insert', 'acs_apache_ext_append', 'acs_nginx_ext_insert',
+                  'acs_nginx_ext_append', 'acs_default']
+        regex_function_name = zip(r_regex, r_function, r_name)
+
+        regex_name = None
+        for regex, function, name in regex_function_name:
+            if regex.search(last_line):
+                self.regex = regex
+                self.resp_time_func = function
+                regex_name = name
+                break
+        return regex_name
+
+    def create_access_charts(self, regex_name):
+        """
+        :param regex_name: str: regex name from 'find_regex' method. Ex.: 'apache_extended', 'nginx_extended'
+        :return:
+        Create additional charts depending on the 'find_regex' result (parsed_line) and configuration file
+        1. 'time_response' chart is removed if there is no 'time_response' in logs.
+        2. Other stuff is just remove/add chart depending on yes/no in conf
+        """
+        def find_job_name(override_name, name):
+            """
+            :param override_name: str: 'name' var from configuration file
+            :param name: str: 'job_name' from configuration file
+            :return: str: new job name
+            We need this for dynamic charts. Actually same logic as in python.d.plugin.
+            """
+            add_to_name = override_name or name
+            if add_to_name:
+                return '_'.join(['web_log', re.sub('\s+', '_', add_to_name)])
+            else:
+                return 'web_log'
+
+        self.order = ORDER[:]
+        self.definitions = deepcopy(CHARTS)
+
+        job_name = find_job_name(self.override_name, self.name)
+        self.detailed_chart = 'CHART %s.detailed_response_codes ""' \
+                              ' "Detailed Response Codes" requests/s responses' \
+                              ' web_log.detailed_response_codes stacked 1 %s\n' % (job_name, self.update_every)
+        self.http_method_chart = 'CHART %s.http_method' \
+                                 ' "" "Requests Per HTTP Method" requests/s "http methods"' \
+                                 ' web_log.http_method stacked 2 %s\n' % (job_name, self.update_every)
+
+        # Remove 'request_time' chart from ORDER if request_time not in logs
+        if regex_name == 'acs_default':
+            self.order.remove('response_time')
+        # Remove 'clients_all' chart from ORDER if specified in the configuration
+        if not self.all_time:
+            self.order.remove('clients_all')
+        # Add 'detailed_response_codes' chart if specified in the configuration
+        if self.detailed_response_codes:
+            self.order.append('detailed_response_codes')
+            self.definitions['detailed_response_codes'] = {'options': [None, 'Detailed Response Codes', 'requests/s',
+                                                                       'responses', 'web_log.detailed_response_codes',
+                                                                       'stacked'],
+                                                           'lines': []}
+
+        # Add 'requests_per_url' chart if specified in the configuration
+        if self.url_pattern:
+            self.url_pattern = [NAMED_URL_PATTERN(description=k, pattern=re.compile(v)) for k, v
+                                in self.url_pattern.items()]
+            self.definitions['requests_per_url'] = {'options': [None, 'Requests Per Url', 'requests/s',
+                                                                'urls', 'web_log.requests_per_url', 'stacked'],
+                                                    'lines': [['other_url', 'other', 'incremental']]}
+            for elem in self.url_pattern:
+                self.definitions['requests_per_url']['lines'].append([elem.description, elem.description,
+                                                                      'incremental'])
+                self.data.update({elem.description: 0})
+            self.data.update({'other_url': 0})
+        else:
+            self.order.remove('requests_per_url')
+
+    def add_new_dimension(self, dimension, line_list, chart_string, key):
+        """
+        :param dimension: str: response status code. Ex.: '202', '499'
+        :param line_list: list: Ex.: ['202', '202', 'incremental']
+        :param chart_string: Current string we need to pass to netdata to rebuild the chart
+        :param key: str: CHARTS dict key (chart name). Ex.: 'response_time'
+        :return: str: new chart string = previous + new dimensions
+        """
+        self.data.update({dimension: 0})
+        # SET method check if dim in _dimensions
+        self._dimensions.append(dimension)
+        # UPDATE method do SET only if dim in definitions
+        self.definitions[key]['lines'].append(line_list)
+        chart = chart_string
+        chart += "%s %s\n" % ('DIMENSION', ' '.join(line_list))
+        print(chart)
+        return chart
+
+    def _get_access_data(self):
+        """
+        Parse new log lines
+        :return: dict OR None
+        None if _get_raw_data method fails.
+        In all other cases - dict.
+        """
+        raw = self._get_raw_data()
+        if raw is None:
+            return None
+
+        request_time, unique_current = list(), list()
+        request_counter = {'count': 0, 'sum': 0}
+        ip_address_counter = {'unique_cur_ip': 0}
+        for line in raw:
+            match = self.regex.search(line)
+            if match:
+                match_dict = dict(zip_longest('address method url code sent resp_length resp_time'.split(),
+                                              match.groups()))
+                try:
+                    code = ''.join([match_dict['code'][0], 'xx'])
+                    self.data[code] += 1
+                except KeyError:
+                    self.data['0xx'] += 1
+                # detailed response code
+                if self.detailed_response_codes:
+                    self._get_data_detailed_response_codes(match_dict['code'])
+                # requests per url
+                if self.url_pattern:
+                    self._get_data_per_url(match_dict['url'])
+                # requests per http method
+                self._get_data_http_method(match_dict['method'])
+                # bandwidth sent
+                self.data['bytes_sent'] += int(match_dict['sent'] if '-' not in match_dict['sent'] else 0)
+                # request processing time and bandwidth received
+                if match_dict['resp_length'] and match_dict['resp_time']:
+                    self.data['resp_length'] += int(match_dict['resp_length'])
+                    resp_time = self.resp_time_func(float(match_dict['resp_time']))
+                    bisect.insort_left(request_time, resp_time)
+                    request_counter['count'] += 1
+                    request_counter['sum'] += resp_time
+                # requests per ip proto
+                proto = 'ipv4' if '.' in match_dict['address'] else 'ipv6'
+                self.data['req_' + proto] += 1
+                # unique clients ips
+                if address_not_in_pool(self.unique_all_time, match_dict['address'],
+                                       self.data['unique_tot_ipv4'] + self.data['unique_tot_ipv6']):
+                        self.data['unique_tot_' + proto] += 1
+                if address_not_in_pool(unique_current, match_dict['address'], ip_address_counter['unique_cur_ip']):
+                        self.data['unique_cur_' + proto] += 1
+                        ip_address_counter['unique_cur_ip'] += 1
+            else:
+                self.data['unmatched'] += 1
+        # timings
+        if request_time:
+            self.data['resp_time_min'] += int(request_time[0])
+            self.data['resp_time_avg'] += int(round(float(request_counter['sum']) / request_counter['count']))
+            self.data['resp_time_max'] += int(request_time[-1])
+        return self.data
+
+    def _get_data_detailed_response_codes(self, code):
+        """
+        :param code: str: CODE from parsed line. Ex.: '202, '499'
+        :return:
+        Calls add_new_dimension method If the value is found for the first time
+        """
+        if code not in self.data:
+            chart_string_copy = self.detailed_chart
+            self.detailed_chart = self.add_new_dimension(code, [code, code, 'incremental'],
+                                                         chart_string_copy, 'detailed_response_codes')
+        self.data[code] += 1
+
+    def _get_data_http_method(self, method):
+        """
+        :param method: str: METHOD from parsed line. Ex.: 'GET', 'POST'
+        :return:
+        Calls add_new_dimension method If the value is found for the first time
+        """
+        if method not in self.data:
+            chart_string_copy = self.http_method_chart
+            self.http_method_chart = self.add_new_dimension(method, [method, method, 'incremental'],
+                                                            chart_string_copy, 'http_method')
+        self.data[method] += 1
+
+    def _get_data_per_url(self, url):
+        """
+        :param url: str: URL from parsed line
+        :return:
+        Scan through string looking for the first location where patterns produce a match for all user
+        defined patterns
+        """
+        match = None
+        for elem in self.url_pattern:
+            if elem.pattern.search(url):
+                self.data[elem.description] += 1
+                match = True
+                break
+        if not match:
+            self.data['other_url'] += 1
+
+
+def address_not_in_pool(pool, address, pool_size):
+    """
+    :param pool: list of ip addresses
+    :param address: ip address
+    :param pool_size: current size of pool
+    :return: True if address not in pool. False if address in pool
+    """
+    index = bisect.bisect_left(pool, address)
+    if index < pool_size:
+        if pool[index] == address:
+            return False
+        else:
+            bisect.insort_left(pool, address)
+            return True
+    else:
+        bisect.insort_left(pool, address)
+        return True
index 128b198561d551622f97ead759d6a3b8459e4ea2..af634c0a44e565c9640afc56ade6981e846cfe2e 100644 (file)
@@ -2960,7 +2960,7 @@ static void parse_args(int argc, char **argv)
                     "\n"
                     " netdata apps.plugin %s\n"
                     " Copyright (C) 2016-2017 Costa Tsaousis <costa@tsaousis.gr>\n"
-                    " Released under GNU Public License v3 or later.\n"
+                    " Released under GNU General Public License v3 or later.\n"
                     " All rights reserved.\n"
                     "\n"
                     " This program is a data collector plugin for netdata.\n"
@@ -3109,7 +3109,9 @@ int main(int argc, char **argv) {
         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
         if(setrlimit(RLIMIT_CORE, &rl) != 0)
             info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
+#ifdef HAVE_SYS_PRCTL_H
         prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
+#endif
     }
 #endif /* NETDATA_INTERNAL_CHECKS */
 
index 57bcaaab5d73f28c30552e08c237cc0ed8677996..e3682e87718d6fb2a8e74d78c27d30b54a69b2fa 100644 (file)
@@ -12,6 +12,8 @@ char *global_host_prefix = "";
 int enable_ksm = 1;
 
 volatile sig_atomic_t netdata_exit = 0;
+const char *os_type = NETDATA_OS_TYPE;
+const char *program_version = VERSION;
 
 // ----------------------------------------------------------------------------
 // memory allocation functions that handle failures
index ea129550fa3c95afc96a18e2688722b237503f5e..e781d47bcc830461b0745fe4b0dc66d9167b88e0 100644 (file)
@@ -67,9 +67,9 @@
 #include <syslog.h>
 #include <sys/mman.h>
 
-#if !(defined(__FreeBSD__) || defined(__APPLE__))
+#ifdef HAVE_SYS_PRCTL_H
 #include <sys/prctl.h>
-#endif /* __FreeBSD__ || __APPLE__*/
+#endif
 
 #include <sys/resource.h>
 #include <sys/socket.h>
 
 #if defined(__FreeBSD__)
 #include "plugin_freebsd.h"
+#define NETDATA_OS_TYPE "freebsd"
 #elif defined(__APPLE__)
 #include "plugin_macos.h"
+#define NETDATA_OS_TYPE "macos"
 #else
 #include "plugin_proc.h"
 #include "plugin_proc_diskspace.h"
+#define NETDATA_OS_TYPE "linux"
 #endif /* __FreeBSD__, __APPLE__*/
 
 #include "plugin_tc.h"
@@ -271,6 +274,10 @@ extern pid_t get_system_pid_max(void);
 extern unsigned int hz;
 extern void get_system_HZ(void);
 
+extern volatile sig_atomic_t netdata_exit;
+extern const char *os_type;
+
+extern const char *program_version;
 
 /* fix for alpine linux */
 #ifndef RUSAGE_THREAD
index 95fe4a92cf01b61b45652dbe04aa1ede7f0b6261..4ad0d5e177dfb2633f72843cedd4823d46c9273e 100644 (file)
@@ -42,6 +42,8 @@
 #define MEGA_FACTOR 1048576     // 1024 * 1024
 #define GIGA_FACTOR 1073741824  // 1024 * 1024 * 1024
 
+#define MAX_INT_DIGITS 10 // maximum number of digits for int
+
 // NEEDED BY: do_disk_io
 #define RRD_TYPE_DISK "disk"
 
@@ -141,7 +143,7 @@ int do_freebsd_sysctl(int update_every, usec_t dt) {
 
     // NEEDED BY: do_cpu_cores
     static long *pcpu_cp_time = NULL;
-    char cpuid[8]; // no more than 4 digits expected
+    char cpuid[MAX_INT_DIGITS + 1];
 
     // NEEDED BY: do_all_processes, do_processes
     struct vmtotal vmtotal_data;
@@ -161,7 +163,7 @@ int do_freebsd_sysctl(int update_every, usec_t dt) {
     int numdevs;
     static void *devstat_data = NULL;
     struct devstat *dstat;
-    char disk[DEVSTAT_NAME_LEN + 10 + 1]; // 10 - maximum number of digits for int
+    char disk[DEVSTAT_NAME_LEN + MAX_INT_DIGITS + 1];
     struct cur_dstat {
         collected_number duration_read_ms;
         collected_number duration_write_ms;
@@ -412,40 +414,33 @@ int do_freebsd_sysctl(int update_every, usec_t dt) {
                 error("DISABLED: cpu.cpuXX");
             } else {
                 pcpu_cp_time = reallocz(pcpu_cp_time, sizeof(cp_time) * ncpus);
-
-                for (i = 0; i < ncpus; i++) {
-                    if (unlikely(getsysctl("kern.cp_times", pcpu_cp_time, sizeof(cp_time) * ncpus))) {
-                        do_cpu_cores = 0;
-                        error("DISABLED: cpu.cpuXX");
-                        break;
-                    }
-                    if (unlikely(ncpus > 9999)) {
-                        error("FREEBSD: There are more than 4 digits in cpu cores number");
-                        do_cpu_cores = 0;
-                        error("DISABLED: cpu.cpuXX");
-                        break;
-                    }
-                    snprintfz(cpuid, 8, "cpu%d", i);
-
-                    st = rrdset_find_bytype("cpu", cpuid);
-                    if (unlikely(!st)) {
-                        st = rrdset_create("cpu", cpuid, NULL, "utilization", "cpu.cpu", "Core utilization", "percentage", 1000, update_every, RRDSET_TYPE_STACKED);
-
-                        rrddim_add(st, "user", NULL, 1, 1, RRDDIM_PCENT_OVER_DIFF_TOTAL);
-                        rrddim_add(st, "nice", NULL, 1, 1, RRDDIM_PCENT_OVER_DIFF_TOTAL);
-                        rrddim_add(st, "system", NULL, 1, 1, RRDDIM_PCENT_OVER_DIFF_TOTAL);
-                        rrddim_add(st, "interrupt", NULL, 1, 1, RRDDIM_PCENT_OVER_DIFF_TOTAL);
-                        rrddim_add(st, "idle", NULL, 1, 1, RRDDIM_PCENT_OVER_DIFF_TOTAL);
-                        rrddim_hide(st, "idle");
-                    }
-                    else rrdset_next(st);
-
-                    rrddim_set(st, "user", pcpu_cp_time[i * 5 + 0]);
-                    rrddim_set(st, "nice", pcpu_cp_time[i * 5 + 1]);
-                    rrddim_set(st, "system", pcpu_cp_time[i * 5 + 2]);
-                    rrddim_set(st, "interrupt", pcpu_cp_time[i * 5 + 3]);
-                    rrddim_set(st, "idle", pcpu_cp_time[i * 5 + 4]);
-                    rrdset_done(st);
+                if (unlikely(getsysctl("kern.cp_times", pcpu_cp_time, sizeof(cp_time) * ncpus))) {
+                    do_cpu_cores = 0;
+                    error("DISABLED: cpu.cpuXX");
+                } else {
+                    for (i = 0; i < ncpus; i++) {
+                        snprintfz(cpuid, MAX_INT_DIGITS, "cpu%d", i);
+                        st = rrdset_find_bytype("cpu", cpuid);
+                        if (unlikely(!st)) {
+                            st = rrdset_create("cpu", cpuid, NULL, "utilization", "cpu.cpu", "Core utilization",
+                                               "percentage", 1000, update_every, RRDSET_TYPE_STACKED);
+
+                            rrddim_add(st, "user", NULL, 1, 1, RRDDIM_PCENT_OVER_DIFF_TOTAL);
+                            rrddim_add(st, "nice", NULL, 1, 1, RRDDIM_PCENT_OVER_DIFF_TOTAL);
+                            rrddim_add(st, "system", NULL, 1, 1, RRDDIM_PCENT_OVER_DIFF_TOTAL);
+                            rrddim_add(st, "interrupt", NULL, 1, 1, RRDDIM_PCENT_OVER_DIFF_TOTAL);
+                            rrddim_add(st, "idle", NULL, 1, 1, RRDDIM_PCENT_OVER_DIFF_TOTAL);
+                            rrddim_hide(st, "idle");
+                        } else
+                            rrdset_next(st);
+
+                        rrddim_set(st, "user", pcpu_cp_time[i * 5 + 0]);
+                        rrddim_set(st, "nice", pcpu_cp_time[i * 5 + 1]);
+                        rrddim_set(st, "system", pcpu_cp_time[i * 5 + 2]);
+                        rrddim_set(st, "interrupt", pcpu_cp_time[i * 5 + 3]);
+                        rrddim_set(st, "idle", pcpu_cp_time[i * 5 + 4]);
+                        rrdset_done(st);
+                }
                 }
             }
         }
@@ -1084,9 +1079,6 @@ int do_freebsd_sysctl(int update_every, usec_t dt) {
     if (likely(do_netisr || do_netisr_per_core)) {
         if (unlikely(GETSYSCTL("kern.smp.cpus", ncpus))) {
             common_error = 1;
-        } else if (unlikely(ncpus > 9999)) {
-            error("FREEBSD: There are more than 4 digits in cpu cores number");
-            common_error = 1;
         } else if (unlikely(sysctlbyname("net.isr.workstream", NULL, &netisr_workstream_size, NULL, 0) == -1)) {
             error("FREEBSD: sysctl(net.isr.workstream...) failed: %s", strerror(errno));
             common_error = 1;
index 7f9be80b18002ae3690d2e17ba01fea622df6c5e..ffe4713b2fbead7096b7213f2191fc32be533037 100644 (file)
@@ -1896,14 +1896,35 @@ static inline int health_parse_db_lookup(
     return 1;
 }
 
-static inline char *tabs2spaces(char *s) {
-    char *t = s;
-    while(*t) {
-        if(unlikely(*t == '\t')) *t = ' ';
-        t++;
+static inline char *trim_all_spaces(char *buffer) {
+    char *d = buffer, *s = buffer;
+
+    // skip spaces
+    while(isspace(*s)) s++;
+
+    while(*s) {
+        // copy the non-space part
+        while(*s && !isspace(*s)) *d++ = *s++;
+
+        // add a space if we have to
+        if(*s && isspace(*s)) {
+            *d++ = ' ';
+            s++;
+        }
+
+        // skip spaces
+        while(isspace(*s)) s++;
+    }
+
+    *d = '\0';
+
+    if(d > buffer) {
+        d--;
+        if(isspace(*d)) *d = '\0';
     }
 
-    return s;
+    if(!buffer[0]) return NULL;
+    return buffer;
 }
 
 static inline char *health_source_file(size_t line, const char *path, const char *filename) {
@@ -2003,8 +2024,8 @@ int health_readfile(const char *path, const char *filename) {
         s++;
 
         char *value = s;
-        key = trim(key);
-        value = trim(value);
+        key = trim_all_spaces(key);
+        value = trim_all_spaces(value);
 
         if(!key) {
             error("Health configuration has invalid line %zu of file '%s/%s'. Keyword is empty. Ignoring it.", line, path, filename);
@@ -2030,7 +2051,7 @@ int health_readfile(const char *path, const char *filename) {
 
             rc = callocz(1, sizeof(RRDCALC));
             rc->next_event_id = 1;
-            rc->name = tabs2spaces(strdupz(value));
+            rc->name = strdupz(value);
             rc->hash = simple_hash(rc->name);
             rc->source = health_source_file(line, path, filename);
             rc->green = NAN;
@@ -2053,7 +2074,7 @@ int health_readfile(const char *path, const char *filename) {
                 rrdcalctemplate_free(&localhost, rt);
 
             rt = callocz(1, sizeof(RRDCALCTEMPLATE));
-            rt->name = tabs2spaces(strdupz(value));
+            rt->name = strdupz(value);
             rt->hash_name = simple_hash(rt->name);
             rt->source = health_source_file(line, path, filename);
             rt->green = NAN;
@@ -2072,7 +2093,7 @@ int health_readfile(const char *path, const char *filename) {
 
                     freez(rc->chart);
                 }
-                rc->chart = tabs2spaces(strdupz(value));
+                rc->chart = strdupz(value);
                 rc->hash_chart = simple_hash(rc->chart);
             }
             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
@@ -2136,7 +2157,7 @@ int health_readfile(const char *path, const char *filename) {
 
                     freez(rc->exec);
                 }
-                rc->exec = tabs2spaces(strdupz(value));
+                rc->exec = strdupz(value);
             }
             else if(hash == hash_recipient && !strcasecmp(key, HEALTH_RECIPIENT_KEY)) {
                 if(rc->recipient) {
@@ -2146,7 +2167,7 @@ int health_readfile(const char *path, const char *filename) {
 
                     freez(rc->recipient);
                 }
-                rc->recipient = tabs2spaces(strdupz(value));
+                rc->recipient = strdupz(value);
             }
             else if(hash == hash_units && !strcasecmp(key, HEALTH_UNITS_KEY)) {
                 if(rc->units) {
@@ -2156,7 +2177,7 @@ int health_readfile(const char *path, const char *filename) {
 
                     freez(rc->units);
                 }
-                rc->units = tabs2spaces(strdupz(value));
+                rc->units = strdupz(value);
                 strip_quotes(rc->units);
             }
             else if(hash == hash_info && !strcasecmp(key, HEALTH_INFO_KEY)) {
@@ -2167,7 +2188,7 @@ int health_readfile(const char *path, const char *filename) {
 
                     freez(rc->info);
                 }
-                rc->info = tabs2spaces(strdupz(value));
+                rc->info = strdupz(value);
                 strip_quotes(rc->info);
             }
             else if(hash == hash_delay && !strcasecmp(key, HEALTH_DELAY_KEY)) {
@@ -2190,14 +2211,14 @@ int health_readfile(const char *path, const char *filename) {
 
                     freez(rt->context);
                 }
-                rt->context = tabs2spaces(strdupz(value));
+                rt->context = strdupz(value);
                 rt->hash_context = simple_hash(rt->context);
             }
             else if(hash == hash_families && !strcasecmp(key, HEALTH_FAMILIES_KEY)) {
                 freez(rt->family_match);
                 simple_pattern_free(rt->family_pattern);
 
-                rt->family_match = tabs2spaces(strdupz(value));
+                rt->family_match = strdupz(value);
                 rt->family_pattern = simple_pattern_create(rt->family_match, SIMPLE_PATTERN_EXACT);
             }
             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
@@ -2260,7 +2281,7 @@ int health_readfile(const char *path, const char *filename) {
 
                     freez(rt->exec);
                 }
-                rt->exec = tabs2spaces(strdupz(value));
+                rt->exec = strdupz(value);
             }
             else if(hash == hash_recipient && !strcasecmp(key, HEALTH_RECIPIENT_KEY)) {
                 if(rt->recipient) {
@@ -2270,7 +2291,7 @@ int health_readfile(const char *path, const char *filename) {
 
                     freez(rt->recipient);
                 }
-                rt->recipient = tabs2spaces(strdupz(value));
+                rt->recipient = strdupz(value);
             }
             else if(hash == hash_units && !strcasecmp(key, HEALTH_UNITS_KEY)) {
                 if(rt->units) {
@@ -2280,7 +2301,7 @@ int health_readfile(const char *path, const char *filename) {
 
                     freez(rt->units);
                 }
-                rt->units = tabs2spaces(strdupz(value));
+                rt->units = strdupz(value);
                 strip_quotes(rt->units);
             }
             else if(hash == hash_info && !strcasecmp(key, HEALTH_INFO_KEY)) {
@@ -2291,7 +2312,7 @@ int health_readfile(const char *path, const char *filename) {
 
                     freez(rt->info);
                 }
-                rt->info = tabs2spaces(strdupz(value));
+                rt->info = strdupz(value);
                 strip_quotes(rt->info);
             }
             else if(hash == hash_delay && !strcasecmp(key, HEALTH_DELAY_KEY)) {
@@ -2518,6 +2539,9 @@ void health_alarm_log2json(RRDHOST *host, BUFFER *wb, uint32_t after) {
 }
 
 static inline void health_rrdcalc2json_nolock(BUFFER *wb, RRDCALC *rc) {
+    char value_string[100 + 1];
+    format_value_and_unit(value_string, 100, rc->value, rc->units, -1);
+
     buffer_sprintf(wb,
            "\t\t\"%s.%s\": {\n"
                    "\t\t\t\"id\": %lu,\n"
@@ -2541,6 +2565,7 @@ static inline void health_rrdcalc2json_nolock(BUFFER *wb, RRDCALC *rc) {
                    "\t\t\t\"delay_multiplier\": %f,\n"
                    "\t\t\t\"delay\": %d,\n"
                    "\t\t\t\"delay_up_to_timestamp\": %lu,\n"
+                   "\t\t\t\"value_string\": \"%s\",\n"
            , rc->chart, rc->name
            , (unsigned long)rc->id
            , rc->name
@@ -2563,6 +2588,7 @@ static inline void health_rrdcalc2json_nolock(BUFFER *wb, RRDCALC *rc) {
            , rc->delay_multiplier
            , rc->delay_last
            , (unsigned long)rc->delay_up_to_timestamp
+           , value_string
     );
 
     if(unlikely(rc->options & RRDCALC_FLAG_NO_CLEAR_NOTIFICATION)) {
index fb547e440526a1489b60365203416323c134ccb0..8dcc5d7097142b7fe501b5391749bf18ee2176b4 100644 (file)
@@ -256,7 +256,7 @@ void help(int exitcode) {
             " +----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+--->\n"
             "\n"
             " Copyright (C) 2016-2017, Costa Tsaousis <costa@tsaousis.gr>\n"
-            " Released under GNU Public License v3 or later.\n"
+            " Released under GNU General Public License v3 or later.\n"
             " All rights reserved.\n"
             "\n"
             " Home Page  : https://my-netdata.io\n"
@@ -332,8 +332,7 @@ static const char *verify_required_directory(const char *dir) {
     return dir;
 }
 
-int main(int argc, char **argv)
-{
+int main(int argc, char **argv) {
     char *hostname = "localhost";
     int i, check_config = 0;
     int config_loaded = 0;
@@ -434,8 +433,7 @@ int main(int argc, char **argv)
                     config_set("global", "run as user", optarg);
                     break;
                 case 'v':
-                    // TODO: Outsource version to makefile which can compute version from git.
-                    printf("netdata %s\n", VERSION);
+                    printf("%s %s\n", program_name, program_version);
                     return 0;
                 case 'W':
                     {
@@ -508,6 +506,16 @@ int main(int argc, char **argv)
         }
     }
 
+#ifdef _SC_OPEN_MAX
+    // close all open file descriptors, except the standard ones
+    // the caller may have left open files (lxc-attach has this issue)
+    {
+        int fd;
+        for(fd = (int) (sysconf(_SC_OPEN_MAX) - 1); fd > 2; fd--)
+            if(fd_is_valid(fd)) close(fd);
+    }
+#endif
+
     if(!config_loaded)
         load_config(NULL, 0);
 
@@ -571,9 +579,9 @@ int main(int argc, char **argv)
             if(setrlimit(RLIMIT_CORE, &rl) != 0)
                 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
 
-#if !(defined(__FreeBSD__) || defined(__APPLE__))
+#ifdef HAVE_SYS_PRCTL_H
             prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
-#endif /* __FreeBSD__ || __APPLE__*/
+#endif
         }
 
         // --------------------------------------------------------------------
@@ -748,9 +756,9 @@ int main(int argc, char **argv)
         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
         if(setrlimit(RLIMIT_CORE, &rl) != 0)
             error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
-#if !(defined(__FreeBSD__) || defined(__APPLE__))
+#ifdef HAVE_SYS_PRCTL_H
         prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
-#endif /* __FreeBSD__ || __APPLE__*/
+#endif
     }
 #endif /* NETDATA_INTERNAL_CHECKS */
 
index 49afaef123e7ce6a6546bc763c78ab4f722f14d6..38df0fea44773d213915d7b1a91c83439ad2a9c6 100644 (file)
@@ -1,8 +1,6 @@
 #ifndef NETDATA_MAIN_H
 #define NETDATA_MAIN_H 1
 
-extern volatile sig_atomic_t netdata_exit;
-
 /**
  * This struct contains information about command line options.
  */
index 17774ba2d9a39be1883fba4490ab114acd2c7fee..a6c5cbb6a3c4d54dfba9e8ea03bc2331548f4115 100644 (file)
--- a/src/rrd.c
+++ b/src/rrd.c
@@ -302,9 +302,9 @@ int rrd_memory_mode_id(const char *name)
 
 int rrddim_algorithm_id(const char *name)
 {
-    if(strcmp(name, RRDDIM_INCREMENTAL_NAME) == 0)          return RRDDIM_INCREMENTAL;
-    if(strcmp(name, RRDDIM_ABSOLUTE_NAME) == 0)             return RRDDIM_ABSOLUTE;
-    if(strcmp(name, RRDDIM_PCENT_OVER_ROW_TOTAL_NAME) == 0)         return RRDDIM_PCENT_OVER_ROW_TOTAL;
+    if(strcmp(name, RRDDIM_INCREMENTAL_NAME) == 0)              return RRDDIM_INCREMENTAL;
+    if(strcmp(name, RRDDIM_ABSOLUTE_NAME) == 0)                 return RRDDIM_ABSOLUTE;
+    if(strcmp(name, RRDDIM_PCENT_OVER_ROW_TOTAL_NAME) == 0)     return RRDDIM_PCENT_OVER_ROW_TOTAL;
     if(strcmp(name, RRDDIM_PCENT_OVER_DIFF_TOTAL_NAME) == 0)    return RRDDIM_PCENT_OVER_DIFF_TOTAL;
     return RRDDIM_ABSOLUTE;
 }
@@ -692,11 +692,6 @@ RRDDIM *rrddim_add(RRDSET *st, const char *id, const char *name, long multiplier
             error("File %s does not have the same divisor. Clearing it.", fullfilename);
             memset(rd, 0, size);
         }
-        else if(rd->algorithm != algorithm) {
-            errno = 0;
-            error("File %s does not have the same algorithm. Clearing it.", fullfilename);
-            memset(rd, 0, size);
-        }
         else if(rd->update_every != st->update_every) {
             errno = 0;
             error("File %s does not have the same refresh frequency. Clearing it.", fullfilename);
@@ -714,6 +709,9 @@ RRDDIM *rrddim_add(RRDSET *st, const char *id, const char *name, long multiplier
             // rd = NULL;
             memset(rd, 0, size);
         }
+
+        if(rd->algorithm && rd->algorithm != algorithm)
+            error("File %s does not have the expected algorithm (expected %d '%s', found %d '%s'). Previous values may be wrong.", fullfilename, algorithm, rrddim_algorithm_name(algorithm), rd->algorithm, rrddim_algorithm_name(rd->algorithm));
     }
 
     if(rd) {
index 4bbf61e8db8a87f5bbf4d5cd1bb1e505cbd9c4bd..b886b25fd29954cc695c05349bc51fc6e307de2c 100644 (file)
@@ -85,10 +85,14 @@ void rrd_stats_api_v1_charts(BUFFER *wb)
 
     buffer_sprintf(wb, "{\n"
            "\t\"hostname\": \"%s\""
+        ",\n\t\"version\": \"%s\""
+        ",\n\t\"os\": \"%s\""
         ",\n\t\"update_every\": %d"
         ",\n\t\"history\": %d"
         ",\n\t\"charts\": {"
         , localhost.hostname
+        , program_version
+        , os_type
         , rrd_update_every
         , rrd_default_history_entries
         );
@@ -918,14 +922,14 @@ static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
     else {
         kq[0] = '"';
         sq[0] = '"';
-        if((options & RRDR_OPTION_SECONDS) || (options & RRDR_OPTION_MILLISECONDS)) {
-            dates = JSON_DATES_TIMESTAMP;
-            dates_with_new = 0;
-        }
-        else {
+        if(options & RRDR_OPTION_GOOGLE_JSON) {
             dates = JSON_DATES_JS;
             dates_with_new = 1;
         }
+        else {
+            dates = JSON_DATES_TIMESTAMP;
+            dates_with_new = 0;
+        }
         if( options & RRDR_OPTION_OBJECTSROWS )
             strcpy(pre_date, "      { ");
         else
index bdc1608ed2889087d90f214d41e417d12bf4c6c3..2591799d4c6849a047a68525700b23d3156ea637 100644 (file)
@@ -389,9 +389,9 @@ static inline char *format_value_with_precision_and_unit(char *value_string, siz
             len = snprintfz(value_string, value_string_len, "%0.0Lf", (long double) value);
             trim_zeros = 0;
         }
-        else if(isgreaterequal(abs, 100)) len = snprintfz(value_string, value_string_len, "%0.1Lf", (long double) value);
+        else if(isgreaterequal(abs, 10))  len = snprintfz(value_string, value_string_len, "%0.1Lf", (long double) value);
         else if(isgreaterequal(abs, 1))   len = snprintfz(value_string, value_string_len, "%0.2Lf", (long double) value);
-        else if(isgreaterequal(abs, 0.1)) len = snprintfz(value_string, value_string_len, "%0.3Lf", (long double) value);
+        else if(isgreaterequal(abs, 0.1)) len = snprintfz(value_string, value_string_len, "%0.2Lf", (long double) value);
         else                              len = snprintfz(value_string, value_string_len, "%0.4Lf", (long double) value);
 
         if(unlikely(trim_zeros)) {
index 396cf0be836e828b2c7359d3deafd847ba2f8001..6d1130239fc259770bd880ef1fe885727194d115 100644 (file)
@@ -44,7 +44,7 @@ dist_weblib_DATA = \
        lib/d3-3.5.17.min.js \
        lib/dygraph-combined-dd74404.js \
        lib/dygraph-smooth-plotter-dd74404.js \
-       lib/gauge-d5260c3.min.js \
+       lib/gauge-1.3.2.min.js \
        lib/jquery-2.2.4.min.js \
        lib/jquery.easypiechart-97b5824.min.js \
        lib/perfect-scrollbar-0.6.15.min.js \
index 02e171d4af7d3c330f722b655a98dcf6f2ef4660..5119a7879918f59fbab60a61dc997a967a598c32 100644 (file)
@@ -1,35 +1,54 @@
+// ----------------------------------------------------------------------------
 // You can set the following variables before loading this script:
-//
-// var netdataNoDygraphs = true;        // do not use dygraph
-// var netdataNoSparklines = true;      // do not use sparkline
-// var netdataNoPeitys = true;          // do not use peity
-// var netdataNoGoogleCharts = true;    // do not use google
-// var netdataNoMorris = true;          // do not use morris
-// var netdataNoEasyPieChart = true;    // do not use easy pie chart
-// var netdataNoGauge = true;           // do not use gauge.js
-// var netdataNoD3 = true;              // do not use D3
-// var netdataNoC3 = true;              // do not use C3
-// var netdataNoBootstrap = true;       // do not load bootstrap
-// var netdataDontStart = true;         // do not start the thread to process the charts
-// var netdataErrorCallback = null;     // Callback function that will be invoked upon error
-// var netdataRegistry = true;          // Update the registry (default disabled)
-// var netdataRegistryCallback = null;  // Callback function that will be invoked with one param,
-//                                         the URLs from the registry
-// var netdataShowHelp = false;         // enable/disable help (default enabled)
-// var netdataShowAlarms = true;        // enable/disable alarms checks and notifications (default disabled)
-//
-// var netdataRegistryAfterMs = 1500    // the time to consult to registry on startup
-//
-// var netdataCallback = null;          // a function to call when netdata is ready
-//                                      // netdata will be running while this is called (call NETDATA.pause to stop it)
-// var netdataPrepCallback = null;      // a callback to be called before netdata does anything else
-//
-// You can also set the default netdata server, using the following.
-// When this variable is not set, we assume the page is hosted on your
-// netdata server already.
-// var netdataServer = "http://yourhost:19999"; // set your NetData server
 
+/*global netdataNoDygraphs           *//* boolean,  disable dygraph charts
+ *                                                  (default: false) */
+/*global netdataNoSparklines         *//* boolean,  disable sparkline charts
+ *                                                  (default: false) */
+/*global netdataNoPeitys             *//* boolean,  disable peity charts
+ *                                                  (default: false) */
+/*global netdataNoGoogleCharts       *//* boolean,  disable google charts
+ *                                                  (default: false) */
+/*global netdataNoMorris             *//* boolean,  disable morris charts
+ *                                                  (default: false) */
+/*global netdataNoEasyPieChart       *//* boolean,  disable easypiechart charts
+ *                                                  (default: false) */
+/*global netdataNoGauge              *//* boolean,  disable gauge.js charts
+ *                                                  (default: false) */
+/*global netdataNoD3                 *//* boolean,  disable d3 charts
+ *                                                  (default: false) */
+/*global netdataNoC3                 *//* boolean,  disable c3 charts
+ *                                                  (default: false) */
+/*global netdataNoBootstrap          *//* boolean,  disable bootstrap - disables help too
+ *                                                  (default: false) */
+/*global netdataDontStart            *//* boolean,  do not start the thread to process the charts
+ *                                                  (default: false) */
+/*global netdataErrorCallback        *//* function, callback to be called when the dashboard encounters an error
+ *                                                  (default: null) */
+/*global netdataRegistry:true        *//* boolean,  use the netdata registry
+ *                                                  (default: false) */
+/*global netdataNoRegistry           *//* boolean,  included only for compatibility with existing custom dashboard
+ *                                                  (obsolete - do not use this any more) */
+/*global netdataRegistryCallback     *//* function, callback that will be invoked with one param: the URLs from the registry
+ *                                                  (default: null) */
+/*global netdataShowHelp:true        *//* boolean,  disable charts help
+ *                                                  (default: true) */
+/*global netdataShowAlarms:true      *//* boolean,  enable alarms checks and notifications
+ *                                                  (default: false) */
+/*global netdataRegistryAfterMs:true *//* ms,       delay registry use at started
+ *                                                  (default: 1500) */
+/*global netdataCallback             *//* function, callback to be called when netdata is ready to start
+ *                                                  (default: null)
+ *                                                  netdata will be running while this is called
+ *                                                  (call NETDATA.pause to stop it) */
+/*global netdataPrepCallback         *//* function, callback to be called before netdata does anything else
+ *                                                  (default: null) */
+/*global netdataServer               *//* string,   the URL of the netdata server to use
+ *                                                  (default: the URL the page is hosted at) */
+
+// ----------------------------------------------------------------------------
 // global namespace
+
 var NETDATA = window.NETDATA || {};
 
 (function(window, document) {
@@ -111,7 +130,7 @@ var NETDATA = window.NETDATA || {};
     NETDATA.peity_js            = NETDATA.serverDefault + 'lib/jquery.peity-3.2.0.min.js';
     NETDATA.sparkline_js        = NETDATA.serverDefault + 'lib/jquery.sparkline-2.1.2.min.js';
     NETDATA.easypiechart_js     = NETDATA.serverDefault + 'lib/jquery.easypiechart-97b5824.min.js';
-    NETDATA.gauge_js            = NETDATA.serverDefault + 'lib/gauge-d5260c3.min.js';
+    NETDATA.gauge_js            = NETDATA.serverDefault + 'lib/gauge-1.3.2.min.js';
     NETDATA.dygraph_js          = NETDATA.serverDefault + 'lib/dygraph-combined-dd74404.js';
     NETDATA.dygraph_smooth_js   = NETDATA.serverDefault + 'lib/dygraph-smooth-plotter-dd74404.js';
     NETDATA.raphael_js          = NETDATA.serverDefault + 'lib/raphael-2.2.4-min.js';
@@ -199,6 +218,29 @@ var NETDATA = window.NETDATA || {};
     if(netdataRegistry === false && typeof netdataRegistryCallback === 'function')
         netdataRegistry = true;
 
+
+    // ----------------------------------------------------------------------------------------------------------------
+    // detect if this is probably a slow device
+
+    var isSlowDeviceResult = undefined;
+    var isSlowDevice = function() {
+        if(isSlowDeviceResult !== undefined)
+            return isSlowDeviceResult;
+
+        try {
+            var ua = navigator.userAgent.toLowerCase();
+
+            var iOS = /ipad|iphone|ipod/.test(ua) && !window.MSStream;
+            var android = /android/.test(ua) && !window.MSStream;
+            isSlowDeviceResult = (iOS === true || android === true);
+        }
+        catch (e) {
+            isSlowDeviceResult = false;
+        }
+
+        return isSlowDeviceResult;
+    };
+
     // ----------------------------------------------------------------------------------------------------------------
     // the defaults for all charts
 
@@ -214,7 +256,7 @@ var NETDATA = window.NETDATA || {};
         before: 0,                      // panning
         after: -600,                    // panning
         pixels_per_point: 1,            // the detail of the chart
-        fill_luminance: 0.8             // luminance of colors in solit areas
+        fill_luminance: 0.8             // luminance of colors in solid areas
     };
 
     // ----------------------------------------------------------------------------------------------------------------
@@ -233,12 +275,12 @@ var NETDATA = window.NETDATA || {};
                                         // new elements we have to check.
 
         auto_refresher_fast_weight: 0,  // this is the current time in ms, spent
-                                        // rendering charts continiously.
+                                        // rendering charts continuously.
                                         // used with .current.fast_render_timeframe
 
         page_is_visible: true,          // when true, this page is visible
 
-        auto_refresher_stop_until: 0,   // timestamp in ms - used internaly, to stop the
+        auto_refresher_stop_until: 0,   // timestamp in ms - used internally, to stop the
                                         // auto-refresher for some time (when a chart is
                                         // performing pan or zoom, we need to stop refreshing
                                         // all other charts, to have the maximum speed for
@@ -252,7 +294,7 @@ var NETDATA = window.NETDATA || {};
         // the current profile
         // we may have many...
         current: {
-            pixels_per_point: 1,        // the minimum pixels per point for all charts
+            pixels_per_point: isSlowDevice()?5:1, // the minimum pixels per point for all charts
                                         // increase this to speed javascript up
                                         // each chart library has its own limit too
                                         // the max of this and the chart library is used
@@ -262,7 +304,7 @@ var NETDATA = window.NETDATA || {};
 
             idle_between_charts: 100,   // ms - how much time to wait between chart updates
 
-            fast_render_timeframe: 200, // ms - render continously until this time of continious
+            fast_render_timeframe: 200, // ms - render continuously until this time of continuous
                                         // rendering has been reached
                                         // this setting is used to make it render e.g. 10
                                         // charts at once, sleep idle_between_charts time
@@ -276,8 +318,8 @@ var NETDATA = window.NETDATA || {};
             idle_lost_focus: 500,       // ms - when the window does not have focus, check
                                         // if focus has been regained, every this time
 
-            global_pan_sync_time: 1000, // ms - when you pan or zoon a chart, the background
-                                        // autorefreshing of charts is paused for this amount
+            global_pan_sync_time: 1000, // ms - when you pan or zoom a chart, the background
+                                        // auto-refreshing of charts is paused for this amount
                                         // of time
 
             sync_selection_delay: 1500, // ms - when you pan or zoom a chart, wait this amount
@@ -294,11 +336,11 @@ var NETDATA = window.NETDATA || {};
 
             update_only_visible: true,  // enable or disable visibility management
 
-            parallel_refresher: true,   // enable parallel refresh of charts
+            parallel_refresher: (isSlowDevice() === false), // enable parallel refresh of charts
 
             concurrent_refreshes: true, // when parallel_refresher is enabled, sync also the charts
 
-            destroy_on_hide: false,     // destroy charts when they are not visible
+            destroy_on_hide: (isSlowDevice() === true), // destroy charts when they are not visible
 
             show_help: netdataShowHelp, // when enabled the charts will show some help
             show_help_delay_show_ms: 500,
@@ -311,7 +353,7 @@ var NETDATA = window.NETDATA || {};
 
             double_click_speed: 500,    // ms - time between clicks / taps to detect double click/tap
 
-            smooth_plot: true,          // enable smooth plot, where possible
+            smooth_plot: (isSlowDevice() === false), // enable smooth plot, where possible
 
             charts_selection_animation_delay: 50, // delay to animate charts when syncing selection
 
@@ -741,7 +783,7 @@ var NETDATA = window.NETDATA || {};
             // find the common min
             var m = min;
             for(var i in t)
-                if(t[i] < m) m = t[i];
+                if(t.hasOwnProperty(i) && t[i] < m) m = t[i];
 
             //state.log('commonMin ' + state.__commonMin + ' updated: ' + m);
             this.latest[name] = m;
@@ -796,7 +838,7 @@ var NETDATA = window.NETDATA || {};
             // find the common max
             var m = max;
             for(var i in t)
-                if(t[i] > m) m = t[i];
+                if(t.hasOwnProperty(i) && t[i] > m) m = t[i];
 
             //state.log('commonMax ' + state.__commonMax + ' updated: ' + m);
             this.latest[name] = m;
@@ -895,8 +937,8 @@ var NETDATA = window.NETDATA || {};
                                 // every time a chart is panned or zoomed
                                 // we set the timestamp here
                                 // then we use it as a sequence number
-                                // to find if other charts are syncronized
-                                // to this timerange
+                                // to find if other charts are synchronized
+                                // to this time-range
 
         master: null,           // the master chart (state), to which all others
                                 // are synchronized
@@ -946,14 +988,12 @@ var NETDATA = window.NETDATA || {};
         // is the given state the master of the global
         // pan and zoom sync?
         isMaster: function(state) {
-            if(this.master === state) return true;
-            return false;
+            return (this.master === state);
         },
 
         // are we currently have a global pan and zoom sync?
         isActive: function() {
-            if(this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0) return true;
-            return false;
+            return (this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0);
         },
 
         // check if a chart, other than the master
@@ -965,10 +1005,7 @@ var NETDATA = window.NETDATA || {};
             //if(state.needsRecreation())
             //  return true;
 
-            if(state.tm.pan_and_zoom_seq === this.seq)
-                return false;
-
-            return true;
+            return (state.tm.pan_and_zoom_seq !== this.seq);
         }
     };
 
@@ -978,18 +1015,14 @@ var NETDATA = window.NETDATA || {};
     // FIXME
     // move color assignment to dimensions, here
 
-    dimensionStatus = function(parent, label, name_div, value_div, color) {
+    var dimensionStatus = function(parent, label, name_div, value_div, color) {
         this.enabled = false;
         this.parent = parent;
         this.label = label;
         this.name_div = null;
         this.value_div = null;
         this.color = NETDATA.themes.current.foreground;
-
-        if(parent.unselected_count === 0)
-            this.selected = true;
-        else
-            this.selected = false;
+        this.selected = (parent.unselected_count === 0);
 
         this.setOptions(name_div, value_div, color);
     };
@@ -1094,7 +1127,7 @@ var NETDATA = window.NETDATA || {};
 
     // ----------------------------------------------------------------------------------------------------------------
 
-    dimensionsVisibility = function(state) {
+    var dimensionsVisibility = function(state) {
         this.state = state;
         this.len = 0;
         this.dimensions = {};
@@ -1149,7 +1182,7 @@ var NETDATA = window.NETDATA || {};
     };
 
     dimensionsVisibility.prototype.selected2BooleanArray = function(array) {
-        var ret = new Array();
+        var ret = [];
         this.selected_count = 0;
         this.unselected_count = 0;
 
@@ -1203,7 +1236,7 @@ var NETDATA = window.NETDATA || {};
     // ----------------------------------------------------------------------------------------------------------------
     // Our state object, where all per-chart values are stored
 
-    chartState = function(element) {
+    var chartState = function(element) {
         var self = $(element);
         this.element = element;
 
@@ -1314,7 +1347,6 @@ var NETDATA = window.NETDATA || {};
         this.override_options = self.data('override-options') || null;  // override options to pass to netdata
 
         this.running = false;                       // boolean - true when the chart is being refreshed now
-        this.validated = false;                     // boolean - has the chart been validated?
         this.enabled = true;                        // boolean - is the chart enabled for refresh?
         this.paused = false;                        // boolean - is the chart paused for any reason?
         this.selected = false;                      // boolean - is the chart shown a selection?
@@ -1331,9 +1363,7 @@ var NETDATA = window.NETDATA || {};
         this.value_decimal_detail = -1;
         var d = self.data('decimal-digits');
         if(typeof d === 'number') {
-            this.value_decimal_detail = 1;
-            while(d-- > 0)
-                this.value_decimal_detail *= 10;
+            this.value_decimal_detail = d;
         }
 
         this.auto = {
@@ -1385,8 +1415,9 @@ var NETDATA = window.NETDATA || {};
         // find the element that needs to be updated
         var refresh_dt_element_name = self.data('dt-element-name') || null; // string - the element to print refresh_dt_ms
 
-        if(refresh_dt_element_name !== null)
+        if(refresh_dt_element_name !== null) {
             this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null;
+        }
         else
             this.refresh_dt_element = null;
 
@@ -1577,10 +1608,7 @@ var NETDATA = window.NETDATA || {};
         };
 
         var isHidden = function() {
-            if(typeof that.___chartIsHidden___ !== 'undefined')
-                return true;
-
-            return false;
+            return (typeof that.___chartIsHidden___ !== 'undefined');
         };
 
         // hide the chart, when it is not visible - called from isVisible()
@@ -1632,10 +1660,7 @@ var NETDATA = window.NETDATA || {};
         };
 
         var canBeRendered = function() {
-            if(isHidden() === true || that.isVisible(true) === false)
-                return false;
-
-            return true;
+            return (isHidden() === false && that.isVisible(true) === true);
         };
 
         // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
@@ -1847,6 +1872,8 @@ var NETDATA = window.NETDATA || {};
                 this.element_legend_childs.resize_handler.onmouseup =
                 this.element_legend_childs.resize_handler.ontouchend =
                     function(e) {
+                        void(e);
+
                         // remove all the hooks
                         document.onmouseup =
                         document.onmousemove =
@@ -1921,10 +1948,7 @@ var NETDATA = window.NETDATA || {};
             if(NETDATA.options.current.sync_selection === false)
                 return false;
 
-            if(NETDATA.globalSelectionSync.dont_sync_before > Date.now())
-                return false;
-
-            return true;
+            return (NETDATA.globalSelectionSync.dont_sync_before <= Date.now());
         };
 
         this.globalSelectionSyncIsMaster = function() {
@@ -1959,7 +1983,7 @@ var NETDATA = window.NETDATA || {};
             var targets = NETDATA.options.targets;
             var len = targets.length;
             while(len--) {
-                st = targets[len];
+                var st = targets[len];
 
                 if(st === this) {
                     if(this.debug === true)
@@ -1978,14 +2002,11 @@ var NETDATA = window.NETDATA || {};
 
         // can the chart participate to the global selection sync as a slave?
         this.globalSelectionSyncIsEligible = function() {
-            if(this.enabled === true
+            return (this.enabled === true
                 && this.library !== null
                 && typeof this.library.setSelection === 'function'
                 && this.isVisible() === true
-                && this.chart_created === true)
-                return true;
-
-            return false;
+                && this.chart_created === true);
         };
 
         // this chart becomes a slave of the global selection sync
@@ -2044,13 +2065,10 @@ var NETDATA = window.NETDATA || {};
         };
 
         this.setSelection = function(t) {
-            if(typeof this.library.setSelection === 'function') {
-                if(this.library.setSelection(this, t) === true)
-                    this.selected = true;
-                else
-                    this.selected = false;
-            }
-            else this.selected = true;
+            if(typeof this.library.setSelection === 'function')
+                this.selected = (this.library.setSelection(this, t) === true);
+            else
+                this.selected = true;
 
             if(this.selected === true && this.debug === true)
                 this.log('selection set to ' + t.toString());
@@ -2060,13 +2078,10 @@ var NETDATA = window.NETDATA || {};
 
         this.clearSelection = function() {
             if(this.selected === true) {
-                if(typeof this.library.clearSelection === 'function') {
-                    if(this.library.clearSelection(this) === true)
-                        this.selected = false;
-                    else
-                        this.selected = true;
-                }
-                else this.selected = false;
+                if(typeof this.library.clearSelection === 'function')
+                    this.selected = (this.library.clearSelection(this) !== true);
+                else
+                    this.selected = false;
 
                 if(this.selected === false && this.debug === true)
                     this.log('selection cleared');
@@ -2079,9 +2094,7 @@ var NETDATA = window.NETDATA || {};
 
         // find if a timestamp (ms) is shown in the current chart
         this.timeIsVisible = function(t) {
-            if(t >= this.data_after && t <= this.data_before)
-                return true;
-            return false;
+            return (t >= this.data_after && t <= this.data_before);
         };
 
         this.calculateRowForTime = function(t) {
@@ -2232,19 +2245,69 @@ var NETDATA = window.NETDATA || {};
             return ret;
         };
 
+        var __legendFormatValueChartDecimalsLastMin = undefined;
+        var __legendFormatValueChartDecimalsLastMax = undefined;
+        var __legendFormatValueChartDecimals = -1;
+        this.legendFormatValueDecimalsFromMinMax = function(min, max) {
+            if(min === __legendFormatValueChartDecimalsLastMin && max === __legendFormatValueChartDecimalsLastMax)
+                return;
+
+            __legendFormatValueChartDecimalsLastMin = min;
+            __legendFormatValueChartDecimalsLastMax = max;
+
+            if(this.data !== null && this.data.min === this.data.max)
+                __legendFormatValueChartDecimals = -1;
+
+            else if(this.value_decimal_detail !== -1)
+                __legendFormatValueChartDecimals = this.value_decimal_detail;
+
+            else {
+                var delta;
+
+                if (min === max)
+                    delta = Math.abs(min);
+                else
+                    delta = Math.abs(max - min);
+
+                if (delta > 1000)     __legendFormatValueChartDecimals = 0;
+                else if (delta > 10)  __legendFormatValueChartDecimals = 1;
+                else if (delta > 1)   __legendFormatValueChartDecimals = 2;
+                else if (delta > 0.1) __legendFormatValueChartDecimals = 2;
+                else                  __legendFormatValueChartDecimals = 4;
+            }
+        };
+
         this.legendFormatValue = function(value) {
-            if(value === null || value === 'undefined') return '-';
-            if(typeof value !== 'number') return value;
-
-            if(this.value_decimal_detail !== -1)
-                return (Math.round(value * this.value_decimal_detail) / this.value_decimal_detail).toLocaleString();
-
-            var abs = Math.abs(value);
-            if(abs >= 1000) return (Math.round(value)).toLocaleString();
-            if(abs >= 100 ) return (Math.round(value * 10) / 10).toLocaleString();
-            if(abs >= 1   ) return (Math.round(value * 100) / 100).toLocaleString();
-            if(abs >= 0.1 ) return (Math.round(value * 1000) / 1000).toLocaleString();
-            return (Math.round(value * 10000) / 10000).toLocaleString();
+            if(typeof value !== 'number') return '-';
+
+            var dmin, dmax;
+
+            if(__legendFormatValueChartDecimals < 0) {
+                dmin = 0;
+                var abs = value;
+                if(abs > 1000)      dmax = 0;
+                else if(abs > 10 )  dmax = 1;
+                else if(abs > 1)    dmax = 2;
+                else if(abs > 0.1)  dmax = 2;
+                else                dmax = 4;
+            }
+            else {
+                dmin = dmax = __legendFormatValueChartDecimals;
+            }
+
+            if(this.value_decimal_detail !== -1) {
+                dmin = dmax = this.value_decimal_detail;
+            }
+
+            return value.toLocaleString(undefined, {
+                // style: 'decimal',
+                // minimumIntegerDigits: 1,
+                // minimumSignificantDigits: 1,
+                // maximumSignificantDigits: 1,
+                useGrouping: true,
+                minimumFractionDigits: dmin,
+                maximumFractionDigits: dmax
+            });
         };
 
         this.legendSetLabelValue = function(label, value) {
@@ -2314,33 +2377,44 @@ var NETDATA = window.NETDATA || {};
             }
         };
 
+        this.legendSetDateLast = {
+            ms: 0,
+            date: undefined,
+            time: undefined
+        };
+
         this.legendSetDate = function(ms) {
             if(typeof ms !== 'number') {
                 this.legendShowUndefined();
                 return;
             }
 
-            var d = new Date(ms);
+            if(this.legendSetDateLast.ms !== ms) {
+                var d = new Date(ms);
+                this.legendSetDateLast.ms = ms;
+                this.legendSetDateLast.date = d.toLocaleDateString();
+                this.legendSetDateLast.time = d.toLocaleTimeString();
+            }
 
-            if(this.element_legend_childs.title_date)
-                this.__legendSetDateString(d.toLocaleDateString());
+            if(this.element_legend_childs.title_date !== null)
+                this.__legendSetDateString(this.legendSetDateLast.date);
 
-            if(this.element_legend_childs.title_time)
-                this.__legendSetTimeString(d.toLocaleTimeString());
+            if(this.element_legend_childs.title_time !== null)
+                this.__legendSetTimeString(this.legendSetDateLast.time);
 
-            if(this.element_legend_childs.title_units)
+            if(this.element_legend_childs.title_units !== null)
                 this.__legendSetUnitsString(this.units)
         };
 
         this.legendShowUndefined = function() {
-            if(this.element_legend_childs.title_date)
+            if(this.element_legend_childs.title_date !== null)
                 this.__legendSetDateString(' ');
 
-            if(this.element_legend_childs.title_time)
+            if(this.element_legend_childs.title_time !== null)
                 this.__legendSetTimeString(this.chart.name);
 
-            if(this.element_legend_childs.title_units)
-                this.__legendSetUnitsString(' ')
+            if(this.element_legend_childs.title_units !== null)
+                this.__legendSetUnitsString(' ');
 
             if(this.data && this.element_legend_childs.series !== null) {
                 var labels = this.data.dimension_names;
@@ -2348,8 +2422,7 @@ var NETDATA = window.NETDATA || {};
                 while(i--) {
                     var label = labels[i];
 
-                    if(typeof label === 'undefined') continue;
-                    if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
+                    if(typeof label === 'undefined' || typeof this.element_legend_childs.series[label] === 'undefined') continue;
                     this.legendSetLabelValue(label, null);
                 }
             }
@@ -2422,8 +2495,8 @@ var NETDATA = window.NETDATA || {};
         this.chartColors = function() {
             if(this.colors !== null) return this.colors;
 
-            this.colors = new Array();
-            this.colors_available = new Array();
+            this.colors = [];
+            this.colors_available = [];
 
             // add the standard colors
             var len = NETDATA.themes.current.colors.length;
@@ -2548,7 +2621,7 @@ var NETDATA = window.NETDATA || {};
                     + state.chart.chart_type
                     + '" style="background-color: '
                     + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')'
-                    + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
+                    + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>';
 
                 var text = document.createTextNode(' ' + name);
                 label.name.appendChild(text);
@@ -2761,16 +2834,19 @@ var NETDATA = window.NETDATA || {};
 
                 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
                 this.element_legend.appendChild(this.element_legend_childs.title_date);
+                this.__last_shown_legend_date = undefined;
 
                 this.element_legend.appendChild(document.createElement('br'));
 
                 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
                 this.element_legend.appendChild(this.element_legend_childs.title_time);
+                this.__last_shown_legend_time = undefined;
 
                 this.element_legend.appendChild(document.createElement('br'));
 
                 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
                 this.element_legend.appendChild(this.element_legend_childs.title_units);
+                this.__last_shown_legend_units = undefined;
 
                 this.element_legend.appendChild(document.createElement('br'));
 
@@ -2789,7 +2865,7 @@ var NETDATA = window.NETDATA || {};
                     placement: 'bottom',
                     title: 'Chart Legend',
                     delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms },
-                    content: 'You can click or tap on the values or the labels to select dimentions. By pressing SHIFT or CONTROL, you can enable or disable multiple dimensions.<br/><small>Help, can be disabled from the settings.</small>'
+                    content: 'You can click or tap on the values or the labels to select dimensions. By pressing SHIFT or CONTROL, you can enable or disable multiple dimensions.<br/><small>Help, can be disabled from the settings.</small>'
                 });
             }
             else {
@@ -2821,7 +2897,7 @@ var NETDATA = window.NETDATA || {};
                 }
             }
             else {
-                var tmp = new Array();
+                var tmp = [];
                 keys = Object.keys(this.chart.dimensions);
                 for(i = 0, len = keys.length; i < len ;i++) {
                     dim = keys[i];
@@ -3026,12 +3102,12 @@ var NETDATA = window.NETDATA || {};
 
             if(NETDATA.options.current.pan_and_zoom_data_padding === true && this.requested_padding !== null) {
                 if(this.view_after < this.data_after) {
-                    // console.log('adusting view_after from ' + this.view_after + ' to ' + this.data_after);
+                    // console.log('adjusting view_after from ' + this.view_after + ' to ' + this.data_after);
                     this.view_after = this.data_after;
                 }
 
                 if(this.view_before > this.data_before) {
-                    // console.log('adusting view_before from ' + this.view_before + ' to ' + this.data_before);
+                    // console.log('adjusting view_before from ' + this.view_before + ' to ' + this.data_before);
                     this.view_before = this.data_before;
                 }
             }
@@ -3063,7 +3139,8 @@ var NETDATA = window.NETDATA || {};
                 if(this.debug === true)
                     this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
 
-                this.chart_created = false;
+                init();
+                return;
             }
 
             // check and update the legend
@@ -3604,10 +3681,10 @@ var NETDATA = window.NETDATA || {};
 
     // ----------------------------------------------------------------------------------------------------------------
 
-    // this is purely sequencial charts refresher
+    // this is purely sequential charts refresher
     // it is meant to be autonomous
     NETDATA.chartRefresherNoParallel = function(index) {
-        if(NETDATA.options.debug.mail_loop === true)
+        if(NETDATA.options.debug.main_loop === true)
             console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
 
         if(NETDATA.options.updated_dom === true) {
@@ -3650,41 +3727,11 @@ var NETDATA = window.NETDATA || {};
         }
     };
 
-    // this is part of the parallel refresher
-    // its cause is to refresh sequencially all the charts
-    // that depend on chart library initialization
-    // it will call the parallel refresher back
-    // as soon as it sees a chart that its chart library
-    // is initialized
-    NETDATA.chartRefresher_uninitialized = function() {
-        if(NETDATA.options.updated_dom === true) {
-            // the dom has been updated
-            // get the dom parts again
-            NETDATA.parseDom(NETDATA.chartRefresher);
-            return;
-        }
-
-        if(NETDATA.options.sequencial.length === 0)
-            NETDATA.chartRefresher();
-        else {
-            var state = NETDATA.options.sequencial.pop();
-            if(state.library.initialized === true)
-                NETDATA.chartRefresher();
-            else
-                state.autoRefresh(NETDATA.chartRefresher_uninitialized);
-        }
-    };
-
     NETDATA.chartRefresherWaitTime = function() {
         return NETDATA.options.current.idle_parallel_loops;
     };
 
     // the default refresher
-    // it will create 2 sets of charts:
-    // - the ones that can be refreshed in parallel
-    // - the ones that depend on something else
-    // the first set will be executed in parallel
-    // the second will be given to NETDATA.chartRefresher_uninitialized()
     NETDATA.chartRefresher = function() {
         // console.log('auto-refresher...');
 
@@ -3717,7 +3764,7 @@ var NETDATA = window.NETDATA || {};
             return;
         }
 
-        var parallel = new Array();
+        var parallel = [];
         var targets = NETDATA.options.targets;
         var len = targets.length;
         var state;
@@ -3764,7 +3811,7 @@ var NETDATA = window.NETDATA || {};
         if(NETDATA.options.debug.main_loop === true)
             console.log('DOM updated - there are ' + targets.length + ' charts on page.');
 
-        NETDATA.options.targets = new Array();
+        NETDATA.options.targets = [];
         var len = targets.length;
         while(len--) {
             // the initialization will take care of sizing
@@ -3810,12 +3857,14 @@ var NETDATA = window.NETDATA || {};
         $('a[data-toggle="tab"]').on('shown.bs.tab', NETDATA.onscroll);
 
         // bootstrap modal switching
-        $('.modal').on('hidden.bs.modal', NETDATA.onscroll);
-        $('.modal').on('shown.bs.modal', NETDATA.onscroll);
+        var $modal = $('.modal');
+        $modal.on('hidden.bs.modal', NETDATA.onscroll);
+        $modal.on('shown.bs.modal', NETDATA.onscroll);
 
         // bootstrap collapse switching
-        $('.collapse').on('hidden.bs.collapse', NETDATA.onscroll);
-        $('.collapse').on('shown.bs.collapse', NETDATA.onscroll);
+        var $collapse = $('.collapse');
+        $collapse.on('hidden.bs.collapse', NETDATA.onscroll);
+        $collapse.on('shown.bs.collapse', NETDATA.onscroll);
 
         NETDATA.parseDom(NETDATA.chartRefresher);
 
@@ -4075,7 +4124,7 @@ var NETDATA = window.NETDATA || {};
         return true;
     };
 
-    NETDATA.dygraphClearSelection = function(state, t) {
+    NETDATA.dygraphClearSelection = function(state) {
         if(typeof state.dygraph_instance !== 'undefined') {
             state.dygraph_instance.clearSelection();
         }
@@ -4222,125 +4271,205 @@ var NETDATA = window.NETDATA || {};
 
         var self = $(state.element);
 
-        var chart_type = state.chart.chart_type;
+        var chart_type = self.data('dygraph-type') || state.chart.chart_type;
         if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
-        chart_type = self.data('dygraph-type') || chart_type;
-
-        var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
-        smooth = self.data('dygraph-smooth') || smooth;
 
-        if(NETDATA.dygraph.smooth === false)
-            smooth = false;
+        var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state) === true)?3:4;
 
-        var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
-        var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
+        var smooth = (NETDATA.dygraph.smooth === true)
+            ?(self.data('dygraph-smooth') || (chart_type === 'line' && NETDATA.chartLibraries.dygraph.isSparkline(state) === false))
+            :false;
 
         state.dygraph_options = {
-            colors: self.data('dygraph-colors') || state.chartColors(),
+            colors:                 self.data('dygraph-colors') || state.chartColors(),
 
             // leave a few pixels empty on the right of the chart
-            rightGap: self.data('dygraph-rightgap') || 5,
-            showRangeSelector: self.data('dygraph-showrangeselector') || false,
-            showRoller: self.data('dygraph-showroller') || false,
-
-            title: self.data('dygraph-title') || state.title,
-            titleHeight: self.data('dygraph-titleheight') || 19,
-
-            legend: self.data('dygraph-legend') || 'always', // we need this to get selection events
-            labels: data.result.labels,
-            labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
-            labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
-            labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
-            labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
-            labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
-            labelsKMB: false,
-            labelsKMG2: false,
-            showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
-            hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
-
-            includeZero: self.data('dygraph-includezero') || ((chart_type === 'stacked')? true : false),
-            xRangePad: self.data('dygraph-xrangepad') || 0,
-            yRangePad: self.data('dygraph-yrangepad') || 1,
-
-            valueRange: self.data('dygraph-valuerange') || [ null, null ],
-
-            ylabel: state.units,
-            yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
-
-            // the function to plot the chart
-            plotter: null,
-
-            // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
-            strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
-            strokePattern: self.data('dygraph-strokepattern') || undefined,
-
-            // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
-            // i.e. there is a missing point on either side of it. This also controls the size of those dots.
-            drawPoints: self.data('dygraph-drawpoints') || false,
-
-            // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
-            drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
-
-            connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
-            pointSize: self.data('dygraph-pointsize') || 1,
-
-            // enabling this makes the chart with little square lines
-            stepPlot: self.data('dygraph-stepplot') || false,
-
-            // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
-            strokeBorderColor: self.data('dygraph-strokebordercolor') || NETDATA.themes.current.background,
-            strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
-
-            fillGraph: self.data('dygraph-fillgraph') || ((chart_type === 'area' || chart_type === 'stacked')?true:false),
-            fillAlpha: self.data('dygraph-fillalpha') || ((chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area),
-            stackedGraph: self.data('dygraph-stackedgraph') || ((chart_type === 'stacked')?true:false),
-            stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
-
-            drawAxis: self.data('dygraph-drawaxis') || true,
-            axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
-            axisLineColor: self.data('dygraph-axislinecolor') || NETDATA.themes.current.axis,
-            axisLineWidth: self.data('dygraph-axislinewidth') || 1.0,
-
-            drawGrid: self.data('dygraph-drawgrid') || true,
-            gridLinePattern: self.data('dygraph-gridlinepattern') || null,
-            gridLineWidth: self.data('dygraph-gridlinewidth') || 1.0,
-            gridLineColor: self.data('dygraph-gridlinecolor') || NETDATA.themes.current.grid,
-
-            maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
-            sigFigs: self.data('dygraph-sigfigs') || null,
-            digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
-            valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
-
-            highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
-            highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
-            highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
-
-            pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
-            visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
+            rightGap:               self.data('dygraph-rightgap')
+                                    || 5,
+
+            showRangeSelector:      self.data('dygraph-showrangeselector')
+                                    || false,
+
+            showRoller:             self.data('dygraph-showroller')
+                                    || false,
+
+            title:                  self.data('dygraph-title')
+                                    || state.title,
+
+            titleHeight:            self.data('dygraph-titleheight')
+                                    || 19,
+
+            legend:                 self.data('dygraph-legend')
+                                    || 'always', // we need this to get selection events
+
+            labels:                 data.result.labels,
+
+            labelsDiv:              self.data('dygraph-labelsdiv')
+                                    || state.element_legend_childs.hidden,
+
+            labelsDivStyles:        self.data('dygraph-labelsdivstyles')
+                                    || { 'fontSize':'1px' },
+
+            labelsDivWidth:         self.data('dygraph-labelsdivwidth')
+                                    || state.chartWidth() - 70,
+
+            labelsSeparateLines:    self.data('dygraph-labelsseparatelines')
+                                    || true,
+
+            labelsShowZeroValues:   self.data('dygraph-labelsshowzerovalues')
+                                    || true,
+
+            labelsKMB:              false,
+            labelsKMG2:             false,
+
+            showLabelsOnHighlight:  self.data('dygraph-showlabelsonhighlight')
+                                    || true,
+
+            hideOverlayOnMouseOut:  self.data('dygraph-hideoverlayonmouseout')
+                                    || true,
+
+            includeZero:            self.data('dygraph-includezero')
+                                    || (chart_type === 'stacked'),
+
+            xRangePad:              self.data('dygraph-xrangepad')
+                                    || 0,
+
+            yRangePad:              self.data('dygraph-yrangepad')
+                                    || 1,
+
+            valueRange:             self.data('dygraph-valuerange')
+                                    || [ null, null ],
+
+            ylabel:                 state.units,
+
+            yLabelWidth:            self.data('dygraph-ylabelwidth')
+                                    || 12,
+
+                                    // the function to plot the chart
+            plotter:                null,
+
+                                    // The width of the lines connecting data points.
+                                    // This can be used to increase the contrast or some graphs.
+            strokeWidth:            self.data('dygraph-strokewidth')
+                                    || ((chart_type === 'stacked')?0.1:((smooth === true)?1.5:0.7)),
+
+            strokePattern:          self.data('dygraph-strokepattern')
+                                    || undefined,
+
+                                    // The size of the dot to draw on each point in pixels (see drawPoints).
+                                    // A dot is always drawn when a point is "isolated",
+                                    // i.e. there is a missing point on either side of it.
+                                    // This also controls the size of those dots.
+            drawPoints:             self.data('dygraph-drawpoints')
+                                    || false,
+
+                                    // Draw points at the edges of gaps in the data.
+                                    // This improves visibility of small data segments or other data irregularities.
+            drawGapEdgePoints:      self.data('dygraph-drawgapedgepoints')
+                                    || true,
+
+            connectSeparatedPoints: self.data('dygraph-connectseparatedpoints')
+                                    || false,
+
+            pointSize:              self.data('dygraph-pointsize')
+                                    || 1,
+
+                                    // enabling this makes the chart with little square lines
+            stepPlot:               self.data('dygraph-stepplot')
+                                    || false,
+
+                                    // Draw a border around graph lines to make crossing lines more easily
+                                    // distinguishable. Useful for graphs with many lines.
+            strokeBorderColor:      self.data('dygraph-strokebordercolor')
+                                    || NETDATA.themes.current.background,
+
+            strokeBorderWidth:      self.data('dygraph-strokeborderwidth')
+                                    || (chart_type === 'stacked')?0.0:0.0,
+
+            fillGraph:              self.data('dygraph-fillgraph')
+                                    || (chart_type === 'area' || chart_type === 'stacked'),
+
+            fillAlpha:              self.data('dygraph-fillalpha')
+                                    || ((chart_type === 'stacked')
+                                        ?NETDATA.options.current.color_fill_opacity_stacked
+                                        :NETDATA.options.current.color_fill_opacity_area),
+
+            stackedGraph:           self.data('dygraph-stackedgraph')
+                                    || (chart_type === 'stacked'),
+
+            stackedGraphNaNFill:    self.data('dygraph-stackedgraphnanfill')
+                                    || 'none',
+
+            drawAxis:               self.data('dygraph-drawaxis')
+                                    || true,
+
+            axisLabelFontSize:      self.data('dygraph-axislabelfontsize')
+                                    || 10,
+
+            axisLineColor:          self.data('dygraph-axislinecolor')
+                                    || NETDATA.themes.current.axis,
+
+            axisLineWidth:          self.data('dygraph-axislinewidth')
+                                    || 1.0,
+
+            drawGrid:               self.data('dygraph-drawgrid')
+                                    || true,
+
+            gridLinePattern:        self.data('dygraph-gridlinepattern')
+                                    || null,
+
+            gridLineWidth:          self.data('dygraph-gridlinewidth')
+                                    || 1.0,
+
+            gridLineColor:          self.data('dygraph-gridlinecolor')
+                                    || NETDATA.themes.current.grid,
+
+            maxNumberWidth:         self.data('dygraph-maxnumberwidth')
+                                    || 8,
+
+            sigFigs:                self.data('dygraph-sigfigs')
+                                    || null,
+
+            digitsAfterDecimal:     self.data('dygraph-digitsafterdecimal')
+                                    || 2,
+
+            valueFormatter:         self.data('dygraph-valueformatter')
+                                    || undefined,
+
+            highlightCircleSize:    self.data('dygraph-highlightcirclesize')
+                                    || highlightCircleSize,
+
+            highlightSeriesOpts:    self.data('dygraph-highlightseriesopts')
+                                    || null, // TOO SLOW: { strokeWidth: 1.5 },
+
+            highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha')
+                                    || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
+
+            pointClickCallback:     self.data('dygraph-pointclickcallback')
+                                    || undefined,
+
+            visibility:             state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
+
             axes: {
                 x: {
                     pixelsPerLabel: 50,
                     ticker: Dygraph.dateTicker,
                     axisLabelFormatter: function (d, gran) {
+                        void(gran);
                         return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
-                    },
-                    valueFormatter: function (ms) {
-                        //var d = new Date(ms);
-                        //return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
-
-                        // no need to return anything here
-                        return ' ';
-
                     }
                 },
                 y: {
                     pixelsPerLabel: 15,
-                    valueFormatter: function (x) {
-                        // we format legends with the state object
-                        // no need to do anything here
-                        // return (Math.round(x*100) / 100).toLocaleString();
-                        // return state.legendFormatValue(x);
-                        return x;
+                    axisLabelFormatter: function (y) {
+
+                        // unfortunately, we have to call this every single time
+                        state.legendFormatValueDecimalsFromMinMax(
+                            this.axes_[0].extremeRange[0],
+                            this.axes_[0].extremeRange[1]
+                        );
+
+                        return state.legendFormatValue(y);
                     }
                 }
             },
@@ -4381,6 +4510,8 @@ var NETDATA = window.NETDATA || {};
                 }
             },
             zoomCallback: function(minDate, maxDate, yRanges) {
+                void(yRanges);
+
                 if(NETDATA.options.debug.dygraph === true)
                     state.log('dygraphZoomCallback()');
 
@@ -4394,6 +4525,8 @@ var NETDATA = window.NETDATA || {};
                 state.updateChartPanOrZoom(minDate, maxDate);
             },
             highlightCallback: function(event, x, points, row, seriesName) {
+                void(seriesName);
+
                 if(NETDATA.options.debug.dygraph === true || state.debug === true)
                     state.log('dygraphHighlightCallback()');
 
@@ -4403,7 +4536,7 @@ var NETDATA = window.NETDATA || {};
                 // the time it thinks is selected is wrong
                 // here we calculate the time t based on the row number selected
                 // which is ok
-                var t = state.data_after + row * state.data_update_every;
+                // var t = state.data_after + row * state.data_update_every;
                 // console.log('row = ' + row + ', x = ' + x + ', t = ' + t + ' ' + ((t === x)?'SAME':(Math.abs(x-t)<=state.data_update_every)?'SIMILAR':'DIFFERENT') + ', rows in db: ' + state.data_points + ' visible(x) = ' + state.timeIsVisible(x) + ' visible(t) = ' + state.timeIsVisible(t) + ' r(x) = ' + state.calculateRowForTime(x) + ' r(t) = ' + state.calculateRowForTime(t) + ' range: ' + state.data_after + ' - ' + state.data_before + ' real: ' + state.data.after + ' - ' + state.data.before + ' every: ' + state.data_update_every);
 
                 state.globalSelectionSync(x);
@@ -4413,6 +4546,8 @@ var NETDATA = window.NETDATA || {};
                 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
             },
             unhighlightCallback: function(event) {
+                void(event);
+
                 if(NETDATA.options.debug.dygraph === true || state.debug === true)
                     state.log('dygraphUnhighlightCallback()');
 
@@ -4496,17 +4631,26 @@ var NETDATA = window.NETDATA || {};
                     }
                 },
                 click: function(event, dygraph, context) {
+                    void(dygraph);
+                    void(context);
+
                     if(NETDATA.options.debug.dygraph === true || state.debug === true)
                         state.log('interactionModel.click()');
 
                     event.preventDefault();
                 },
                 dblclick: function(event, dygraph, context) {
+                    void(event);
+                    void(dygraph);
+                    void(context);
+
                     if(NETDATA.options.debug.dygraph === true || state.debug === true)
                         state.log('interactionModel.dblclick()');
                     NETDATA.resetAllCharts(state);
                 },
                 wheel: function(event, dygraph, context) {
+                    void(context);
+
                     if(NETDATA.options.debug.dygraph === true || state.debug === true)
                         state.log('interactionModel.wheel()');
 
@@ -4518,7 +4662,7 @@ var NETDATA = window.NETDATA || {};
                         var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
                         var yar0 = g.yAxisRange(0);
 
-                        // This is calculating the pixel of the higest value. (Top pixel)
+                        // This is calculating the pixel of the highest value. (Top pixel)
                         var yOffset = g.toDomCoords(null, yar0[1])[1];
 
                         // x y w and h are relative to the corner of the drawing area,
@@ -4629,7 +4773,7 @@ var NETDATA = window.NETDATA || {};
                     Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
 
                     // we overwrite the touch directions at the end, to overwrite
-                    // the internal default of dygraphs
+                    // the internal default of dygraph
                     context.touchDirections = { x: true, y: false };
 
                     state.dygraph_last_touch_start = Date.now();
@@ -4658,7 +4802,7 @@ var NETDATA = window.NETDATA || {};
 
                     // if it didn't move, it is a selection
                     if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
-                        // internal api of dygraphs
+                        // internal api of dygraph
                         var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
                         var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
                         if(NETDATA.dygraphSetSelection(state, t) === true)
@@ -4714,7 +4858,7 @@ var NETDATA = window.NETDATA || {};
             state.__commonMax = self.data('common-max') || null;
         }
         else {
-            state.log('incompatible version of dygraphs detected');
+            state.log('incompatible version of Dygraph detected');
             state.__commonMin = null;
             state.__commonMax = null;
         }
@@ -5000,10 +5144,16 @@ var NETDATA = window.NETDATA || {};
     };
 
     NETDATA.d3ChartUpdate = function(state, data) {
+        void(state);
+        void(data);
+
         return false;
     };
 
     NETDATA.d3ChartCreate = function(state, data) {
+        void(state);
+        void(data);
+
         return false;
     };
 
@@ -5198,10 +5348,11 @@ var NETDATA = window.NETDATA || {};
 
     NETDATA.easypiechartClearSelection = function(state) {
         if(typeof state.easyPieChartEvent !== 'undefined') {
-            if(state.easyPieChartEvent.timer !== null)
+            if(state.easyPieChartEvent.timer !== undefined) {
                 clearTimeout(state.easyPieChartEvent.timer);
+            }
 
-            state.easyPieChartEvent.timer = null;
+            state.easyPieChartEvent.timer = undefined;
         }
 
         if(state.isAutoRefreshable() === true && state.data !== null) {
@@ -5226,7 +5377,7 @@ var NETDATA = window.NETDATA || {};
 
         if(typeof state.easyPieChartEvent === 'undefined') {
             state.easyPieChartEvent = {
-                timer: null,
+                timer: undefined,
                 value: 0,
                 pcent: 0
             };
@@ -5241,11 +5392,11 @@ var NETDATA = window.NETDATA || {};
         state.easyPieChartEvent.pcent = pcent;
         state.easyPieChartLabel.innerText = state.legendFormatValue(value);
 
-        if(state.easyPieChartEvent.timer === null) {
+        if(state.easyPieChartEvent.timer === undefined) {
             state.easyPieChart_instance.disableAnimation();
 
             state.easyPieChartEvent.timer = setTimeout(function() {
-                state.easyPieChartEvent.timer = null;
+                state.easyPieChartEvent.timer = undefined;
                 state.easyPieChart_instance.update(state.easyPieChartEvent.pcent);
             }, NETDATA.options.current.charts_selection_animation_delay);
         }
@@ -5445,9 +5596,10 @@ var NETDATA = window.NETDATA || {};
         // is always between min and max
         var pcent = (value - min) * 100 / (max - min);
 
-        // these should never happen
-        if(pcent < 0) pcent = 0;
-        if(pcent > 100) pcent = 100;
+        // bug fix for gauge.js 1.3.1
+        // if the value is the absolute min or max, the chart is broken
+        if(pcent < 0.001) pcent = 0.001;
+        if(pcent > 99.999) pcent = 99.999;
 
         state.gauge_instance.set(pcent);
         // console.log('gauge set ' + pcent + ', value ' + value + ', min ' + min + ', max ' + max);
@@ -5474,10 +5626,11 @@ var NETDATA = window.NETDATA || {};
 
     NETDATA.gaugeClearSelection = function(state) {
         if(typeof state.gaugeEvent !== 'undefined') {
-            if(state.gaugeEvent.timer !== null)
+            if(state.gaugeEvent.timer !== undefined) {
                 clearTimeout(state.gaugeEvent.timer);
+            }
 
-            state.gaugeEvent.timer = null;
+            state.gaugeEvent.timer = undefined;
         }
 
         if(state.isAutoRefreshable() === true && state.data !== null) {
@@ -5503,7 +5656,7 @@ var NETDATA = window.NETDATA || {};
 
         if(typeof state.gaugeEvent === 'undefined') {
             state.gaugeEvent = {
-                timer: null,
+                timer: undefined,
                 value: 0,
                 min: 0,
                 max: 0
@@ -5523,11 +5676,11 @@ var NETDATA = window.NETDATA || {};
         state.gaugeEvent.max = max;
         NETDATA.gaugeSetLabels(state, value, min, max);
 
-        if(state.gaugeEvent.timer === null) {
+        if(state.gaugeEvent.timer === undefined) {
             NETDATA.gaugeAnimation(state, false);
 
             state.gaugeEvent.timer = setTimeout(function() {
-                state.gaugeEvent.timer = null;
+                state.gaugeEvent.timer = undefined;
                 NETDATA.gaugeSet(state, state.gaugeEvent.value, state.gaugeEvent.min, state.gaugeEvent.max);
             }, NETDATA.options.current.charts_selection_animation_delay);
         }
@@ -5607,19 +5760,22 @@ var NETDATA = window.NETDATA || {};
 
         var options = {
             lines: 12,                  // The number of lines to draw
-            angle: 0.15,                // The length of each line
-            lineWidth: 0.44,            // 0.44 The line thickness
+            angle: 0.15,                // The span of the gauge arc
+            lineWidth: 0.50,            // The line thickness
+            radiusScale: 0.85,          // Relative radius
             pointer: {
                 length: 0.8,            // 0.9 The radius of the inner circle
                 strokeWidth: 0.035,     // The rotation offset
                 color: pointerColor     // Fill color
             },
+            limitMax: true,             // If false, the max value of the gauge will be updated if value surpass max
+            limitMin: true,             // If true, the min value of the gauge will be fixed unless you set it manually
             colorStart: startColor,     // Colors
             colorStop: stopColor,       // just experiment with them
             strokeColor: strokeColor,   // to see which ones work best for you
-            limitMax: true,
-            generateGradient: (generateGradient === true)?true:false,
-            gradientType: 0
+            generateGradient: (generateGradient === true),
+            gradientType: 0,
+            highDpiSupport: true        // High resolution support
         };
 
         if (generateGradient.constructor === Array) {
@@ -5629,13 +5785,13 @@ var NETDATA = window.NETDATA || {};
             // data-gauge-gradient-percent-color-50="#999900"
             // data-gauge-gradient-percent-color-100="#000000"
 
-            options.percentColors = new Array();
+            options.percentColors = [];
             var len = generateGradient.length;
             while(len--) {
                 var pcent = generateGradient[len];
                 var color = self.data('gauge-gradient-percent-color-' + pcent.toString()) || false;
                 if(color !== false) {
-                    var a = new Array();
+                    var a = [];
                     a[0] = pcent / 100;
                     a[1] = color;
                     options.percentColors.unshift(a);
@@ -5645,6 +5801,7 @@ var NETDATA = window.NETDATA || {};
                 delete options.percentColors;
         }
         else if(generateGradient === false && NETDATA.themes.current.gauge_gradient === true) {
+            //noinspection PointlessArithmeticExpressionJS
             options.percentColors = [
                 [0.0, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 0))],
                 [0.1, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 1))],
@@ -5746,31 +5903,21 @@ var NETDATA = window.NETDATA || {};
             toolboxPanAndZoom: NETDATA.dygraphToolboxPanAndZoom,
             initialized: false,
             enabled: true,
-            format: function(state) { return 'json'; },
-            options: function(state) { return 'ms|flip'; },
+            format: function(state) { void(state); return 'json'; },
+            options: function(state) { void(state); return 'ms|flip'; },
             legend: function(state) {
-                if(this.isSparkline(state) === false)
-                    return 'right-side';
-                else
-                    return null;
+                return (this.isSparkline(state) === false)?'right-side':null;
             },
-            autoresize: function(state) { return true; },
-            max_updates_to_recreate: function(state) { return 5000; },
-            track_colors: function(state) { return true; },
+            autoresize: function(state) { void(state); return true; },
+            max_updates_to_recreate: function(state) { void(state); return 5000; },
+            track_colors: function(state) { void(state); return true; },
             pixels_per_point: function(state) {
-                if(this.isSparkline(state) === false)
-                    return 3;
-                else
-                    return 2;
+                return (this.isSparkline(state) === false)?3:2;
             },
-
             isSparkline: function(state) {
                 if(typeof state.dygraph_sparkline === 'undefined') {
                     var t = $(state.element).data('dygraph-theme');
-                    if(t === 'sparkline')
-                        state.dygraph_sparkline = true;
-                    else
-                        state.dygraph_sparkline = false;
+                    state.dygraph_sparkline = (t === 'sparkline');
                 }
                 return state.dygraph_sparkline;
             }
@@ -5780,126 +5927,126 @@ var NETDATA = window.NETDATA || {};
             create: NETDATA.sparklineChartCreate,
             update: NETDATA.sparklineChartUpdate,
             resize: null,
-            setSelection: undefined, // function(state, t) { return true; },
-            clearSelection: undefined, // function(state) { return true; },
+            setSelection: undefined, // function(state, t) { void(state); return true; },
+            clearSelection: undefined, // function(state) { void(state); return true; },
             toolboxPanAndZoom: null,
             initialized: false,
             enabled: true,
-            format: function(state) { return 'array'; },
-            options: function(state) { return 'flip|abs'; },
-            legend: function(state) { return null; },
-            autoresize: function(state) { return false; },
-            max_updates_to_recreate: function(state) { return 5000; },
-            track_colors: function(state) { return false; },
-            pixels_per_point: function(state) { return 3; }
+            format: function(state) { void(state); return 'array'; },
+            options: function(state) { void(state); return 'flip|abs'; },
+            legend: function(state) { void(state); return null; },
+            autoresize: function(state) { void(state); return false; },
+            max_updates_to_recreate: function(state) { void(state); return 5000; },
+            track_colors: function(state) { void(state); return false; },
+            pixels_per_point: function(state) { void(state); return 3; }
         },
         "peity": {
             initialize: NETDATA.peityInitialize,
             create: NETDATA.peityChartCreate,
             update: NETDATA.peityChartUpdate,
             resize: null,
-            setSelection: undefined, // function(state, t) { return true; },
-            clearSelection: undefined, // function(state) { return true; },
+            setSelection: undefined, // function(state, t) { void(state); return true; },
+            clearSelection: undefined, // function(state) { void(state); return true; },
             toolboxPanAndZoom: null,
             initialized: false,
             enabled: true,
-            format: function(state) { return 'ssvcomma'; },
-            options: function(state) { return 'null2zero|flip|abs'; },
-            legend: function(state) { return null; },
-            autoresize: function(state) { return false; },
-            max_updates_to_recreate: function(state) { return 5000; },
-            track_colors: function(state) { return false; },
-            pixels_per_point: function(state) { return 3; }
+            format: function(state) { void(state); return 'ssvcomma'; },
+            options: function(state) { void(state); return 'null2zero|flip|abs'; },
+            legend: function(state) { void(state); return null; },
+            autoresize: function(state) { void(state); return false; },
+            max_updates_to_recreate: function(state) { void(state); return 5000; },
+            track_colors: function(state) { void(state); return false; },
+            pixels_per_point: function(state) { void(state); return 3; }
         },
         "morris": {
             initialize: NETDATA.morrisInitialize,
             create: NETDATA.morrisChartCreate,
             update: NETDATA.morrisChartUpdate,
             resize: null,
-            setSelection: undefined, // function(state, t) { return true; },
-            clearSelection: undefined, // function(state) { return true; },
+            setSelection: undefined, // function(state, t) { void(state); return true; },
+            clearSelection: undefined, // function(state) { void(state); return true; },
             toolboxPanAndZoom: null,
             initialized: false,
             enabled: true,
-            format: function(state) { return 'json'; },
-            options: function(state) { return 'objectrows|ms'; },
-            legend: function(state) { return null; },
-            autoresize: function(state) { return false; },
-            max_updates_to_recreate: function(state) { return 50; },
-            track_colors: function(state) { return false; },
-            pixels_per_point: function(state) { return 15; }
+            format: function(state) { void(state); return 'json'; },
+            options: function(state) { void(state); return 'objectrows|ms'; },
+            legend: function(state) { void(state); return null; },
+            autoresize: function(state) { void(state); return false; },
+            max_updates_to_recreate: function(state) { void(state); return 50; },
+            track_colors: function(state) { void(state); return false; },
+            pixels_per_point: function(state) { void(state); return 15; }
         },
         "google": {
             initialize: NETDATA.googleInitialize,
             create: NETDATA.googleChartCreate,
             update: NETDATA.googleChartUpdate,
             resize: null,
-            setSelection: undefined, //function(state, t) { return true; },
-            clearSelection: undefined, //function(state) { return true; },
+            setSelection: undefined, //function(state, t) { void(state); return true; },
+            clearSelection: undefined, //function(state) { void(state); return true; },
             toolboxPanAndZoom: null,
             initialized: false,
             enabled: true,
-            format: function(state) { return 'datatable'; },
-            options: function(state) { return ''; },
-            legend: function(state) { return null; },
-            autoresize: function(state) { return false; },
-            max_updates_to_recreate: function(state) { return 300; },
-            track_colors: function(state) { return false; },
-            pixels_per_point: function(state) { return 4; }
+            format: function(state) { void(state); return 'datatable'; },
+            options: function(state) { void(state); return ''; },
+            legend: function(state) { void(state); return null; },
+            autoresize: function(state) { void(state); return false; },
+            max_updates_to_recreate: function(state) { void(state); return 300; },
+            track_colors: function(state) { void(state); return false; },
+            pixels_per_point: function(state) { void(state); return 4; }
         },
         "raphael": {
             initialize: NETDATA.raphaelInitialize,
             create: NETDATA.raphaelChartCreate,
             update: NETDATA.raphaelChartUpdate,
             resize: null,
-            setSelection: undefined, // function(state, t) { return true; },
-            clearSelection: undefined, // function(state) { return true; },
+            setSelection: undefined, // function(state, t) { void(state); return true; },
+            clearSelection: undefined, // function(state) { void(state); return true; },
             toolboxPanAndZoom: null,
             initialized: false,
             enabled: true,
-            format: function(state) { return 'json'; },
-            options: function(state) { return ''; },
-            legend: function(state) { return null; },
-            autoresize: function(state) { return false; },
-            max_updates_to_recreate: function(state) { return 5000; },
-            track_colors: function(state) { return false; },
-            pixels_per_point: function(state) { return 3; }
+            format: function(state) { void(state); return 'json'; },
+            options: function(state) { void(state); return ''; },
+            legend: function(state) { void(state); return null; },
+            autoresize: function(state) { void(state); return false; },
+            max_updates_to_recreate: function(state) { void(state); return 5000; },
+            track_colors: function(state) { void(state); return false; },
+            pixels_per_point: function(state) { void(state); return 3; }
         },
         "c3": {
             initialize: NETDATA.c3Initialize,
             create: NETDATA.c3ChartCreate,
             update: NETDATA.c3ChartUpdate,
             resize: null,
-            setSelection: undefined, // function(state, t) { return true; },
-            clearSelection: undefined, // function(state) { return true; },
+            setSelection: undefined, // function(state, t) { void(state); return true; },
+            clearSelection: undefined, // function(state) { void(state); return true; },
             toolboxPanAndZoom: null,
             initialized: false,
             enabled: true,
-            format: function(state) { return 'csvjsonarray'; },
-            options: function(state) { return 'milliseconds'; },
-            legend: function(state) { return null; },
-            autoresize: function(state) { return false; },
-            max_updates_to_recreate: function(state) { return 5000; },
-            track_colors: function(state) { return false; },
-            pixels_per_point: function(state) { return 15; }
+            format: function(state) { void(state); return 'csvjsonarray'; },
+            options: function(state) { void(state); return 'milliseconds'; },
+            legend: function(state) { void(state); return null; },
+            autoresize: function(state) { void(state); return false; },
+            max_updates_to_recreate: function(state) { void(state); return 5000; },
+            track_colors: function(state) { void(state); return false; },
+            pixels_per_point: function(state) { void(state); return 15; }
         },
         "d3": {
             initialize: NETDATA.d3Initialize,
             create: NETDATA.d3ChartCreate,
             update: NETDATA.d3ChartUpdate,
             resize: null,
-            setSelection: undefined, // function(state, t) { return true; },
-            clearSelection: undefined, // function(state) { return true; },
+            setSelection: undefined, // function(state, t) { void(state); return true; },
+            clearSelection: undefined, // function(state) { void(state); return true; },
             toolboxPanAndZoom: null,
             initialized: false,
             enabled: true,
-            format: function(state) { return 'json'; },
-            options: function(state) { return ''; },
-            legend: function(state) { return null; },
-            autoresize: function(state) { return false; },
-            max_updates_to_recreate: function(state) { return 5000; },
-            track_colors: function(state) { return false; },
-            pixels_per_point: function(state) { return 3; }
+            format: function(state) { void(state); return 'json'; },
+            options: function(state) { void(state); return ''; },
+            legend: function(state) { void(state); return null; },
+            autoresize: function(state) { void(state); return false; },
+            max_updates_to_recreate: function(state) { void(state); return 5000; },
+            track_colors: function(state) { void(state); return false; },
+            pixels_per_point: function(state) { void(state); return 3; }
         },
         "easypiechart": {
             initialize: NETDATA.easypiechartInitialize,
@@ -5911,13 +6058,13 @@ var NETDATA = window.NETDATA || {};
             toolboxPanAndZoom: null,
             initialized: false,
             enabled: true,
-            format: function(state) { return 'array'; },
-            options: function(state) { return 'absolute'; },
-            legend: function(state) { return null; },
-            autoresize: function(state) { return false; },
-            max_updates_to_recreate: function(state) { return 5000; },
-            track_colors: function(state) { return true; },
-            pixels_per_point: function(state) { return 3; },
+            format: function(state) { void(state); return 'array'; },
+            options: function(state) { void(state); return 'absolute'; },
+            legend: function(state) { void(state); return null; },
+            autoresize: function(state) { void(state); return false; },
+            max_updates_to_recreate: function(state) { void(state); return 5000; },
+            track_colors: function(state) { void(state); return true; },
+            pixels_per_point: function(state) { void(state); return 3; },
             aspect_ratio: 100
         },
         "gauge": {
@@ -5930,13 +6077,13 @@ var NETDATA = window.NETDATA || {};
             toolboxPanAndZoom: null,
             initialized: false,
             enabled: true,
-            format: function(state) { return 'array'; },
-            options: function(state) { return 'absolute'; },
-            legend: function(state) { return null; },
-            autoresize: function(state) { return false; },
-            max_updates_to_recreate: function(state) { return 5000; },
-            track_colors: function(state) { return true; },
-            pixels_per_point: function(state) { return 3; },
+            format: function(state) { void(state); return 'array'; },
+            options: function(state) { void(state); return 'absolute'; },
+            legend: function(state) { void(state); return null; },
+            autoresize: function(state) { void(state); return false; },
+            max_updates_to_recreate: function(state) { void(state); return 5000; },
+            track_colors: function(state) { void(state); return true; },
+            pixels_per_point: function(state) { void(state); return 3; },
             aspect_ratio: 70
         }
     };
@@ -5962,10 +6109,7 @@ var NETDATA = window.NETDATA || {};
                 if(typeof $().emulateTransitionEnd === 'function')
                     return true;
                 else {
-                    if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
-                        return true;
-                    else
-                        return false;
+                    return (typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap === true);
                 }
             }
         },
@@ -5979,10 +6123,7 @@ var NETDATA = window.NETDATA || {};
         {
             url: NETDATA.themes.current.bootstrap_css,
             isAlreadyLoaded: function() {
-                if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
-                    return true;
-                else
-                    return false;
+                return (typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap === true);
             }
         },
         {
@@ -6034,7 +6175,7 @@ var NETDATA = window.NETDATA || {};
 
             if(async === false)
                 NETDATA.loadRequiredJs(++index, callback);
-        })
+        });
 
         if(async === true)
             NETDATA.loadRequiredJs(++index, callback);
@@ -6074,7 +6215,7 @@ var NETDATA = window.NETDATA || {};
         last_notification_id: 0,        // the id of the last alarm_log we have raised an alarm for
         first_notification_id: 0,       // the id of the first alarm_log entry for this session
                                         // this is used to prevent CLEAR notifications for past events
-        // notifications_shown: new Array(),
+        // notifications_shown: [],
 
         server: null,                   // the server to connect to for fetching alarms
         current: null,                  // the list of raised alarms - updated in the background
@@ -6088,16 +6229,18 @@ var NETDATA = window.NETDATA || {};
                 return;
             }
 
-            var value = entry.value;
+            var value_string = entry.value_string;
+
             if(NETDATA.alarms.current !== null) {
+                // get the current value_string
                 var t = NETDATA.alarms.current.alarms[entry.chart + '.' + entry.name];
-                if(typeof t !== 'undefined' && entry.status === t.status)
-                    value = t.value;
+                if(typeof t !== 'undefined' && entry.status === t.status && typeof t.value_string !== 'undefined')
+                    value_string = t.value_string;
             }
 
             var name = entry.name.replace(/_/g, ' ');
             var status = entry.status.toLowerCase();
-            var title = name + ' = ' + entry.value_string.toString();
+            var title = name + ' = ' + value_string.toString();
             var tag = entry.alarm_id;
             var icon = 'images/seo-performance-128.png';
             var interaction = false;
@@ -6130,8 +6273,8 @@ var NETDATA = window.NETDATA || {};
                         // console.log('alarm' + entry.unique_id + ' is CLEAR but has no_clear_notification flag');
                         return;
                     }
-                    title = name + ' back to normal (' + entry.value_string.toString() + ')';
-                    icon = 'images/check-mark-2-128-green.png'
+                    title = name + ' back to normal (' + value_string.toString() + ')';
+                    icon = 'images/check-mark-2-128-green.png';
                     interaction = false;
                     break;
 
@@ -6147,7 +6290,7 @@ var NETDATA = window.NETDATA || {};
                     if(entry.old_status === 'WARNING')
                         status = 'escalated to ' + entry.status.toLowerCase();
                     
-                    icon = 'images/alert-128-red.png'
+                    icon = 'images/alert-128-red.png';
                     interaction = true;
                     break;
 
@@ -6389,12 +6532,12 @@ var NETDATA = window.NETDATA || {};
     // Registry of netdata hosts
 
     NETDATA.registry = {
-        server: null,       // the netdata registry server
-        person_guid: null,  // the unique ID of this browser / user
-        machine_guid: null, // the unique ID the netdata server that served dashboard.js
-        hostname: null,     // the hostname of the netdata server that served dashboard.js
-        machines: null,         // the user's other URLs
-        machines_array: null,   // the user's other URLs in an array
+        server: null,         // the netdata registry server
+        person_guid: null,    // the unique ID of this browser / user
+        machine_guid: null,   // the unique ID the netdata server that served dashboard.js
+        hostname: 'unknown',  // the hostname of the netdata server that served dashboard.js
+        machines: null,       // the user's other URLs
+        machines_array: null, // the user's other URLs in an array
         person_urls: null,
 
         parsePersonUrls: function(person_urls) {
@@ -6403,9 +6546,8 @@ var NETDATA = window.NETDATA || {};
 
             if(person_urls) {
                 NETDATA.registry.machines = {};
-                NETDATA.registry.machines_array = new Array();
+                NETDATA.registry.machines_array = [];
 
-                var now = Date.now();
                 var apu = person_urls;
                 var i = apu.length;
                 while(i--) {
@@ -6418,7 +6560,7 @@ var NETDATA = window.NETDATA || {};
                             last_t: apu[i][2],
                             accesses: apu[i][3],
                             name: apu[i][4],
-                            alternate_urls: new Array()
+                            alternate_urls: []
                         };
                         obj.alternate_urls.push(apu[i][1]);
 
index 871a4f8f657701ef236be5cbcc247c5cc1309833..b4028168e8c072c50d16760a35bb59c2b5e879c0 100644 (file)
@@ -1,7 +1,9 @@
 
 var netdataDashboard = window.netdataDashboard || {};
 
-// menu
+// ----------------------------------------------------------------------------
+// menus
+
 // information about the main menus
 
 netdataDashboard.menu = {
@@ -14,177 +16,177 @@ netdataDashboard.menu = {
     'services': {
         title: 'systemd Services',
         icon: '<i class="fa fa-cogs" aria-hidden="true"></i>',
-        info: 'Resources utilization of systemd services.'
+        info: 'Resources utilization of systemd services. netdata monitors all systemd services via cgroups (the resources accounting used by containers). '
     },
 
     'ap': {
         title: 'Access Points',
         icon: '<i class="fa fa-wifi" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics for the access points (i.e. wireless interfaces in AP mode) found on the system.'
     },
 
     'tc': {
         title: 'Quality of Service',
         icon: '<i class="fa fa-globe" aria-hidden="true"></i>',
-        info: 'Netdata collects and visualizes tc class utilization using its <a href="https://github.com/firehol/netdata/blob/master/plugins.d/tc-qos-helper.sh" target="_blank">tc-helper plugin</a>. If you also use <a href="http://firehol.org/#fireqos" target="_blank">FireQOS</a> for setting up QoS, netdata automatically collects interface and class names. If your QoS configuration includes overheads calculation, the values shown here will include these overheads (the total bandwidth for the same interface as reported in the Network Interfaces section, will be lower than the total bandwidth reported here). Also, data collection may have a slight time difference compared to the interface (QoS data collection is implemented with a BASH script, so a shift in data collection of a few milliseconds should be justified).'
+        info: 'Netdata collects and visualizes <code>tc</code> class utilization using its <a href="https://github.com/firehol/netdata/blob/master/plugins.d/tc-qos-helper.sh" target="_blank">tc-helper plugin</a>. If you also use <a href="http://firehol.org/#fireqos" target="_blank">FireQOS</a> for setting up QoS, netdata automatically collects interface and class names. If your QoS configuration includes overheads calculation, the values shown here will include these overheads (the total bandwidth for the same interface as reported in the Network Interfaces section, will be lower than the total bandwidth reported here). QoS data collection may have a slight time difference compared to the interface (QoS data collection uses a BASH script, so a shift in data collection of a few milliseconds should be justified).'
     },
 
     'net': {
         title: 'Network Interfaces',
         icon: '<i class="fa fa-share-alt" aria-hidden="true"></i>',
-        info: 'Per network interface statistics collected from <code>/proc/net/dev</code>.'
+        info: 'Performance metrics for network interfaces.'
     },
 
     'ipv4': {
         title: 'IPv4 Networking',
         icon: '<i class="fa fa-cloud" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Metrics for the IPv4 stack of the system. <a href="https://en.wikipedia.org/wiki/IPv4" target="_blank">Internet Protocol version 4 (IPv4)</a> is the fourth version of the Internet Protocol (IP). It is one of the core protocols of standards-based internetworking methods in the Internet. IPv4 is a connectionless protocol for use on packet-switched networks. It operates on a best effort delivery model, in that it does not guarantee delivery, nor does it assure proper sequencing or avoidance of duplicate delivery. These aspects, including data integrity, are addressed by an upper layer transport protocol, such as the Transmission Control Protocol (TCP).'
     },
 
     'ipv6': {
         title: 'IPv6 Networking',
         icon: '<i class="fa fa-cloud" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Metrics for the IPv6 stack of the system. <a href="https://en.wikipedia.org/wiki/IPv6" target="_blank">Internet Protocol version 6 (IPv6)</a> is the most recent version of the Internet Protocol (IP), the communications protocol that provides an identification and location system for computers on networks and routes traffic across the Internet. IPv6 was developed by the Internet Engineering Task Force (IETF) to deal with the long-anticipated problem of IPv4 address exhaustion. IPv6 is intended to replace IPv4.'
     },
 
     'ipvs': {
         title: 'IP Virtual Server',
         icon: '<i class="fa fa-eye" aria-hidden="true"></i>',
-        info: undefined
+        info: '<a href="http://www.linuxvirtualserver.org/software/ipvs.html" target="_blank">IPVS (IP Virtual Server)</a> implements transport-layer load balancing inside the Linux kernel, so called Layer-4 switching. IPVS running on a host acts as a load balancer at the front of a cluster of real servers, it can direct requests for TCP/UDP based services to the real servers, and makes services of the real servers to appear as a virtual service on a single IP address.'
     },
 
     'netfilter': {
         title: 'Firewall (netfilter)',
         icon: '<i class="fa fa-shield" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics of the netfilter components.'
     },
 
     'cpu': {
         title: 'CPUs',
         icon: '<i class="fa fa-bolt" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Detailed information for each CPU of the system. A summary of the system for all CPUs can be found at the <a href="#menu_system">System Overview</a> section.'
     },
 
     'mem': {
         title: 'Memory',
         icon: '<i class="fa fa-bolt" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Detailed information about the memory management of the system.'
     },
 
     'disk': {
         title: 'Disks',
         icon: '<i class="fa fa-folder" aria-hidden="true"></i>',
-        info: 'Charts with performance information for all the system disks. Special care has been given to present disk performance metrics in a way compatible with <code>iostat -x</code>. netdata by default prevents rendering performance charts for individual partitions and unmounted virtual disks. Disabled charts can still be enabled by altering the relative settings in the netdata configuration file.'
+        info: 'Charts with performance information for all the system disks. Special care has been given to present disk performance metrics in a way compatible with <code>iostat -x</code>. netdata by default prevents rendering performance charts for individual partitions and unmounted virtual disks. Disabled charts can still be enabled by configuring the relative settings in the netdata configuration file.'
     },
 
     'sensors': {
         title: 'Sensors',
         icon: '<i class="fa fa-leaf" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Readings of the configured system sensors.'
     },
 
     'nfsd': {
         title: 'NFS Server',
         icon: '<i class="fa fa-folder-open" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics of the Network File Server. NFS is a distributed file system protocol, allowing a user on a client computer to access files over a network, much like local storage is accessed. NFS, like many other protocols, builds on the Open Network Computing Remote Procedure Call (ONC RPC) system. The NFS is an open standard defined in Request for Comments (RFC).'
     },
 
     'nfs': {
         title: 'NFS Client',
         icon: '<i class="fa fa-folder-open" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics of the NFS operations of this system, acting as an NFS client.'
     },
 
     'apps': {
         title: 'Applications',
         icon: '<i class="fa fa-heartbeat" aria-hidden="true"></i>',
-        info: 'Per application statistics are collected using netdata\'s <code>apps.plugin</code>. This plugin walks through the entire <code>/proc</code> filesystem and aggregates statistics for applications of interest, defined in <code>/etc/netdata/apps_groups.conf</code> (the default is <a href="https://github.com/firehol/netdata/blob/master/conf.d/apps_groups.conf" target="_blank">here</a>). The plugin internally builds a process tree (much like <code>ps fax</code> does), and groups processes together (evaluating both child and parent processes) so that the result is always a chart with a predefined set of dimensions (of course, only application groups found running are reported). The reported values are compatible with <code>top</code>, although the netdata plugin counts also the resources of exited children (unlike <code>top</code> which shows only the resources of the currently running processes). So for processes like shell scripts, the reported values include the resources used by the commands these scripts run within each timeframe.',
+        info: 'Per application statistics are collected using netdata\'s <code>apps.plugin</code>. This plugin walks through all processes and aggregates statistics for applications of interest, defined in <code>/etc/netdata/apps_groups.conf</code> (the default is <a href="https://github.com/firehol/netdata/blob/master/conf.d/apps_groups.conf" target="_blank">here</a>). The plugin internally builds a process tree (much like <code>ps fax</code> does), and groups processes together (evaluating both child and parent processes) so that the result is always a chart with a predefined set of dimensions (of course, only application groups found running are reported). The reported values are compatible with <code>top</code>, although the netdata plugin counts also the resources of exited children (unlike <code>top</code> which shows only the resources of the currently running processes). So for processes like shell scripts, the reported values include the resources used by the commands these scripts run within each timeframe.',
         height: 1.5
     },
 
     'users': {
         title: 'Users',
         icon: '<i class="fa fa-user" aria-hidden="true"></i>',
-        info: 'Per user statistics are collected using netdata\'s <code>apps.plugin</code>. This plugin walks through the entire <code>/proc</code> filesystem and aggregates statistics per user. The reported values are compatible with <code>top</code>, although the netdata plugin counts also the resources of exited children (unlike <code>top</code> which shows only the resources of the currently running processes). So for processes like shell scripts, the reported values include the resources used by the commands these scripts run within each timeframe.',
+        info: 'Per user statistics are collected using netdata\'s <code>apps.plugin</code>. This plugin walks through all processes and aggregates statistics per user. The reported values are compatible with <code>top</code>, although the netdata plugin counts also the resources of exited children (unlike <code>top</code> which shows only the resources of the currently running processes). So for processes like shell scripts, the reported values include the resources used by the commands these scripts run within each timeframe.',
         height: 1.5
     },
 
     'groups': {
         title: 'User Groups',
         icon: '<i class="fa fa-users" aria-hidden="true"></i>',
-        info: 'Per user group statistics are collected using netdata\'s <code>apps.plugin</code>. This plugin walks through the entire <code>/proc</code> filesystem and aggregates statistics per user group. The reported values are compatible with <code>top</code>, although the netdata plugin counts also the resources of exited children (unlike <code>top</code> which shows only the resources of the currently running processes). So for processes like shell scripts, the reported values include the resources used by the commands these scripts run within each timeframe.',
+        info: 'Per user group statistics are collected using netdata\'s <code>apps.plugin</code>. This plugin walks through all processes and aggregates statistics per user group. The reported values are compatible with <code>top</code>, although the netdata plugin counts also the resources of exited children (unlike <code>top</code> which shows only the resources of the currently running processes). So for processes like shell scripts, the reported values include the resources used by the commands these scripts run within each timeframe.',
         height: 1.5
     },
 
     'netdata': {
         title: 'Netdata Monitoring',
         icon: '<i class="fa fa-bar-chart" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics for the operation of netdata itself and its plugins.'
     },
 
     'example': {
         title: 'Example Charts',
-        info: undefined
+        info: 'Example charts, demonstrating the external plugin architecture.'
     },
 
     'cgroup': {
         title: '',
         icon: '<i class="fa fa-th" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Container resource utilization metrics. Netdata reads this information from <b>cgroups</b> (abbreviated from <b>control groups</b>), a Linux kernel feature that limits and accounts resource usage (CPU, memory, disk I/O, network, etc.) of a collection of processes. <b>cgroups</b> together with <b>namespaces</b> (that offer isolation between processes) provide what we usually call: <b>containers</b>.'
     },
 
     'cgqemu': {
         title: '',
         icon: '<i class="fa fa-th-large" aria-hidden="true"></i>',
-        info: undefined
+        info: 'QEMU virtual machine resource utilization metrics. QEMU (short for Quick Emulator) is a free and open-source hosted hypervisor that performs hardware virtualization.'
     },
 
     'fping': {
         title: 'fping',
         icon: '<i class="fa fa-exchange" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Network latency statistics, via <b>fping</b>. <b>fping</b> is a program to send ICMP echo probes to network hosts, similar to <code>ping</code>, but much better performing when pinging multiple hosts. fping versions after 3.15 can be directly used as netdata plugins.'
     },
 
     'memcached': {
         title: 'memcached',
         icon: '<i class="fa fa-database" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics for <b>memcached</b>. Memcached is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read.'
     },
 
     'mysql': {
         title: 'MySQL',
         icon: '<i class="fa fa-database" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics for <b>mysql</b>, the open-source relational database management system (RDBMS).'
     },
 
     'postgres': {
         title: 'Postgres',
         icon: '<i class="fa fa-database" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics for <b>PostgresSQL</b>, the object-relational database (ORDBMS).'
     },
 
     'redis': {
         title: 'Redis',
         icon: '<i class="fa fa-database" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics for <b>redis</b>. Redis (REmote DIctionary Server) is a software project that implements data structure servers. It is open-source, networked, in-memory, and stores keys with optional durability.'
     },
 
     'retroshare': {
         title: 'RetroShare',
         icon: '<i class="fa fa-share-alt" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics for <b>RetroShare</b>. RetroShare is open source software for encrypted filesharing, serverless email, instant messaging, online chat, and BBS, based on a friend-to-friend network built on GNU Privacy Guard (GPG).'
     },
 
     'ipfs': {
         title: 'IPFS',
         icon: '<i class="fa fa-folder-open" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics for the InterPlanetary File System (IPFS), a content-addressable, peer-to-peer hypermedia distribution protocol.'
     },
 
     'phpfpm': {
         title: 'PHP-FPM',
         icon: '<i class="fa fa-eye" aria-hidden="true"></i>',
-        info: undefined
+        info: 'Performance metrics for <b>PHP-FPM</b>, an alternative FastCGI implementation for PHP.'
     },
 
     'postfix': {
@@ -217,6 +219,12 @@ netdataDashboard.menu = {
         info: undefined
     },
 
+    'web_log': {
+        title: undefined,
+        icon: '<i class="fa fa-file-text-o" aria-hidden="true"></i>',
+        info: 'Information extracted from a web server log file. <code>python.d/web_log</code> plugin incrementally parses the web server log file to provide, in real-time, a break down of key web server performance metrics. A special log file format may optionally be used (for <code>nginx</code> and <code>apache</code>) allowing the plugin to extract timing information for the web server responses and bandwidth for both requests and responses. <code>web_log</code> plugin may also be configured to provide a break down of requests per URL pattern (check <a href="https://github.com/firehol/netdata/blob/master/conf.d/python.d/web_log.conf" target="_blank"><code>/etc/netdata/python.d/web_log.conf</code></a>). netdata attaches several alarms on these charts, such as <b>too many bad requests</b>, <b>too many redirects</b>, <b>too many internal errors</b>, <b>unreasonably slow responses</b>, <b>unreasonably many requests</b> (i.e. web attack) and <b>unreasonably few requests</b> (i.e. something is wrong).'
+    },
+
     'named': {
         title: 'named',
         icon: '<i class="fa fa-tag" aria-hidden="true"></i>',
@@ -254,9 +262,31 @@ netdataDashboard.menu = {
     }
 };
 
-// submenu
+
+
+// ----------------------------------------------------------------------------
+// submenus
+
+// information to be shown, just below each submenu
+
 // information about the submenus
 netdataDashboard.submenu = {
+    'web_log.bandwidth': {
+        info: 'Bandwidth of requests (<code>received</code>) and responses (<code>sent</code>). <code>received</code> requires a special file format (without it, the web server log does not have this information). This chart may present unusual spikes, since the whole bandwidth will be accounted at the time the log line is saved by the web server, even if the time needed to serve it spans across a longer duration. We suggest to use QoS (e.g. <a href="http://firehol.org/#fireqos" target="_blank">FireQOS</a>) for accurate accounting of the web server bandwidth.'
+    },
+
+    'web_log.urls': {
+        info: 'Number of requests for each URL <code>category</code> (URL pattern) defined in <a href="https://github.com/firehol/netdata/blob/master/conf.d/python.d/web_log.conf" target="_blank"><code>/etc/netdata/python.d/web_log.conf</code></a>. This chart counts all requests matching the URL patterns defined, independently of the web server response codes (i.e. both successful and unsuccessful).'
+    },
+
+    'web_log.clients': {
+        info: 'Charts showing the number of unique client IPs, accessing the web server.'
+    },
+
+    'web_log.timings': {
+        info: 'Web server response timings - the time the web server needed to prepare and respond to requests. This requires a special log format and its meaning is web server specific. For most web servers this accounts the time from the reception of a complete request, to the dispatch of the last byte of the response. So, it includes the network delays of responses, but it does not include the network delays of requests.'
+    },
+
     'mem.ksm': {
         title: 'Memory Deduper',
         info: 'Kernel Same-page Merging (KSM) performance monitoring, read from several files in <code>/sys/kernel/mm/ksm/</code>. KSM is a memory-saving de-duplication feature in the Linux kernel (since version 2.6.32). The KSM daemon ksmd periodically scans those areas of user memory which have been registered with it, looking for pages of identical content which can be replaced by a single write-protected page (which is automatically copied if a process later wants to update its content). KSM was originally developed for use with KVM (where it was known as Kernel Shared Memory), to fit more virtual machines into physical memory, by sharing the data common between them.  But it can be useful to any application which generates many instances of the same data.'
@@ -272,7 +302,7 @@ netdataDashboard.submenu = {
 
     'netfilter.conntrack': {
         title: 'Connection Tracker',
-        info: 'Netfilter Connection Tracker performance monitoring, read from <code>/proc/net/stat/nf_conntrack</code>. The connection tracker keeps track of all connections of the machine, inbound and outbound. It works by keeping a database with all open connections, tracking network and address translation and connection expectations.'
+        info: 'Netfilter Connection Tracker performance metrics. The connection tracker keeps track of all connections of the machine, inbound and outbound. It works by keeping a database with all open connections, tracking network and address translation and connection expectations.'
     },
 
     'netfilter.nfacct': {
@@ -282,21 +312,35 @@ netdataDashboard.submenu = {
 
     'netfilter.synproxy': {
         title: 'DDoS Protection',
-        info: 'DDoS Protection performance monitoring read from <code>/proc/net/stat/synproxy</code>. <a href="https://github.com/firehol/firehol/wiki/Working-with-SYNPROXY" target="_blank">SYNPROXY</a> is a TCP SYN packets proxy. It is used to protect any TCP server (like a web server) from SYN floods and similar DDoS attacks. It is a netfilter module, in the Linux kernel (since version 3.12). It is optimized to handle millions of packets per second utilizing all CPUs available without any concurrency locking between the connections. It can be used for any kind of TCP traffic (even encrypted), since it does not interfere with the content itself.'
+        info: 'DDoS protection performance metrics. <a href="https://github.com/firehol/firehol/wiki/Working-with-SYNPROXY" target="_blank">SYNPROXY</a> is a TCP SYN packets proxy. It is used to protect any TCP server (like a web server) from SYN floods and similar DDoS attacks. It is a netfilter module, in the Linux kernel (since version 3.12). It is optimized to handle millions of packets per second utilizing all CPUs available without any concurrency locking between the connections. It can be used for any kind of TCP traffic (even encrypted), since it does not interfere with the content itself.'
     },
 
     'system.softnet_stat': {
         title: 'softnet',
-        info: 'Statistics for CPUs SoftIRQs related to network receive work, read from <code>/proc/net/softnet_stat</code>. Break down per CPU core can be found at <a href="#menu_cpu_submenu_softnet_stat">CPU / softnet statistics</a>. <b>processed</b> states the number of packets processed, <b>dropped</b> is the number packets dropped because the network device backlog was full (to fix them use <code>sysctl</code> to increase <code>net.core.netdev_max_backlog</code>), <b>squeezed</b> is the number of packets dropped because the network device budget ran out (to fix them use <code>sysctl</code> to increase <code>net.core.netdev_budget</code>). More information about identifying and troubleshooting network driver related issues can be found at <a href="https://access.redhat.com/sites/default/files/attachments/20150325_network_performance_tuning.pdf" target="_blank">Red Hat Enterprise Linux Network Performance Tuning Guide</a>.'
+        info: function(os) {
+            if(os === 'linux')
+                return 'Statistics for CPUs SoftIRQs related to network receive work. Break down per CPU core can be found at <a href="#menu_cpu_submenu_softnet_stat">CPU / softnet statistics</a>. <b>processed</b> states the number of packets processed, <b>dropped</b> is the number packets dropped because the network device backlog was full (to fix them on Linux use <code>sysctl</code> to increase <code>net.core.netdev_max_backlog</code>), <b>squeezed</b> is the number of packets dropped because the network device budget ran out (to fix them on Linux use <code>sysctl</code> to increase <code>net.core.netdev_budget</code>). More information about identifying and troubleshooting network driver related issues can be found at <a href="https://access.redhat.com/sites/default/files/attachments/20150325_network_performance_tuning.pdf" target="_blank">Red Hat Enterprise Linux Network Performance Tuning Guide</a>.';
+            else
+                return 'Statistics for CPUs SoftIRQs related to network receive work.';
+        }
     },
 
     'cpu.softnet_stat': {
         title: 'softnet',
-        info: 'Statistics for per CPUs core SoftIRQs related to network receive work, read from <code>/proc/net/softnet_stat</code>. Total for all CPU cores can be found at <a href="#menu_system_submenu_softnet_stat">System / softnet statistics</a>. <b>processed</b> states the number of packets processed, <b>dropped</b> is the number packets dropped because the network device backlog was full (to fix them use <code>sysctl</code> to increase <code>net.core.netdev_max_backlog</code>), <b>squeezed</b> is the number of packets dropped because the network device budget ran out (to fix them use <code>sysctl</code> to increase <code>net.core.netdev_budget</code>). More information about identifying and troubleshooting network driver related issues can be found at <a href="https://access.redhat.com/sites/default/files/attachments/20150325_network_performance_tuning.pdf" target="_blank">Red Hat Enterprise Linux Network Performance Tuning Guide</a>.'
+        info: function(os) {
+            if(os === 'linux')
+                return 'Statistics for per CPUs core SoftIRQs related to network receive work. Total for all CPU cores can be found at <a href="#menu_system_submenu_softnet_stat">System / softnet statistics</a>. <b>processed</b> states the number of packets processed, <b>dropped</b> is the number packets dropped because the network device backlog was full (to fix them on Linux use <code>sysctl</code> to increase <code>net.core.netdev_max_backlog</code>), <b>squeezed</b> is the number of packets dropped because the network device budget ran out (to fix them on Linux use <code>sysctl</code> to increase <code>net.core.netdev_budget</code>). More information about identifying and troubleshooting network driver related issues can be found at <a href="https://access.redhat.com/sites/default/files/attachments/20150325_network_performance_tuning.pdf" target="_blank">Red Hat Enterprise Linux Network Performance Tuning Guide</a>.';
+            else
+                return 'Statistics for per CPUs core SoftIRQs related to network receive work. Total for all CPU cores can be found at <a href="#menu_system_submenu_softnet_stat">System / softnet statistics</a>.';
+        }
     }
 };
 
+
+
+// ----------------------------------------------------------------------------
 // chart
+
 // information works on the context of a chart
 // Its purpose is to set:
 //
@@ -308,60 +352,65 @@ netdataDashboard.submenu = {
 //
 netdataDashboard.context = {
     'system.cpu': {
-        info: 'Total CPU utilization (all cores). 100% here means there is no CPU idle time at all. You can get per core usage at the <a href="#menu_cpu">CPUs</a> section and per application usage at the <a href="#menu_apps">Applications Monitoring</a> section.<br/>Keep an eye on <b>iowait</b> ' + sparkline('system.cpu', 'iowait', '%') + '. If it is constantly high, your disks are a bottleneck and they slow your system down.<br/>Another important metric worth monitoring, is <b>softirq</b> ' + sparkline('system.cpu', 'softirq', '%') + '. A constantly high percentage of softirq may indicate network driver issues.',
+        info: function(os) {
+            void(os);
+            return 'Total CPU utilization (all cores). 100% here means there is no CPU idle time at all. You can get per core usage at the <a href="#menu_cpu">CPUs</a> section and per application usage at the <a href="#menu_apps">Applications Monitoring</a> section.'
+                + netdataDashboard.sparkline('<br/>Keep an eye on <b>iowait</b> ', 'system.cpu', 'iowait', '%', '. If it is constantly high, your disks are a bottleneck and they slow your system down.')
+                + netdataDashboard.sparkline('<br/>An important metric worth monitoring, is <b>softirq</b> ', 'system.cpu', 'softirq', '%', '. A constantly high percentage of softirq may indicate network driver issues.');
+        },
         valueRange: "[0, 100]"
     },
 
     'system.load': {
-        info: 'Current system load, i.e. the number of processes using CPU or waiting for system resources (usually CPU and disk). The 3 metrics refer to 1, 5 and 15 minute averages. Linux calculates this once every 5 seconds. Netdata reads them from <code>/proc/loadavg</code>. For more information check <a href="https://en.wikipedia.org/wiki/Load_(computing)" target="_blank">this wikipedia article</a>',
+        info: 'Current system load, i.e. the number of processes using CPU or waiting for system resources (usually CPU and disk). The 3 metrics refer to 1, 5 and 15 minute averages. The system calculates this once every 5 seconds. For more information check <a href="https://en.wikipedia.org/wiki/Load_(computing)" target="_blank">this wikipedia article</a>',
         height: 0.7
     },
 
     'system.io': {
-        info: 'Total Disk I/O, for all disks, read from <code>/proc/vmstat</code>. You can get detailed information about each disk at the <a href="#menu_disk">Disks</a> section and per application Disk usage at the <a href="#menu_apps">Applications Monitoring</a> section.'
+        info: 'Total Disk I/O, for all disks. You can get detailed information about each disk at the <a href="#menu_disk">Disks</a> section and per application Disk usage at the <a href="#menu_apps">Applications Monitoring</a> section.'
     },
 
     'system.swapio': {
-        info: 'Total Swap I/O, read from <code>/proc/vmstat</code>. (netdata measures both <code>in</code> and <code>out</code>. If either of them is not shown in the chart, it is because it is zero - you can change the page settings to always render all the available dimensions on all charts).'
+        info: 'Total Swap I/O. (netdata measures both <code>in</code> and <code>out</code>. If either of them is not shown in the chart, it is because it is zero - you can change the page settings to always render all the available dimensions on all charts).'
     },
 
     'system.pgfaults': {
-        info: 'Total page faults, read from <code>/proc/vmstat</code>. <b>Major page faults</b> indicates that the system is using its swap. You can find which applications use the swap at the <a href="#menu_apps">Applications Monitoring</a> section.'
+        info: 'Total page faults. <b>Major page faults</b> indicates that the system is using its swap. You can find which applications use the swap at the <a href="#menu_apps">Applications Monitoring</a> section.'
     },
 
     'system.entropy': {
         colors: '#CC22AA',
-        info: '<a href="https://en.wikipedia.org/wiki/Entropy_(computing)" target="_blank">Entropy</a>, read from <code>/proc/sys/kernel/random/entropy_avail</code>, is like a pool of random numbers (<a href="https://en.wikipedia.org/wiki//dev/random" target="_blank">/dev/random</a>) that are mainly used in cryptography. It is advised that the pool remains always <a href="https://blog.cloudflare.com/ensuring-randomness-with-linuxs-random-number-generator/" target="_blank">above 200</a>. If the pool of entropy gets empty, you risk your security to be predictable and you should install a user-space random numbers generating daemon, like <code>haveged</code> or <code>rng-tools</code> (i.e. <b>rngd</b>), to keep the pool in healthy levels.'
+        info: '<a href="https://en.wikipedia.org/wiki/Entropy_(computing)" target="_blank">Entropy</a>, is like a pool of random numbers (<a href="https://en.wikipedia.org/wiki//dev/random" target="_blank">/dev/random</a>) that are mainly used in cryptography. It is advised that the pool remains always <a href="https://blog.cloudflare.com/ensuring-randomness-with-linuxs-random-number-generator/" target="_blank">above 200</a>. If the pool of entropy gets empty, you risk your security to be predictable and you should install a user-space random numbers generating daemon, like <code>haveged</code> or <code>rng-tools</code> (i.e. <b>rngd</b>), to keep the pool in healthy levels.'
     },
 
     'system.forks': {
         colors: '#5555DD',
-        info: 'The number of new processes created per second, read from <code>/proc/stat</code>.'
+        info: 'Number of new processes created.'
     },
 
     'system.intr': {
         colors: '#DD5555',
-        info: 'Total number of CPU interrupts, read from <code>/proc/stat</code>. Check <code>system.interrupts</code> that gives more detail about each interrupt and also the <a href="#menu_cpu">CPUs</a> section where interrupts are analyzed per CPU core.'
+        info: 'Total number of CPU interrupts. Check <code>system.interrupts</code> that gives more detail about each interrupt and also the <a href="#menu_cpu">CPUs</a> section where interrupts are analyzed per CPU core.'
     },
 
     'system.interrupts': {
-        info: 'CPU interrupts in detail, read from <code>/proc/interrupts</code>. At the <a href="#menu_cpu">CPUs</a> section, interrupts are analyzed per CPU core.'
+        info: 'CPU interrupts in detail. At the <a href="#menu_cpu">CPUs</a> section, interrupts are analyzed per CPU core.'
     },
 
     'system.softirqs': {
-        info: 'CPU softirqs in detail, read from <code>/proc/softirqs</code>. At the <a href="#menu_cpu">CPUs</a> section, softirqs are analyzed per CPU core.'
+        info: 'CPU softirqs in detail. At the <a href="#menu_cpu">CPUs</a> section, softirqs are analyzed per CPU core.'
     },
 
     'system.processes': {
-        info: 'System processes, read from <code>/proc/stat</code>. <b>Running</b> are the processes in the CPU. <b>Blocked</b> are processes that are willing to enter the CPU, but they cannot, e.g. because they wait for disk activity.'
+        info: 'System processes. <b>Running</b> are the processes in the CPU. <b>Blocked</b> are processes that are willing to enter the CPU, but they cannot, e.g. because they wait for disk activity.'
     },
 
     'system.active_processes': {
-        info: 'All system processes, read from <code>/proc/loadavg</code>.'
+        info: 'All system processes.'
     },
 
     'system.ctxt': {
-        info: '<a href="https://en.wikipedia.org/wiki/Context_switch" target="_blank">Context Switches</a>, read from <code>/proc/stat</code>, is the switching of the CPU from one process, task or thread to another. If there are many processes or threads willing to execute and very few CPU cores available to handle them, the system is making more context switching to balance the CPU resources among them. The whole process is computationally intensive. The more the context switches, the slower the system gets.'
+        info: '<a href="https://en.wikipedia.org/wiki/Context_switch" target="_blank">Context Switches</a>, is the switching of the CPU from one process, task or thread to another. If there are many processes or threads willing to execute and very few CPU cores available to handle them, the system is making more context switching to balance the CPU resources among them. The whole process is computationally intensive. The more the context switches, the slower the system gets.'
     },
 
     'system.idlejitter': {
@@ -370,19 +419,19 @@ netdataDashboard.context = {
     },
 
     'system.ipv4': {
-        info: 'Total IPv4 Traffic, read from <code>/proc/net/netstat</code>.'
+        info: 'Total IPv4 Traffic.'
     },
 
     'system.ipv6': {
-        info: 'Total IPv6 Traffic, read from <code>/proc/net/snmp6</code>.'
+        info: 'Total IPv6 Traffic.'
     },
 
     'system.ram': {
-        info: 'System memory, read from <code>/proc/meminfo</code>.'
+        info: 'System Random Access Memory (i.e. physical memory) usage.'
     },
 
     'system.swap': {
-        info: 'System swap memory, read from <code>/proc/meminfo</code>.'
+        info: 'System swap memory usage. Swap space is used when the amount of physical memory (RAM) is full. When the system needs more memory resources and the RAM is full, inactive pages in memory are moved to the swap space (usually a disk, a disk partition or a file).'
     },
 
     // ------------------------------------------------------------------------
@@ -396,7 +445,8 @@ netdataDashboard.context = {
 
     'mem.ksm_ratios': {
         heads: [
-            function(id) {
+            function(os, id) {
+                void(os);
                 return  '<div data-netdata="' + id + '"'
                     + ' data-gauge-max-value="100"'
                     + ' data-chart-library="gauge"'
@@ -413,24 +463,24 @@ netdataDashboard.context = {
     },
 
     'mem.pgfaults': {
-       info: 'A <a href="https://en.wikipedia.org/wiki/Page_fault" target="_blank">page fault</a> is a type of interrupt, called trap, raised by computer hardware when a running program accesses a memory page that is mapped into the virtual address space, but not actually loaded into main memory. If the page is loaded in memory at the time the fault is generated, but is not marked in the memory management unit as being loaded in memory, then it is called a <b>minor</b> or soft page fault. A <b>major</b> page fault is generated when the system needs to load the memory page from disk or swap memory. These values are read from <code>/proc/vmstat</code>.'
+       info: 'A <a href="https://en.wikipedia.org/wiki/Page_fault" target="_blank">page fault</a> is a type of interrupt, called trap, raised by computer hardware when a running program accesses a memory page that is mapped into the virtual address space, but not actually loaded into main memory. If the page is loaded in memory at the time the fault is generated, but is not marked in the memory management unit as being loaded in memory, then it is called a <b>minor</b> or soft page fault. A <b>major</b> page fault is generated when the system needs to load the memory page from disk or swap memory.'
     },
 
     'mem.committed': {
         colors: NETDATA.colors[3],
-        info: 'Committed Memory, read from <code>/proc/meminfo</code>, is the sum of all memory which has been allocated by processes.'
+        info: 'Committed Memory, is the sum of all memory which has been allocated by processes.'
     },
 
     'mem.writeback': {
-        info: 'Read from <code>/proc/meminfo</code>, <b>Dirty</b> is the amount of memory waiting to be written to disk. <b>Writeback</b> is how much memory is actively being written to disk.'
+        info: '<b>Dirty</b> is the amount of memory waiting to be written to disk. <b>Writeback</b> is how much memory is actively being written to disk.'
     },
 
     'mem.kernel': {
-        info: 'Read from <code>/proc/meminfo</code>, This chart displays the total ammount of memory being used by the kernel. <b>Slab</b> is the amount of memory used by the kernel to cache data structures for its own use. <b>KernelStack</b> is the amount of memory allocated for each task done by the kernel. <b>PageTables</b> is the amount of memory decicated to the lowest level of page tables (A page table is used to turn a virtual address into a physical memory address). <b>VmallocUsed</b> is the amount of memory being used as virtual address space.'
+        info: 'The total ammount of memory being used by the kernel. <b>Slab</b> is the amount of memory used by the kernel to cache data structures for its own use. <b>KernelStack</b> is the amount of memory allocated for each task done by the kernel. <b>PageTables</b> is the amount of memory decicated to the lowest level of page tables (A page table is used to turn a virtual address into a physical memory address). <b>VmallocUsed</b> is the amount of memory being used as virtual address space.'
     },
 
     'mem.slab': {
-        info: 'Read from <code>/proc/meminfo</code>, <b>reclaimable</b> is the amount of memory which the kernel can reuse. <b>unreclaimable</b> can not be reused even when the kernel is lacking memory.'
+        info: '<b>Reclaimable</b> is the amount of memory which the kernel can reuse. <b>Unreclaimable</b> can not be reused even when the kernel is lacking memory.'
     },
 
     // ------------------------------------------------------------------------
@@ -525,7 +575,9 @@ netdataDashboard.context = {
 
     'tc.qos': {
         heads: [
-            function(id) {
+            function(os, id) {
+                void(os);
+
                 if(id.match(/.*-ifb$/))
                     return netdataDashboard.gaugeChart('Inbound', '12%', '', '#5555AA');
                 else
@@ -568,12 +620,12 @@ netdataDashboard.context = {
         heads: [
             netdataDashboard.gaugeChart('Utilization', '12%', '', '#FF5588')
         ],
-        info: 'Disk Utilization measures the amount of time the disk was busy with something. This is not related to its performance. 100% means that the Linux kernel always had an outstanding operation on the disk. Keep in mind that depending on the underlying technology of the disk, 100% here may or may not be an indication of congestion.'
+        info: 'Disk Utilization measures the amount of time the disk was busy with something. This is not related to its performance. 100% means that the system always had an outstanding operation on the disk. Keep in mind that depending on the underlying technology of the disk, 100% here may or may not be an indication of congestion.'
     },
 
     'disk.backlog': {
         colors: '#0099CC',
-        info: 'Backlog is an indication of the duration of pending disk operations. On every I/O event the Linux kernel is multiplying the time spent doing I/O since the last update of this field with the number of pending operations. While not accurate, this metric can provide an indication of the expected completion time of the operations in progress.'
+        info: 'Backlog is an indication of the duration of pending disk operations. On every I/O event the system is multiplying the time spent doing I/O since the last update of this field with the number of pending operations. While not accurate, this metric can provide an indication of the expected completion time of the operations in progress.'
     },
 
     'disk.io': {
@@ -585,7 +637,7 @@ netdataDashboard.context = {
     },
 
     'disk.ops': {
-        info: 'Completed disk I/O operations. Keep in mind the number of operations requested might be higher, since the Linux kernel is able to merge adjacent to each other (see merged operations chart).'
+        info: 'Completed disk I/O operations. Keep in mind the number of operations requested might be higher, since the system is able to merge adjacent to each other (see merged operations chart).'
     },
 
     'disk.qops': {
@@ -598,7 +650,7 @@ netdataDashboard.context = {
     },
     'disk.mops': {
         height: 0.5,
-        info: 'The number of merged disk operations. The Linux kernel is able to merge adjacent I/O operations, for example two 4KB reads can become one 8KB read before given to disk.'
+        info: 'The number of merged disk operations. The system is able to merge adjacent I/O operations, for example two 4KB reads can become one 8KB read before given to disk.'
     },
     'disk.svctm': {
         height: 0.5,
@@ -689,7 +741,8 @@ netdataDashboard.context = {
 
     'apache.workers': {
         mainheads: [
-            function(id) {
+            function(os, id) {
+                void(os);
                 return  '<div data-netdata="' + id + '"'
                     + ' data-dimensions="busy"'
                     + ' data-append-options="percentage"'
@@ -761,7 +814,8 @@ netdataDashboard.context = {
     'retroshare.peers': {
         info: 'Number of (connected) RetroShare friends.',
         mainheads: [
-            function(id) {
+            function(os, id) {
+                void(os);
                 return  '<div data-netdata="' + id + '"'
                     + ' data-dimensions="peers_connected"'
                     + ' data-append-options="friends"'
@@ -791,6 +845,121 @@ netdataDashboard.context = {
 
     'fping.packets': {
         height: 0.5
+    },
+
+    'web_log.response_codes': {
+        info: 'Break down of web server responses by response code type. <code>1xx</code> are informational responses, <code>2xx</code> are successful responses, <code>3xx</code> are redirects, <code>4xx</code> are bad requests, <code>5xx</code> are internal server errors, <code>other</code> are non-standard responses, <code>unmatched</code> counts the lines in the log file that are not matched by the plugin (please <a href="https://github.com/firehol/netdata/issues/new?title=web_log%20reports%20unmatched%20lines&body=web_log%20plugin%20reports%20unmatched%20lines.%0A%0AThis%20is%20my%20log:%0A%0A%60%60%60txt%0A%0Aplease%20paste%20your%20web%20server%20log%20here%0A%0A%60%60%60" target="_blank">open a github issue</a> to help us fix it, if you have any unmatched lines).',
+
+        mainheads: [
+            function(os, id) {
+                void(os);
+                return  '<div data-netdata="' + id + '"'
+                    + ' data-dimensions="2xx"'
+                    + ' data-chart-library="gauge"'
+                    + ' data-title="Successful"'
+                    + ' data-units="requests/s"'
+                    + ' data-gauge-adjust="width"'
+                    + ' data-width="12%"'
+                    + ' data-before="0"'
+                    + ' data-after="-CHART_DURATION"'
+                    + ' data-points="CHART_DURATION"'
+                    + ' data-common-max="' + id + '"'
+                    + ' data-colors="' + NETDATA.colors[0] + '"'
+                    + ' data-decimal-digits="0"'
+                    + ' role="application"></div>';
+            },
+
+            function(os, id) {
+                void(os);
+                return  '<div data-netdata="' + id + '"'
+                    + ' data-dimensions="3xx"'
+                    + ' data-chart-library="gauge"'
+                    + ' data-title="Redirects"'
+                    + ' data-units="requests/s"'
+                    + ' data-gauge-adjust="width"'
+                    + ' data-width="12%"'
+                    + ' data-before="0"'
+                    + ' data-after="-CHART_DURATION"'
+                    + ' data-points="CHART_DURATION"'
+                    + ' data-common-max="' + id + '"'
+                    + ' data-colors="' + NETDATA.colors[2] + '"'
+                    + ' data-decimal-digits="0"'
+                    + ' role="application"></div>';
+            },
+
+            function(os, id) {
+                void(os);
+                return  '<div data-netdata="' + id + '"'
+                    + ' data-dimensions="4xx"'
+                    + ' data-chart-library="gauge"'
+                    + ' data-title="Bad Requests"'
+                    + ' data-units="requests/s"'
+                    + ' data-gauge-adjust="width"'
+                    + ' data-width="12%"'
+                    + ' data-before="0"'
+                    + ' data-after="-CHART_DURATION"'
+                    + ' data-points="CHART_DURATION"'
+                    + ' data-common-max="' + id + '"'
+                    + ' data-colors="' + NETDATA.colors[3] + '"'
+                    + ' data-decimal-digits="0"'
+                    + ' role="application"></div>';
+            },
+
+            function(os, id) {
+                void(os);
+                return  '<div data-netdata="' + id + '"'
+                    + ' data-dimensions="5xx"'
+                    + ' data-chart-library="gauge"'
+                    + ' data-title="Server Errors"'
+                    + ' data-units="requests/s"'
+                    + ' data-gauge-adjust="width"'
+                    + ' data-width="12%"'
+                    + ' data-before="0"'
+                    + ' data-after="-CHART_DURATION"'
+                    + ' data-points="CHART_DURATION"'
+                    + ' data-common-max="' + id + '"'
+                    + ' data-colors="' + NETDATA.colors[1] + '"'
+                    + ' data-decimal-digits="0"'
+                    + ' role="application"></div>';
+            }
+        ]
+    },
+
+    'web_log.response_time': {
+        mainheads: [
+            function(os, id) {
+                void(os);
+                return  '<div data-netdata="' + id + '"'
+                    + ' data-dimensions="avg"'
+                    + ' data-chart-library="gauge"'
+                    + ' data-title="Average Response Time"'
+                    + ' data-units="milliseconds"'
+                    + ' data-gauge-adjust="width"'
+                    + ' data-width="12%"'
+                    + ' data-before="0"'
+                    + ' data-after="-CHART_DURATION"'
+                    + ' data-points="CHART_DURATION"'
+                    + ' data-colors="' + NETDATA.colors[4] + '"'
+                    + ' data-decimal-digits="2"'
+                    + ' role="application"></div>';
+            }
+        ]
+    },
+
+    'web_log.detailed_response_codes': {
+        info: 'Number of responses for each response code.'
+    },
+
+    'web_log.requests_per_ipproto': {
+        info: 'Web server requests received per IP protocol version.'
+    },
+
+    'web_log.clients': {
+        info: 'Unique client IPs accessing the web server, within each data collection iteration. If data collection is <b>per second</b>, this chart shows <b>unique client IPs per second</b>.'
+    },
+
+    'web_log.clients_all': {
+        info: 'Unique client IPs accessing the web server since the last restart of netdata. This plugin keeps in memory all the unique IPs that have accessed the web server. On very busy web servers (several millions of unique IPs) you may want to disable this chart (check <a href="https://github.com/firehol/netdata/blob/master/conf.d/python.d/web_log.conf" target="_blank"><code>/etc/netdata/python.d/web_log.conf</code></a>).'
     }
 
 };
index c9685ba3a0b6133ec2f3d893ca7b2548c9be0194..7bba3f4d5ef465b5563991ec722d1f73f7d9b18f 100644 (file)
                 if(localStorageTest() === true)
                     ret = localStorage.getItem(name);
             }
-            catch(error) {
-                ;
-            }
+            catch(error) {}
 
             if(typeof ret === 'undefined' || ret === null)
                 return null;
                     return true;
                 }
             }
-            catch(error) {
-                ;
-            }
+            catch(error) {}
 
             return false;
         }
                             this_is_demo = true;
                 }
             }
-            catch(error) {
-                ;
-            }
-
+            catch(error) {}
             return this_is_demo;
         }
 
         }
 
         function netdataReload(url) {
-            var t = netdataURL(url);
-            // console.log('netdataReload: ' + t);
-            document.location = t;
+            document.location = netdataURL(url);
 
             // since we play with hash
             // this is needed to reload the page
 
         var deleteRegistryUrl = null;
         function deleteRegistryModalHandler(guid, name, url) {
+            void(guid);
+
             deleteRegistryUrl = url;
             document.getElementById('deleteRegistryServerName').innerHTML = name;
             document.getElementById('deleteRegistryServerName2').innerHTML = name;
         }
 
         var options = {
-            sparklines_registry: {},
             menus: {},
             submenu_names: {},
             data: null,
             hostname: 'netdata_server', // will be overwritten by the netdata server
-            categories: new Array(),
+            version: 'unknown',
+            categories: [],
             categories_idx: {},
-            families: new Array(),
+            families: [],
             families_idx: {},
 
             chartsPerRow: 0,
             chartsMinWidth: 1450,
-            chartsHeight: 180,
-            sparklinesHeight: 60,
+            chartsHeight: 180
         };
 
-        // generate a sparkline
-        // used in the documentation
-        function sparkline(chart, dimension, units) {
-            var key = chart + '.' + dimension;
-
-            if(typeof units === 'undefined')
-                units = '';
-
-            if(typeof options.sparklines_registry[key] === 'undefined')
-                options.sparklines_registry[key] = { count: 1 };
-            else
-                options.sparklines_registry[key].count++;
-
-            key = key + '.' + options.sparklines_registry[key].count;
-
-            var h = '<div data-netdata="' + chart + '" data-after="-120" data-width="25%" data-height="15px" data-chart-library="dygraph" data-dygraph-theme="sparkline" data-dimensions="' + dimension + '" data-show-value-of-' + dimension + '-at="' + key + '"></div> (<span id="' + key + '" style="display: inline-block; min-width: 50px; text-align: right;">X</span>' + units + ')';
-
-            return h;
-        }
-
         function chartsPerRow(total) {
             if(options.chartsPerRow === 0) {
-                width = Math.floor(total / options.chartsMinWidth);
+                var width = Math.floor(total / options.chartsMinWidth);
                 if(width === 0) width = 1;
                 return width;
             }
 
         function sortObjectByPriority(object) {
             var idx = {};
-            var sorted = new Array();
+            var sorted = [];
 
             for(var i in object) {
+                if(!object.hasOwnProperty(i)) continue;
+
                 if(typeof idx[i] === 'undefined') {
                     idx[i] = object[i];
                     sorted.push(i);
         // ----------------------------------------------------------------------------
 
         var netdataDashboard = {
+            sparklines_registry: {},
+            os: 'unknown',
+
             menu: {},
             submenu: {},
             context: {},
 
+            // generate a sparkline
+            // used in the documentation
+            sparkline: function (prefix, chart, dimension, units, suffix) {
+                if(options.data === null || typeof options.data.charts === 'undefined')
+                    return '';
+
+                if(typeof options.data.charts[chart] === 'undefined')
+                    return '';
+
+                if(typeof options.data.charts[chart].dimensions === 'undefined')
+                    return '';
+
+                if(typeof options.data.charts[chart].dimensions[dimension] === 'undefined')
+                    return '';
+
+                var key = chart + '.' + dimension;
+
+                if(typeof units === 'undefined')
+                    units = '';
+
+                if(typeof this.sparklines_registry[key] === 'undefined')
+                    this.sparklines_registry[key] = { count: 1 };
+                else
+                    this.sparklines_registry[key].count++;
+
+                key = key + '.' + this.sparklines_registry[key].count;
+
+                return prefix + '<div data-netdata="' + chart + '" data-after="-120" data-width="25%" data-height="15px" data-chart-library="dygraph" data-dygraph-theme="sparkline" data-dimensions="' + dimension + '" data-show-value-of-' + dimension + '-at="' + key + '"></div> (<span id="' + key + '" style="display: inline-block; min-width: 50px; text-align: right;">X</span>' + units + ')' + suffix;
+            },
+
             gaugeChart: function(title, width, dimensions, colors) {
                 if(typeof colors === 'undefined')
                     colors = '';
                     dimensions = '';
 
                 return '<div data-netdata="CHART_UNIQUE_ID"'
-                                        + ' data-dimensions="' + dimensions + '"'
-                                        + ' data-chart-library="gauge"'
-                                        + ' data-gauge-adjust="width"'
-                                        + ' data-title="' + title + '"'
-                                        + ' data-width="' + width + '"'
-                                        + ' data-before="0"'
-                                        + ' data-after="-CHART_DURATION"'
-                                        + ' data-points="CHART_DURATION"'
-                                        + ' data-colors="' + colors + '"'
-                                        + ' role="application"></div>';
+                            + ' data-dimensions="' + dimensions + '"'
+                            + ' data-chart-library="gauge"'
+                            + ' data-gauge-adjust="width"'
+                            + ' data-title="' + title + '"'
+                            + ' data-width="' + width + '"'
+                            + ' data-before="0"'
+                            + ' data-after="-CHART_DURATION"'
+                            + ' data-points="CHART_DURATION"'
+                            + ' data-colors="' + colors + '"'
+                            + ' role="application"></div>';
             },
 
             anyAttribute: function(obj, attr, key, def) {
-                if(typeof obj[key] !== 'undefined') {
-                    if(typeof obj[key][attr] !== 'undefined')
-                        return obj[key][attr];
+                if(typeof(obj[key]) !== 'undefined') {
+                    var x = obj[key][attr];
+
+                    if(typeof(x) === 'undefined')
+                        return def;
+
+                    if(typeof(x) === 'function') {
+                        return x(netdataDashboard.os);
+                    }
+
+                    return x;
                 }
+
                 return def;
             },
 
             menuTitle: function(chart) {
                 if(typeof chart.menu_pattern !== 'undefined') {
-                    return (netdataDashboard.anyAttribute(netdataDashboard.menu, 'title', chart.menu_pattern, chart.menu_pattern).toString()
+                    return (this.anyAttribute(this.menu, 'title', chart.menu_pattern, chart.menu_pattern).toString()
                             + '&nbsp;' + chart.type.slice(-(chart.type.length - chart.menu_pattern.length - 1)).toString()).replace(/_/g, ' ');
                 }
 
-                return (netdataDashboard.anyAttribute(netdataDashboard.menu, 'title', chart.menu, chart.menu)).toString().replace(/_/g, ' ');
+                return (this.anyAttribute(this.menu, 'title', chart.menu, chart.menu)).toString().replace(/_/g, ' ');
             },
 
             menuIcon: function(chart) {
                 if(typeof chart.menu_pattern !== 'undefined')
-                    return netdataDashboard.anyAttribute(netdataDashboard.menu, 'icon', chart.menu_pattern, '<i class="fa fa-puzzle-piece" aria-hidden="true"></i>').toString();
+                    return this.anyAttribute(this.menu, 'icon', chart.menu_pattern, '<i class="fa fa-puzzle-piece" aria-hidden="true"></i>').toString();
 
-                return netdataDashboard.anyAttribute(netdataDashboard.menu, 'icon', chart.menu, '<i class="fa fa-puzzle-piece" aria-hidden="true"></i>');
+                return this.anyAttribute(this.menu, 'icon', chart.menu, '<i class="fa fa-puzzle-piece" aria-hidden="true"></i>');
             },
 
-            menuInfo: function(menu) {
-                return netdataDashboard.anyAttribute(netdataDashboard.menu, 'info', menu, null);
+            menuInfo: function(chart) {
+                if(typeof chart.menu_pattern !== 'undefined')
+                    return this.anyAttribute(this.menu, 'info', chart.menu_pattern, null);
+
+                return this.anyAttribute(this.menu, 'info', chart.menu, null);
             },
 
-            menuHeight: function(menu, relative) {
-                return netdataDashboard.anyAttribute(netdataDashboard.menu, 'height', menu, 1.0) * relative;
+            menuHeight: function(chart) {
+                if(typeof chart.menu_pattern !== 'undefined')
+                    return this.anyAttribute(this.menu, 'height', chart.menu_pattern, 1.0);
+
+                return this.anyAttribute(this.menu, 'height', chart.menu, 1.0);
             },
 
             submenuTitle: function(menu, submenu) {
                 var key = menu + '.' + submenu;
-                var title = netdataDashboard.anyAttribute(netdataDashboard.submenu, 'title', key, submenu).toString().replace(/_/g, ' ');;
+                // console.log(key);
+                var title = this.anyAttribute(this.submenu, 'title', key, submenu).toString().replace(/_/g, ' ');
                 if(title.length > 28) {
                     var a = title.substring(0, 13);
                     var b = title.substring(title.length - 12, title.length);
 
             submenuInfo: function(menu, submenu) {
                 var key = menu + '.' + submenu;
-                return netdataDashboard.anyAttribute(netdataDashboard.submenu, 'info', key, null);
+                return this.anyAttribute(this.submenu, 'info', key, null);
             },
 
             submenuHeight: function(menu, submenu, relative) {
                 var key = menu + '.' + submenu;
-                return netdataDashboard.anyAttribute(netdataDashboard.submenu, 'height', key, 1.0) * relative;
+                return this.anyAttribute(this.submenu, 'height', key, 1.0) * relative;
             },
 
             contextInfo: function(id) {
-                if(typeof netdataDashboard.context[id] !== 'undefined' && typeof netdataDashboard.context[id].info !== 'undefined')
-                    return '<div class="chart-message netdata-chart-alignment" role="document">' + netdataDashboard.context[id].info + '</div>';
+                var x = this.anyAttribute(this.context, 'info', id, null);
+
+                if(x !== null)
+                    return '<div class="chart-message netdata-chart-alignment" role="document">' + x + '</div>';
                 else
                     return '';
             },
 
             contextValueRange: function(id) {
-                if(typeof netdataDashboard.context[id] !== 'undefined' && typeof netdataDashboard.context[id].valueRange !== 'undefined')
-                    return netdataDashboard.context[id].valueRange;
+                if(typeof this.context[id] !== 'undefined' && typeof this.context[id].valueRange !== 'undefined')
+                    return this.context[id].valueRange;
                 else
                     return '[null, null]';
             },
 
             contextHeight: function(id, def) {
-                if(typeof netdataDashboard.context[id] !== 'undefined' && typeof netdataDashboard.context[id].height !== 'undefined')
-                    return def * netdataDashboard.context[id].height;
+                if(typeof this.context[id] !== 'undefined' && typeof this.context[id].height !== 'undefined')
+                    return def * this.context[id].height;
                 else
                     return def;
             }
 
         // enrich the data structure returned by netdata
         // to reflect our menu system and content
+        // FIXME: this is a shame - we should fix charts naming (issue #807)
         function enrichChartData(chart) {
-            var tmp = chart.type.split('_')[0];
+            var parts = chart.type.split('_');
+            var tmp = parts[0];
 
             switch(tmp) {
                 case 'ap':
                     chart.menu = tmp;
                     break;
 
+                case 'apache':
+                    chart.menu = chart.type;
+                    if(parts.length > 2 && parts[1] === 'cache')
+                        chart.menu_pattern = tmp + '_' + parts[1];
+                    break;
+
+                case 'bind':
+                    chart.menu = chart.type;
+                    if(parts.length > 2 && parts[1] === 'rndc')
+                        chart.menu_pattern = tmp + '_' + parts[1];
+                    break;
+
                 case 'cgroup':
                     chart.menu = chart.type;
                     if(chart.id.match(/.*[\._\/-:]qemu[\._\/-:]*/) || chart.id.match(/.*[\._\/-:]kvm[\._\/-:]*/))
                         chart.menu_pattern = 'cgroup';
                     break;
 
-                case 'apache':
-                case 'exim':
+                case 'isc':
+                    chart.menu = chart.type;
+                    if(parts.length > 2 && parts[1] === 'dhcpd')
+                        chart.menu_pattern = tmp + '_' + parts[1];
+                    break;
+
+                case 'ovpn':
+                    chart.menu = chart.type;
+                    if(parts.length > 3 && parts[1] === 'status' && parts[2] === 'log')
+                        chart.menu_pattern = tmp + '_' + parts[1];
+                    break;
+
+                case 'smartd':
+                case 'web':
+                    chart.menu = chart.type;
+                    if(parts.length > 2 && parts[1] === 'log')
+                        chart.menu_pattern = tmp + '_' + parts[1];
+                    break;
+
                 case 'dovecot':
+                case 'exim':
                 case 'hddtemp':
                 case 'ipfs':
                 case 'memcached':
 
         // ----------------------------------------------------------------------------
 
-        function headMain(charts, duration) {
+        function headMain(os, charts, duration) {
+            void(os);
+
             var head = '';
 
             if(typeof charts['system.swap'] !== 'undefined')
                 var hi = 0, hlen = hcharts.length;
                 while(hi < hlen) {
                     if(typeof hcharts[hi] === 'function')
-                        head += hcharts[hi](chart.id).replace('CHART_DURATION', duration.toString()).replace('CHART_UNIQUE_ID', chart.id);
+                        head += hcharts[hi](netdataDashboard.os, chart.id).replace('CHART_DURATION', duration.toString()).replace('CHART_UNIQUE_ID', chart.id);
                     else
                         head += hcharts[hi].replace('CHART_DURATION', duration.toString()).replace('CHART_UNIQUE_ID', chart.id);
                     hi++;
             var duration = Math.round(($(div).width() * pcent_width / 100 * data.update_every / 3) / 60) * 60;
             var html = '';
             var sidebar = '<ul class="nav dashboard-sidenav" data-spy="affix" id="sidebar_ul">';
-            var mainhead = headMain(data.charts, duration);
+            var mainhead = headMain(netdataDashboard.os, data.charts, duration);
 
             // sort the menus
             var main = sortObjectByPriority(menus);
 
             sidebar += '<li class="" style="padding-top:15px;"><a href="https://github.com/firehol/netdata/wiki/Add-more-charts-to-netdata" target="_blank"><i class="fa fa-plus" aria-hidden="true"></i> add more charts</a></li>';
             sidebar += '<li class=""><a href="https://github.com/firehol/netdata/wiki/Add-more-alarms-to-netdata" target="_blank"><i class="fa fa-plus" aria-hidden="true"></i> add more alarms</a></li>';
-            sidebar += '<li class="" style="margin:20px;color:#666;"><small>netdata on <b>' + data.hostname.toString() + '</b>, collects every ' + ((data.update_every == 1)?'second':data.update_every.toString() + ' seconds') + ' <b>' + data.dimensions_count.toLocaleString() + '</b> metrics, presented as <b>' + data.charts_count.toLocaleString() + '</b> charts and monitored by <b>' + data.alarms_count.toLocaleString() + '</b> alarms, using ' + Math.round(data.rrd_memory_bytes / 1024 / 1024).toLocaleString() + ' MB of memory for ' + Math.round(data.history / (3600/data.update_every)).toLocaleString() + ' ' + ((data.history == (3600/data.update_every))?'hour':'hours').toString() + ' of real-time history.</small></li>';
+            sidebar += '<li class="" style="margin:20px;color:#666;"><small>netdata on <b>' + data.hostname.toString() + '</b>, collects every ' + ((data.update_every == 1)?'second':data.update_every.toString() + ' seconds') + ' <b>' + data.dimensions_count.toLocaleString() + '</b> metrics, presented as <b>' + data.charts_count.toLocaleString() + '</b> charts and monitored by <b>' + data.alarms_count.toLocaleString() + '</b> alarms, using ' + Math.round(data.rrd_memory_bytes / 1024 / 1024).toLocaleString() + ' MB of memory for ' + Math.round(data.history / (3600/data.update_every)).toLocaleString() + ' ' + ((data.history == (3600/data.update_every))?'hour':'hours').toString() + ' of real-time history.<br/>&nbsp;<br/><b>netdata</b><br/>v' +  data.version.toString() +'</small></li>';
             sidebar += '</ul>';
             div.innerHTML = html;
             document.getElementById('sidebar').innerHTML = sidebar;
         function renderChartsAndMenu(data) {
             var menus = options.menus;
             var charts = data.charts;
+            var m, menu_key;
 
             for(var c in charts) {
-                enrichChartData(charts[c]);
+                if(!charts.hasOwnProperty(c)) continue;
+
+                var chart = charts[c];
+                enrichChartData(chart);
+                m = chart.menu;
 
                 // create the menu
-                if(typeof menus[charts[c].menu] === 'undefined') {
-                    menus[charts[c].menu] = {
-                        priority: charts[c].priority,
+                if(typeof menus[m] === 'undefined') {
+                    menus[m] = {
+                        menu_pattern: chart.menu_pattern,
+                        priority: chart.priority,
                         submenus: {},
-                        title: netdataDashboard.menuTitle(charts[c]),
-                        icon: netdataDashboard.menuIcon(charts[c]),
-                        info: netdataDashboard.menuInfo(charts[c].menu),
-                        height: netdataDashboard.menuHeight(charts[c].menu, options.chartsHeight)
+                        title: netdataDashboard.menuTitle(chart),
+                        icon: netdataDashboard.menuIcon(chart),
+                        info: netdataDashboard.menuInfo(chart),
+                        height: netdataDashboard.menuHeight(chart) * options.chartsHeight
                     };
                 }
+                else {
+                    if(typeof(menus[m].menu_pattern) === 'undefined')
+                        menus[m].menu_pattern = chart.menu_pattern;
+
+                    if(chart.priority < menus[m].priority)
+                        menus[m].priority = chart.priority;
+                }
 
-                if(charts[c].priority < menus[charts[c].menu].priority)
-                    menus[charts[c].menu].priority = charts[c].priority;
+                menu_key = (typeof(menus[m].menu_pattern) !== 'undefined')?menus[m].menu_pattern:m;
 
                 // create the submenu
-                if(typeof menus[charts[c].menu].submenus[charts[c].submenu] === 'undefined') {
-                    menus[charts[c].menu].submenus[charts[c].submenu] = {
-                        priority: charts[c].priority,
-                        charts: new Array(),
+                if(typeof menus[m].submenus[chart.submenu] === 'undefined') {
+                    menus[m].submenus[chart.submenu] = {
+                        priority: chart.priority,
+                        charts: [],
                         title: null,
-                        info: netdataDashboard.submenuInfo(charts[c].menu, charts[c].submenu),
-                        height: netdataDashboard.submenuHeight(charts[c].menu, charts[c].submenu, menus[charts[c].menu].height)
+                        info: netdataDashboard.submenuInfo(menu_key, chart.submenu),
+                        height: netdataDashboard.submenuHeight(menu_key, chart.submenu, menus[m].height)
                     };
                 }
-
-                if(charts[c].priority < menus[charts[c].menu].submenus[charts[c].submenu].priority)
-                    menus[charts[c].menu].submenus[charts[c].submenu].priority = charts[c].priority;
+                else {
+                    if (chart.priority < menus[m].submenus[chart.submenu].priority)
+                        menus[m].submenus[chart.submenu].priority = chart.priority;
+                }
 
                 // index the chart in the menu/submenu
-                menus[charts[c].menu].submenus[charts[c].submenu].charts.push(charts[c]);
+                menus[m].submenus[chart.submenu].charts.push(chart);
             }
 
             // propagate the descriptive subname given to QoS
             // to all the other submenus with the same name
-            for(var m in menus) {
+            for(m in menus) {
+                if(!menus.hasOwnProperty(m)) continue;
+
                 for(var s in menus[m].submenus) {
+                    if(!menus[m].submenus.hasOwnProperty(s)) continue;
+
                     // set the family using a name
                     if(typeof options.submenu_names[s] !== 'undefined') {
                         menus[m].submenus[s].title = s + ' (' + options.submenu_names[s] + ')';
                     }
                     else {
-                        menus[m].submenus[s].title = netdataDashboard.submenuTitle(m, s);
+                        menu_key = (typeof(menus[m].menu_pattern) !== 'undefined')?menus[m].menu_pattern:m;
+                        menus[m].submenus[s].title = netdataDashboard.submenuTitle(menu_key, s);
                     }
                 }
             }
         var bootstrapTableLoaded = false;
         function loadBootstrapTable(callback) {
             if(bootstrapTableLoaded === false) {
-                bootstrapTableLoaded === true;
+                bootstrapTableLoaded = true;
                 loadJs(NETDATA.serverDefault + 'lib/bootstrap-table-1.11.0.min.js', function() {
                     loadJs(NETDATA.serverDefault + 'lib/bootstrap-table-export-1.11.0.min.js', function() {
                         loadJs(NETDATA.serverDefault + 'lib/tableExport-1.6.0.min.js', callback);
             var footer = '<hr/><a href="https://github.com/firehol/netdata/wiki/Generating-Badges" target="_blank">netdata badges</a> refresh automatically. Their color indicates the state of the alarm: <span style="color: #e05d44"><b>&nbsp;red&nbsp;</b></span> is critical, <span style="color:#fe7d37"><b>&nbsp;orange&nbsp;</b></span> is warning, <span style="color: #4c1"><b>&nbsp;bright green&nbsp;</b></span> is ok, <span style="color: #9f9f9f"><b>&nbsp;light grey&nbsp;</b></span> is undefined (i.e. no data or no status), <span style="color: #000"><b>&nbsp;black&nbsp;</b></span> is not initialized. You can copy and paste their URLs to embed them in any web page.<br/>netdata can send notifications for these alarms. Check <a href="https://github.com/firehol/netdata/blob/master/conf.d/health_alarm_notify.conf">this configuration file</a> for more information.';
 
             NETDATA.alarms.get('all', function(data) {
-                options.alarm_families = new Array();
+                options.alarm_families = [];
 
                 alarmsCallback(data);
 
                         return '';
                     }
 
-                    var has_alarm = ((typeof alarm.warn !== 'undefined' || typeof alarm.crit !== 'undefined')?true:false);
+                    var has_alarm = (typeof alarm.warn !== 'undefined' || typeof alarm.crit !== 'undefined');
 
                     var role_href = ((has_alarm === true)?('<br/>&nbsp;<br/>role: <b>' + alarm.recipient + '</b><br/>&nbsp;<br/><b><i class="fa fa-line-chart" aria-hidden="true"></i></b><small>&nbsp;&nbsp;<a href="#" onClick="NETDATA.alarms.scrollToChart(\'' + alarm.chart + '\'); $(\'#alarmsModal\').modal(\'hide\'); return false;">jump to chart</a></small>'):('&nbsp;'));
 
 
                 // find the proper family of each alarm
                 var now = Date.now();
-                var x;
+                var x, family, alarm;
                 var count_active = 0;
                 var count_all = 0;
                 var families = {};
-                var families_sort = new Array();
+                var families_sort = [];
                 for(x in data.alarms) {
-                    var alarm = data.alarms[x];
-                    var family = alarm.family;
+                    if(!data.alarms.hasOwnProperty(x)) continue;
+
+                    alarm = data.alarms[x];
+                    family = alarm.family;
 
                     // find the chart
                     var chart = options.data.charts[alarm.chart];
                     if(typeof families[family] === 'undefined') {
                         families[family] = {
                             name: family,
-                            arr: new Array(),
+                            arr: [],
                             priority: chart.priority
                         };
 
                 var fc = 0;
                 var len = families_sorted.length;
                 while(len--) {
-                    var family = families_sorted[len].name;
+                    family = families_sorted[len].name;
                     var active_family_added = false;
                     var expanded = 'true';
                     var collapsed = '';
                     if(fc !== 0) {
                         all += "</table></div></div></div>";
                         expanded = 'false';
-                        collapsed = 'class="collapsed"'
+                        collapsed = 'class="collapsed"';
                         cin = '';
                     }
 
                     var arr = families[family].arr;
                     var c = arr.length;
                     while(c--) {
-                        var alarm = arr[c];
+                        alarm = arr[c];
                         if(alarm.status === 'WARNING' || alarm.status === 'CRITICAL') {
                             if(!active_family_added) {
                                 active_family_added = true;
                 if(families_sorted.length > 0) alarm_family_show(0);
 
                 // register bootstrap events
-                $('#alarms_all_accordion').on('show.bs.collapse', function (d) {
+                var $accordion = $('#alarms_all_accordion');
+                $accordion.on('show.bs.collapse', function (d) {
                     var target = $(d.target);
                     var id = $(target).data('alarm-id');
                     alarm_family_show(id);
                 });
-                $('#alarms_all_accordion').on('hidden.bs.collapse', function (d) {
+                $accordion.on('hidden.bs.collapse', function (d) {
                     var target = $(d.target);
                     var id = $(target).data('alarm-id');
                     $('#alarm_all_' + id.toString()).html('');
                             fileName: 'netdata_alarm_log'
                         },
                         rowStyle: function(row, index) {
+                            void(index);
+
                             switch(row.status) {
                                 case 'CRITICAL' : return { classes: 'danger'  }; break;
                                 case 'WARNING'  : return { classes: 'warning' }; break;
                                 title: 'Event Date',
                                 valign: 'middle',
                                 titleTooltip: 'The date and time the even took place',
-                                formatter: function(value, row, index) { return timestamp4human(value, ' '); },
+                                formatter: function(value, row, index) { void(row); void(index); return timestamp4human(value, ' '); },
                                 align: 'center',
-                                valign: 'middle',
                                 switchable: false,
                                 sortable: true
                             },
                                 valign: 'middle',
                                 titleTooltip: 'The host that generated this event',
                                 align: 'center',
-                                valign: 'middle',
                                 visible: false,
                                 sortable: true
                             },
                                 field: 'unique_id',
                                 title: 'Unique ID',
                                 titleTooltip: 'The host unique ID for this event',
-                                formatter: function(value, row, index) { return alarmid4human(value); },
+                                formatter: function(value, row, index) { void(row); void(index); return alarmid4human(value); },
                                 align: 'center',
                                 valign: 'middle',
                                 visible: false,
                                 field: 'alarm_id',
                                 title: 'Alarm ID',
                                 titleTooltip: 'The ID of the alarm that generated this event',
-                                formatter: function(value, row, index) { return alarmid4human(value); },
+                                formatter: function(value, row, index) { void(row); void(index); return alarmid4human(value); },
                                 align: 'center',
                                 valign: 'middle',
                                 visible: false,
                                 field: 'alarm_event_id',
                                 title: 'Alarm Event ID',
                                 titleTooltip: 'The incremental ID of this event for the given alarm',
-                                formatter: function(value, row, index) { return alarmid4human(value); },
+                                formatter: function(value, row, index) { void(row); void(index); return alarmid4human(value); },
                                 align: 'center',
                                 valign: 'middle',
                                 visible: false,
                                 title: 'Alarm',
                                 titleTooltip: 'The alarm name that generated this event',
                                 formatter: function(value, row, index) {
+                                    void(row);
+                                    void(index);
                                     return value.toString().replace(/_/g, ' ');
                                 },
                                 align: 'center',
                                 title: 'Old Value',
                                 titleTooltip: 'The value of the alarm, just before this event',
                                 formatter: function(value, row, index) {
+                                    void(row);
+                                    void(index);
                                     return ((value !== null)?Math.round(value * 100) / 100:'NaN').toString();
                                 },
                                 align: 'center',
                                 title: 'Value',
                                 titleTooltip: 'The value of the alarm, that triggered this event',
                                 formatter: function(value, row, index) {
+                                    void(row);
+                                    void(index);
                                     return ((value !== null)?Math.round(value * 100) / 100:'NaN').toString();
                                 },
                                 align: 'right',
                                 field: 'duration',
                                 title: 'Last Duration',
                                 titleTooltip: 'The duration the alarm was at its previous state, just before this event',
-                                formatter: function(value, row, index) { return seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' }); },
+                                formatter: function(value, row, index) {
+                                    void(row);
+                                    void(index);
+                                    return seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' });
+                                },
                                 align: 'center',
                                 valign: 'middle',
                                 visible: false,
                                 field: 'non_clear_duration',
                                 title: 'Raised Duration',
                                 titleTooltip: 'The duration the alarm was raised, just before this event',
-                                formatter: function(value, row, index) { return seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' }); },
+                                formatter: function(value, row, index) {
+                                    void(row);
+                                    void(index);
+                                    return seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' });
+                                },
                                 align: 'center',
                                 valign: 'middle',
                                 visible: false,
                                 title: 'Processed Status',
                                 titleTooltip: 'True when this event is processed',
                                 formatter: function(value, row, index) {
+                                    void(row);
+                                    void(index);
+
                                     if(value === true)
                                         return 'DONE';
                                     else
                                 title: 'Updated Status',
                                 titleTooltip: 'True when this event has been updated by another event',
                                 formatter: function(value, row, index) {
+                                    void(row);
+                                    void(index);
+
                                     if(value === true)
                                         return 'UPDATED';
                                     else
                                 field: 'updated_by_id',
                                 title: 'Updated By ID',
                                 titleTooltip: 'The unique ID of the event that obsoleted this one',
-                                formatter: function(value, row, index) { return alarmid4human(value); },
+                                formatter: function(value, row, index) { void(row); void(index); return alarmid4human(value); },
                                 align: 'center',
                                 valign: 'middle',
                                 visible: false,
                                 field: 'updates_id',
                                 title: 'Updates ID',
                                 titleTooltip: 'The unique ID of the event obsoleted because of this event',
-                                formatter: function(value, row, index) { return alarmid4human(value); },
+                                formatter: function(value, row, index) { void(row); void(index); return alarmid4human(value); },
                                 align: 'center',
                                 valign: 'middle',
                                 visible: false,
                                 field: 'exec_run',
                                 title: 'Script Run At',
                                 titleTooltip: 'The date and time the script has been ran',
-                                formatter: function(value, row, index) { return timestamp4human(value, ' '); },
+                                formatter: function(value, row, index) { void(row); void(index); return timestamp4human(value, ' '); },
                                 align: 'center',
                                 valign: 'middle',
                                 visible: false,
                                 title: 'Script Return Value',
                                 titleTooltip: 'The return code of the script',
                                 formatter: function(value, row, index) {
+                                    void(row);
+                                    void(index);
+
                                     if(value === 0)
                                         return 'OK (returned 0)';
                                     else
                                 field: 'delay',
                                 title: 'Script Delay',
                                 titleTooltip: 'The hysteresis of the notification',
-                                formatter: function(value, row, index) { return seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' }); },
+                                formatter: function(value, row, index) {
+                                    void(row);
+                                    void(index);
+
+                                    return seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' });
+                                },
                                 align: 'center',
                                 valign: 'middle',
                                 visible: false,
                                 field: 'delay_up_to_timestamp',
                                 title: 'Script Delay Run At',
                                 titleTooltip: 'The date and time the script should be run, after hysteresis',
-                                formatter: function(value, row, index) { return timestamp4human(value, ' '); },
+                                formatter: function(value, row, index) { void(row); void(index); return timestamp4human(value, ' '); },
                                 align: 'center',
                                 valign: 'middle',
                                 visible: false,
         function alarmsCallback(data) {
             var count = 0;
             for(x in data.alarms) {
+                if(!data.alarms.hasOwnProperty(x)) continue;
+
                 var alarm = data.alarms[x];
                 if(alarm.status === 'WARNING' || alarm.status === 'CRITICAL')
                     count++;
                     if(data !== null) {
                         options.hostname = data.hostname;
                         options.data = data;
+                        options.version = data.version;
+                        netdataDashboard.os = data.os;
 
                         // update the dashboard hostname
                         document.getElementById('hostname').innerHTML = options.hostname;
                         document.getElementById('hostname').href = NETDATA.serverDefault;
+                        document.getElementById('netdataVersion').innerHTML = options.version;
 
                         // update the dashboard title
                         document.title = options.hostname + ' netdata dashboard';
                         var charts = data.charts;
                         var x;
                         for(x in charts) {
+                            if(!charts.hasOwnProperty(x)) continue;
+
                             var chart = charts[x];
                             data.charts_by_name[chart.name] = chart;
                         }
             document.getElementById('versionCheckLog').innerHTML = msg;
         }
 
-        function getNetdataVersion(callback) {
-            versionLog('Downloading installed version info from netdata...');
+        function getNetdataCommitIdFromVersion() {
+            var s = options.version.split('-');
+
+            if(s.length !== 3) return null;
+            if(s[2][0] == 'g') {
+                var v = s[2].split('_')[0].substring(1, 8);
+                if(v.length === 7) {
+                    versionLog('Installed git commit id of netdata is ' + v);
+                    document.getElementById('netdataCommitId').innerHTML = v;
+                    return v;
+                }
+            }
+            return null;
+        }
+
+        function getNetdataCommitId(force, callback) {
+            versionLog('Downloading installed git commit id from netdata...');
 
             $.ajax({
                 url: 'version.txt',
             })
             .done(function(data) {
                 data = data.replace(/(\r\n|\n|\r| |\t)/gm,"");
-                if(data.length !== 40) {
-                    versionLog('Received version string is invalid.');
-                    callback(null);
+
+                var c = getNetdataCommitIdFromVersion();
+                if(c !== null && data.length === 40 && data.substring(0, 7) !== c) {
+                    versionLog('Installed files commit id and internal netdata git commit id do not match');
+                    data = c;
                 }
-                else {
-                    versionLog('Installed version of netdata is ' + data);
-                    document.getElementById('netdataVersion').innerHTML = data;
+
+                if(data.length >= 7) {
+                    versionLog('Installed git commit id of netdata is ' + data);
+                    document.getElementById('netdataCommitId').innerHTML = data.substring(0, 7);
                     callback(data);
                 }
             })
             .fail(function() {
-                versionLog('Failed to download installed version info from netdata!');
-                callback(null);
+                versionLog('Failed to download installed git commit id from netdata!');
+
+                if(force === true) {
+                    var c = getNetdataCommitIdFromVersion();
+                    if(c === null) versionLog('Cannot find the git commit id of netdata.');
+                    callback(c);
+                }
+                else
+                    callback(null);
             });
         }
 
         function getGithubLatestCommit(callback) {
-            versionLog('Downloading latest version info from github...');
+            versionLog('Downloading latest git commit id info from github...');
 
             $.ajax({
                 url: 'https://api.github.com/repos/firehol/netdata/commits',
                 cache: false
             })
             .done(function(data) {
-                versionLog('Latest version info from github is ' + data[0].sha);
+                versionLog('Latest git commit id from github is ' + data[0].sha);
                 callback(data[0].sha);
             })
             .fail(function() {
-                versionLog('Failed to download installed version info from github!');
+                versionLog('Failed to download installed git commit id from github!');
                 callback(null);
             });
         }
 
-        function checkForUpdate(callback) {
-            getNetdataVersion(function(sha1) {
+        function checkForUpdate(force, callback) {
+            getNetdataCommitId(force, function(sha1) {
                 if(sha1 === null) callback(null, null);
 
                 getGithubLatestCommit(function(sha2) {
                 }
             }
 
-            checkForUpdate(function(sha1, sha2) {
+            checkForUpdate(force, function(sha1, sha2) {
                 var save = false;
 
                 if(sha1 === null) {
                     save = false;
-                    versionLog('<p><big>Failed to get your netdata version!</big></p><p>You can always get the latest version of netdata from <a href="https://github.com/firehol/netdata" target="_blank">its github page</a>.</p>');
+                    versionLog('<p><big>Failed to get your netdata git commit id!</big></p><p>You can always get the latest netdata from <a href="https://github.com/firehol/netdata" target="_blank">its github page</a>.</p>');
                 }
                 else if(sha2 === null) {
                     save = false;
-                    versionLog('<p><big>Failed to get the latest version from github.</big></p><p>You can always get the latest version of netdata from <a href="https://github.com/firehol/netdata" target="_blank">its github page</a>.</p>');
+                    versionLog('<p><big>Failed to get the latest git commit id from github.</big></p><p>You can always get the latest netdata from <a href="https://github.com/firehol/netdata" target="_blank">its github page</a>.</p>');
                 }
                 else if(sha1 === sha2) {
                     save = true;
-                    versionLog('<p><big>You already have the latest version of netdata!</big></p><p>No update yet?<br/>Probably, we need some motivation to keep going on!</p><p>If you haven\'t already, <a href="https://github.com/firehol/netdata" target="_blank">give netdata a <b>Star</b> at its github page</a>.</p>');
+                    versionLog('<p><big>You already have the latest netdata!</big></p><p>No update yet?<br/>Probably, we need some motivation to keep going on!</p><p>If you haven\'t already, <a href="https://github.com/firehol/netdata" target="_blank">give netdata a <b>Star</b> at its github page</a>.</p>');
                 }
                 else {
                     save = true;
                     var compare = 'https://github.com/firehol/netdata/compare/' + sha1.toString() + '...' + sha2.toString();
 
-                    versionLog('<p><big><strong>New version of netdata available!</strong></big></p><p>Latest version: ' + sha2.toString() + '</p><p><a href="' + compare + '" target="_blank">Click here for the changes log</a> since your installed version, and<br/><a href="https://github.com/firehol/netdata/wiki/Updating-Netdata" target="_blank">click here for directions on updating</a> your netdata installation.</p><p>We suggest to review the changes log for new features you may be interested, or important bug fixes you may need.<br/>Keeping your netdata updated, is generally a good idea.</p>');
+                    versionLog('<p><big><strong>New version of netdata available!</strong></big></p><p>Latest commit: <b><code>' + sha2.substring(0, 7).toString() + '</code></b></p><p><a href="' + compare + '" target="_blank">Click here for the changes log</a> since your installed version, and<br/><a href="https://github.com/firehol/netdata/wiki/Updating-Netdata" target="_blank">click here for directions on updating</a> your netdata installation.</p><p>We suggest to review the changes log for new features you may be interested, or important bug fixes you may need.<br/>Keeping your netdata updated, is generally a good idea.</p>');
 
                     document.getElementById('update_badge').innerHTML = '!';
                 }
                                         {
                                             //console.log('They were open tags');
                                             //console.log(openTags);
-                                            for (j = 0; j < openTags.length; j++) {
+                                            for (var j = 0; j < openTags.length; j++) {
                                                 //console.log('Cierro tag ' + openTags[j]);
                                                 bag += '</' + openTags[j] + '>'; // Close all tags that were opened
 
                 //console.log('hash = ' + urlOptions.hash);
             }
 
+            var $sidebar = $('#sidebar');
             /* activate bootstrap sidebar (affix) */
-            $('#sidebar').affix({
+            $sidebar.affix({
                 offset: {
                     top: (isdemo())?150:0,
                     bottom: 0
             /* fix scrolling of very long affix lists
                http://stackoverflow.com/questions/21691585/bootstrap-3-1-0-affix-too-long
              */
-            $('#sidebar').on('affixed.bs.affix', function() {
+            $sidebar.on('affixed.bs.affix', function() {
                 $(this).removeAttr('style');
             });
 
             });
 
             // change the URL based on the current position of the screen
-            $('#sidebar').on('activate.bs.scrollspy', function (e) {
+            $sidebar.on('activate.bs.scrollspy', function (e) {
                 // console.log(e);
                 var el = $(e.target);
                 //if(el.find('ul').size() == 0) {
                         // console.log('switching ' + option.toString());
                         self.bootstrapToggle(NETDATA.getOption(option)?'on':'off');
                     }
-                }
+                };
 
                 var theme_sync_option = function(option) {
                     var self = $('#' + option);
 
                     self.bootstrapToggle(netdataTheme === 'slate'?'on':'off');
-                }
+                };
 
                 sync_option('eliminate_zero_dimensions');
                 sync_option('destroy_on_hide');
                     netdataReload();
             });
 
-            $('#updateModal').on('show.bs.modal', function() {
+            var $updateModal = $('#updateModal');
+            $updateModal.on('show.bs.modal', function() {
                 versionLog('checking, please wait...');
             });
 
-            $('#updateModal').on('shown.bs.modal', function() {
+            $updateModal.on('shown.bs.modal', function() {
                 notifyForUpdate(true);
             });
 
-            $('#alarmsModal').on('shown.bs.modal', function() {
+            var $alarmsModal = $('#alarmsModal');
+            $alarmsModal.on('shown.bs.modal', function() {
                 NETDATA.pause(alarmsUpdateModal);
             });
 
-            $('#alarmsModal').on('hidden.bs.modal', function() {
+            $alarmsModal.on('hidden.bs.modal', function() {
                 NETDATA.unpause();
                 document.getElementById('alarms_active').innerHTML =
                         document.getElementById('alarms_all').innerHTML =
             });
 
             NETDATA.requiredJs.push({
-                url: NETDATA.serverDefault + 'dashboard_info.js?v20170115-1',
+                url: NETDATA.serverDefault + 'dashboard_info.js?v20170211-20',
                 async: false,
                 isAlreadyLoaded: function() { return false; }
             });
                     <h4 class="modal-title" id="updateModalLabel">Update Check</h4>
                 </div>
                 <div class="modal-body">
-                    Your netdata version: <b><code><span id="netdataVersion">Unknown</span></code></b>
+                    Your netdata version: <b><code><span id="netdataVersion">Unknown</span></code></b><br/>
+                    Your netdata commit: <b><code><span id="netdataCommitId">Unknown</span></code></b>
                     <br/>
                     <div style="padding: 10px;"></div>
                     <div id="versionCheckLog">Not checked yet. Please press the Check Now button.</div>
     </div>
 </body>
 </html>
-<script type="text/javascript" src="dashboard.js?v20170204-1"></script>
+<script type="text/javascript" src="dashboard.js?v20170211-2"></script>
diff --git a/web/lib/gauge-1.3.2.min.js b/web/lib/gauge-1.3.2.min.js
new file mode 100644 (file)
index 0000000..be327fe
--- /dev/null
@@ -0,0 +1 @@
+(function(){var a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p=[].slice,q={}.hasOwnProperty,r=function(a,b){function d(){this.constructor=a}for(var c in b)q.call(b,c)&&(a[c]=b[c]);return d.prototype=b.prototype,a.prototype=new d,a.__super__=b.prototype,a};!function(){var a,b,c,d,e,f,g;for(g=["ms","moz","webkit","o"],c=0,e=g.length;c<e&&(f=g[c],!window.requestAnimationFrame);c++)window.requestAnimationFrame=window[f+"RequestAnimationFrame"],window.cancelAnimationFrame=window[f+"CancelAnimationFrame"]||window[f+"CancelRequestAnimationFrame"];return a=null,d=0,b={},requestAnimationFrame?window.cancelAnimationFrame?void 0:(a=window.requestAnimationFrame,window.requestAnimationFrame=function(c,e){var f;return f=++d,a(function(){if(!b[f])return c()},e),f},window.cancelAnimationFrame=function(a){return b[a]=!0}):(window.requestAnimationFrame=function(a,b){var c,d,e,f;return c=(new Date).getTime(),f=Math.max(0,16-(c-e)),d=window.setTimeout(function(){return a(c+f)},f),e=c+f,d},window.cancelAnimationFrame=function(a){return clearTimeout(a)})}(),String.prototype.hashCode=function(){var a,b,c,d,e;if(b=0,0===this.length)return b;for(c=d=0,e=this.length;0<=e?d<e:d>e;c=0<=e?++d:--d)a=this.charCodeAt(c),b=(b<<5)-b+a,b&=b;return b},o=function(a){var b,c;for(b=Math.floor(a/3600),c=Math.floor((a-3600*b)/60),a-=3600*b+60*c,a+="",c+="";c.length<2;)c="0"+c;for(;a.length<2;)a="0"+a;return b=b?b+":":"",b+c+":"+a},m=function(){var a,b,c;return b=1<=arguments.length?p.call(arguments,0):[],c=b[0],a=b[1],k(c.toFixed(a))},n=function(a,b){var c,d,e;d={};for(c in a)q.call(a,c)&&(e=a[c],d[c]=e);for(c in b)q.call(b,c)&&(e=b[c],d[c]=e);return d},k=function(a){var b,c,d,e;for(a+="",c=a.split("."),d=c[0],e="",c.length>1&&(e="."+c[1]),b=/(\d+)(\d{3})/;b.test(d);)d=d.replace(b,"$1,$2");return d+e},l=function(a){return"#"===a.charAt(0)?a.substring(1,7):a},j=function(){function a(a,b){null==a&&(a=!0),this.clear=null==b||b,a&&AnimationUpdater.add(this)}return a.prototype.animationSpeed=32,a.prototype.update=function(a){var b;return null==a&&(a=!1),!(!a&&this.displayedValue===this.value)&&(this.ctx&&this.clear&&this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),b=this.value-this.displayedValue,Math.abs(b/this.animationSpeed)<=.001?this.displayedValue=this.value:this.displayedValue=this.displayedValue+b/this.animationSpeed,this.render(),!0)},a}(),e=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return r(b,a),b.prototype.displayScale=1,b.prototype.setTextField=function(a,b){return this.textField=a instanceof i?a:new i(a,b)},b.prototype.setMinValue=function(a,b){var c,d,e,f,g;if(this.minValue=a,null==b&&(b=!0),b){for(this.displayedValue=this.minValue,f=this.gp||[],g=[],d=0,e=f.length;d<e;d++)c=f[d],g.push(c.displayedValue=this.minValue);return g}},b.prototype.setOptions=function(a){return null==a&&(a=null),this.options=n(this.options,a),this.textField&&(this.textField.el.style.fontSize=a.fontSize+"px"),this.options.angle>.5&&(this.options.angle=.5),this.configDisplayScale(),this},b.prototype.configDisplayScale=function(){var a,b,c,d,e;return d=this.displayScale,this.options.highDpiSupport===!1?delete this.displayScale:(b=window.devicePixelRatio||1,a=this.ctx.webkitBackingStorePixelRatio||this.ctx.mozBackingStorePixelRatio||this.ctx.msBackingStorePixelRatio||this.ctx.oBackingStorePixelRatio||this.ctx.backingStorePixelRatio||1,this.displayScale=b/a),this.displayScale!==d&&(e=this.canvas.G__width||this.canvas.width,c=this.canvas.G__height||this.canvas.height,this.canvas.width=e*this.displayScale,this.canvas.height=c*this.displayScale,this.canvas.style.width=e+"px",this.canvas.style.height=c+"px",this.canvas.G__width=e,this.canvas.G__height=c),this},b}(j),i=function(){function a(a,b){this.el=a,this.fractionDigits=b}return a.prototype.render=function(a){return this.el.innerHTML=m(a.displayedValue,this.fractionDigits)},a}(),a=function(a){function b(a,b){this.elem=a,this.text=null!=b&&b,this.value=1*this.elem.innerHTML,this.text&&(this.value=0)}return r(b,a),b.prototype.displayedValue=0,b.prototype.value=0,b.prototype.setVal=function(a){return this.value=1*a},b.prototype.render=function(){var a;return a=this.text?o(this.displayedValue.toFixed(0)):k(m(this.displayedValue)),this.elem.innerHTML=a},b}(j),b={create:function(b){var c,d,e,f;for(f=[],d=0,e=b.length;d<e;d++)c=b[d],f.push(new a(c));return f}},h=function(a){function b(a){this.gauge=a,this.ctx=this.gauge.ctx,this.canvas=this.gauge.canvas,b.__super__.constructor.call(this,!1,!1),this.setOptions()}return r(b,a),b.prototype.displayedValue=0,b.prototype.value=0,b.prototype.options={strokeWidth:.035,length:.1,color:"#000000"},b.prototype.setOptions=function(a){return null==a&&(a=null),this.options=n(this.options,a),this.length=2*this.gauge.radius*this.gauge.options.radiusScale*this.options.length,this.strokeWidth=this.canvas.height*this.options.strokeWidth,this.maxValue=this.gauge.maxValue,this.minValue=this.gauge.minValue,this.animationSpeed=this.gauge.animationSpeed,this.options.angle=this.gauge.options.angle},b.prototype.render=function(){var a,b,c,d,e,f,g;return a=this.gauge.getAngle.call(this,this.displayedValue),f=Math.round(this.length*Math.cos(a)),g=Math.round(this.length*Math.sin(a)),d=Math.round(this.strokeWidth*Math.cos(a-Math.PI/2)),e=Math.round(this.strokeWidth*Math.sin(a-Math.PI/2)),b=Math.round(this.strokeWidth*Math.cos(a+Math.PI/2)),c=Math.round(this.strokeWidth*Math.sin(a+Math.PI/2)),this.ctx.fillStyle=this.options.color,this.ctx.beginPath(),this.ctx.arc(0,0,this.strokeWidth,0,2*Math.PI,!0),this.ctx.fill(),this.ctx.beginPath(),this.ctx.moveTo(d,e),this.ctx.lineTo(f,g),this.ctx.lineTo(b,c),this.ctx.fill()},b}(j),c=function(){function a(a){this.elem=a}return a.prototype.updateValues=function(a){return this.value=a[0],this.maxValue=a[1],this.avgValue=a[2],this.render()},a.prototype.render=function(){var a,b;return this.textField&&this.textField.text(m(this.value)),0===this.maxValue&&(this.maxValue=2*this.avgValue),b=this.value/this.maxValue*100,a=this.avgValue/this.maxValue*100,$(".bar-value",this.elem).css({width:b+"%"}),$(".typical-value",this.elem).css({width:a+"%"})},a}(),g=function(a){function b(a){var c,d;this.canvas=a,b.__super__.constructor.call(this),this.percentColors=null,this.forceUpdate=!0,"undefined"!=typeof G_vmlCanvasManager&&(this.canvas=window.G_vmlCanvasManager.initElement(this.canvas)),this.ctx=this.canvas.getContext("2d"),c=this.canvas.clientHeight,d=this.canvas.clientWidth,this.canvas.height=c,this.canvas.width=d,this.gp=[new h(this)],this.setOptions(),this.render()}return r(b,a),b.prototype.elem=null,b.prototype.value=[20],b.prototype.maxValue=80,b.prototype.minValue=0,b.prototype.displayedAngle=0,b.prototype.displayedValue=0,b.prototype.lineWidth=40,b.prototype.paddingTop=.1,b.prototype.paddingBottom=.1,b.prototype.percentColors=null,b.prototype.options={colorStart:"#6fadcf",colorStop:void 0,gradientType:0,strokeColor:"#e0e0e0",pointer:{length:.8,strokeWidth:.035},angle:.15,lineWidth:.44,radiusScale:1,fontSize:40,limitMax:!1,limitMin:!1},b.prototype.setOptions=function(a){var c,d,e,f,g;for(null==a&&(a=null),b.__super__.setOptions.call(this,a),this.configPercentColors(),this.extraPadding=0,this.options.angle<0&&(f=Math.PI*(1+this.options.angle),this.extraPadding=Math.sin(f)),this.availableHeight=this.canvas.height*(1-this.paddingTop-this.paddingBottom),this.lineWidth=this.availableHeight*this.options.lineWidth,this.radius=(this.availableHeight-this.lineWidth/2)/(1+this.extraPadding),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),g=this.gp,d=0,e=g.length;d<e;d++)c=g[d],c.setOptions(this.options.pointer),c.render();return this},b.prototype.configPercentColors=function(){var a,b,c,d,e,f,g;if(this.percentColors=null,void 0!==this.options.percentColors){for(this.percentColors=new Array,f=[],c=d=0,e=this.options.percentColors.length-1;0<=e?d<=e:d>=e;c=0<=e?++d:--d)g=parseInt(l(this.options.percentColors[c][1]).substring(0,2),16),b=parseInt(l(this.options.percentColors[c][1]).substring(2,4),16),a=parseInt(l(this.options.percentColors[c][1]).substring(4,6),16),f.push(this.percentColors[c]={pct:this.options.percentColors[c][0],color:{r:g,g:b,b:a}});return f}},b.prototype.set=function(a){var b,c,d,e,f,g,i;if(a instanceof Array||(a=[a]),a.length>this.gp.length)for(c=d=0,g=a.length-this.gp.length;0<=g?d<g:d>g;c=0<=g?++d:--d)b=new h(this),b.setOptions(this.options.pointer),this.gp.push(b);else a.length<this.gp.length&&(this.gp=this.gp.slice(this.gp.length-a.length));for(c=0,e=0,f=a.length;e<f;e++)i=a[e],i>this.maxValue?this.options.limitMax?i=this.maxValue:this.maxValue=i+1:i<this.minValue&&(this.options.limitMin?i=this.minValue:this.minValue=i-1),this.gp[c].value=i,this.gp[c++].setOptions({minValue:this.minValue,maxValue:this.maxValue,angle:this.options.angle});return this.value=Math.max(Math.min(a[a.length-1],this.maxValue),this.minValue),AnimationUpdater.run(this.forceUpdate),this.forceUpdate=!1},b.prototype.getAngle=function(a){return(1+this.options.angle)*Math.PI+(a-this.minValue)/(this.maxValue-this.minValue)*(1-2*this.options.angle)*Math.PI},b.prototype.getColorForPercentage=function(a,b){var c,d,e,f,g,h,i;if(0===a)c=this.percentColors[0].color;else for(c=this.percentColors[this.percentColors.length-1].color,e=f=0,h=this.percentColors.length-1;0<=h?f<=h:f>=h;e=0<=h?++f:--f)if(a<=this.percentColors[e].pct){b===!0?(i=this.percentColors[e-1]||this.percentColors[0],d=this.percentColors[e],g=(a-i.pct)/(d.pct-i.pct),c={r:Math.floor(i.color.r*(1-g)+d.color.r*g),g:Math.floor(i.color.g*(1-g)+d.color.g*g),b:Math.floor(i.color.b*(1-g)+d.color.b*g)}):c=this.percentColors[e].color;break}return"rgb("+[c.r,c.g,c.b].join(",")+")"},b.prototype.getColorForValue=function(a,b){var c;return c=(a-this.minValue)/(this.maxValue-this.minValue),this.getColorForPercentage(c,b)},b.prototype.renderStaticLabels=function(a,b,c,d){var e,f,g,h,i,j,k,l,n,o;for(this.ctx.save(),this.ctx.translate(b,c),e=a.font||"10px Times",j=/\d+\.?\d?/,i=e.match(j)[0],l=e.slice(i.length),f=parseFloat(i)*this.displayScale,this.ctx.font=f+l,this.ctx.fillStyle=a.color||"#000000",this.ctx.textBaseline="bottom",this.ctx.textAlign="center",k=a.labels,g=0,h=k.length;g<h;g++)o=k[g],(!this.options.limitMin||o>=this.minValue)&&(!this.options.limitMax||o<=this.maxValue)&&(n=this.getAngle(o)-3*Math.PI/2,this.ctx.rotate(n),this.ctx.fillText(m(o,a.fractionDigits),0,-d-this.lineWidth/2),this.ctx.rotate(-n));return this.ctx.restore()},b.prototype.render=function(){var a,b,c,d,e,f,g,h,i,j,k,l,m,n,o;if(n=this.canvas.width/2,d=this.canvas.height*this.paddingTop+this.availableHeight-(this.radius+this.lineWidth/2)*this.extraPadding,a=this.getAngle(this.displayedValue),this.textField&&this.textField.render(this),this.ctx.lineCap="butt",k=this.radius*this.options.radiusScale,this.options.staticLabels&&this.renderStaticLabels(this.options.staticLabels,n,d,k),this.options.staticZones){for(this.ctx.save(),this.ctx.translate(n,d),this.ctx.lineWidth=this.lineWidth,l=this.options.staticZones,e=0,g=l.length;e<g;e++)o=l[e],j=o.min,this.options.limitMin&&j<this.minValue&&(j=this.minValue),i=o.max,this.options.limitMax&&i>this.maxValue&&(i=this.maxValue),this.ctx.strokeStyle=o.strokeStyle,this.ctx.beginPath(),this.ctx.arc(0,0,k,this.getAngle(j),this.getAngle(i),!1),this.ctx.stroke();this.ctx.restore()}else void 0!==this.options.customFillStyle?b=this.options.customFillStyle(this):null!==this.percentColors?b=this.getColorForValue(this.displayedValue,!0):void 0!==this.options.colorStop?(b=0===this.options.gradientType?this.ctx.createRadialGradient(n,d,9,n,d,70):this.ctx.createLinearGradient(0,0,n,0),b.addColorStop(0,this.options.colorStart),b.addColorStop(1,this.options.colorStop)):b=this.options.colorStart,this.ctx.strokeStyle=b,this.ctx.beginPath(),this.ctx.arc(n,d,k,(1+this.options.angle)*Math.PI,a,!1),this.ctx.lineWidth=this.lineWidth,this.ctx.stroke(),this.ctx.strokeStyle=this.options.strokeColor,this.ctx.beginPath(),this.ctx.arc(n,d,k,a,(2-this.options.angle)*Math.PI,!1),this.ctx.stroke();for(this.ctx.translate(n,d),m=this.gp,f=0,h=m.length;f<h;f++)c=m[f],c.update(!0);return this.ctx.translate(-n,-d)},b}(e),d=function(a){function b(a){this.canvas=a,b.__super__.constructor.call(this),"undefined"!=typeof G_vmlCanvasManager&&(this.canvas=window.G_vmlCanvasManager.initElement(this.canvas)),this.ctx=this.canvas.getContext("2d"),this.setOptions(),this.render()}return r(b,a),b.prototype.lineWidth=15,b.prototype.displayedValue=0,b.prototype.value=33,b.prototype.maxValue=80,b.prototype.minValue=0,b.prototype.options={lineWidth:.1,colorStart:"#6f6ea0",colorStop:"#c0c0db",strokeColor:"#eeeeee",shadowColor:"#d5d5d5",angle:.35,radiusScale:1},b.prototype.getAngle=function(a){return(1-this.options.angle)*Math.PI+(a-this.minValue)/(this.maxValue-this.minValue)*(2+this.options.angle-(1-this.options.angle))*Math.PI},b.prototype.setOptions=function(a){return null==a&&(a=null),b.__super__.setOptions.call(this,a),this.lineWidth=this.canvas.height*this.options.lineWidth,this.radius=this.options.radiusScale*(this.canvas.height/2-this.lineWidth/2),this},b.prototype.set=function(a){return this.value=a,this.value>this.maxValue&&(this.maxValue=1.1*this.value),AnimationUpdater.run()},b.prototype.render=function(){var a,b,c,d,e,f;return a=this.getAngle(this.displayedValue),f=this.canvas.width/2,c=this.canvas.height/2,this.textField&&this.textField.render(this),b=this.ctx.createRadialGradient(f,c,39,f,c,70),b.addColorStop(0,this.options.colorStart),b.addColorStop(1,this.options.colorStop),d=this.radius-this.lineWidth/2,e=this.radius+this.lineWidth/2,this.ctx.strokeStyle=this.options.strokeColor,this.ctx.beginPath(),this.ctx.arc(f,c,this.radius,(1-this.options.angle)*Math.PI,(2+this.options.angle)*Math.PI,!1),this.ctx.lineWidth=this.lineWidth,this.ctx.lineCap="round",this.ctx.stroke(),this.ctx.strokeStyle=b,this.ctx.beginPath(),this.ctx.arc(f,c,this.radius,(1-this.options.angle)*Math.PI,a,!1),this.ctx.stroke()},b}(e),f=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return r(b,a),b.prototype.strokeGradient=function(a,b,c,d){var e;return e=this.ctx.createRadialGradient(a,b,c,a,b,d),e.addColorStop(0,this.options.shadowColor),e.addColorStop(.12,this.options._orgStrokeColor),e.addColorStop(.88,this.options._orgStrokeColor),e.addColorStop(1,this.options.shadowColor),e},b.prototype.setOptions=function(a){var c,d,e,f;return null==a&&(a=null),b.__super__.setOptions.call(this,a),f=this.canvas.width/2,c=this.canvas.height/2,d=this.radius-this.lineWidth/2,e=this.radius+this.lineWidth/2,this.options._orgStrokeColor=this.options.strokeColor,this.options.strokeColor=this.strokeGradient(f,c,d,e),this},b}(d),window.AnimationUpdater={elements:[],animId:null,addAll:function(a){var b,c,d,e;for(e=[],c=0,d=a.length;c<d;c++)b=a[c],e.push(AnimationUpdater.elements.push(b));return e},add:function(a){return AnimationUpdater.elements.push(a)},run:function(a){var b,c,d,e,f;for(null==a&&(a=!1),b=!0,f=AnimationUpdater.elements,d=0,e=f.length;d<e;d++)c=f[d],c.update(a===!0)&&(b=!1);return b?cancelAnimationFrame(AnimationUpdater.animId):AnimationUpdater.animId=requestAnimationFrame(AnimationUpdater.run)}},"function"==typeof window.define&&null!=window.define.amd?define(function(){return{Gauge:g,Donut:f,BaseDonut:d,TextRenderer:i}}):"undefined"!=typeof module&&null!=module.exports?module.exports={Gauge:g,Donut:f,BaseDonut:d,TextRenderer:i}:(window.Gauge=g,window.Donut=f,window.BaseDonut=d,window.TextRenderer=i)}).call(this);
\ No newline at end of file
diff --git a/web/lib/gauge-d5260c3.min.js b/web/lib/gauge-d5260c3.min.js
deleted file mode 100644 (file)
index 733d502..0000000
+++ /dev/null
@@ -1 +0,0 @@
-(function(){var a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q={}.hasOwnProperty,r=function(a,b){function c(){this.constructor=a}for(var d in b)q.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a};!function(){var a,b,c,d,e,f,g;for(g=["ms","moz","webkit","o"],c=0,e=g.length;e>c&&(f=g[c],!window.requestAnimationFrame);c++)window.requestAnimationFrame=window[f+"RequestAnimationFrame"],window.cancelAnimationFrame=window[f+"CancelAnimationFrame"]||window[f+"CancelRequestAnimationFrame"];return a=null,d=0,b={},requestAnimationFrame?window.cancelAnimationFrame?void 0:(a=window.requestAnimationFrame,window.requestAnimationFrame=function(c,e){var f;return f=++d,a(function(){return b[f]?void 0:c()},e),f},window.cancelAnimationFrame=function(a){return b[a]=!0}):(window.requestAnimationFrame=function(a,b){var c,d,e,f;return c=(new Date).getTime(),f=Math.max(0,16-(c-e)),d=window.setTimeout(function(){return a(c+f)},f),e=c+f,d},window.cancelAnimationFrame=function(a){return clearTimeout(a)})}(),String.prototype.hashCode=function(){var a,b,c,d,e;if(b=0,0===this.length)return b;for(c=d=0,e=this.length;e>=0?e>d:d>e;c=e>=0?++d:--d)a=this.charCodeAt(c),b=(b<<5)-b+a,b&=b;return b},o=function(a){var b,c;for(b=Math.floor(a/3600),c=Math.floor((a-3600*b)/60),a-=3600*b+60*c,a+="",c+="";c.length<2;)c="0"+c;for(;a.length<2;)a="0"+a;return b=b?b+":":"",b+c+":"+a},m=function(a){return k(a.toFixed(0))},p=function(a,b){var c,d;for(c in b)q.call(b,c)&&(d=b[c],a[c]=d);return a},n=function(a,b){var c,d,e;d={};for(c in a)q.call(a,c)&&(e=a[c],d[c]=e);for(c in b)q.call(b,c)&&(e=b[c],d[c]=e);return d},k=function(a){var b,c,d,e;for(a+="",c=a.split("."),d=c[0],e="",c.length>1&&(e="."+c[1]),b=/(\d+)(\d{3})/;b.test(d);)d=d.replace(b,"$1,$2");return d+e},l=function(a){return"#"===a.charAt(0)?a.substring(1,7):a},j=function(){function a(a,b){null==a&&(a=!0),this.clear=null!=b?b:!0,a&&AnimationUpdater.add(this)}return a.prototype.animationSpeed=32,a.prototype.update=function(a){var b;return null==a&&(a=!1),a||this.displayedValue!==this.value?(this.ctx&&this.clear&&this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),b=this.value-this.displayedValue,Math.abs(b/this.animationSpeed)<=.001?this.displayedValue=this.value:this.displayedValue=this.displayedValue+b/this.animationSpeed,this.render(),!0):!1},a}(),e=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return r(b,a),b.prototype.displayScale=1,b.prototype.setTextField=function(a){return this.textField=a instanceof i?a:new i(a)},b.prototype.setMinValue=function(a,b){var c,d,e,f,g;if(this.minValue=a,null==b&&(b=!0),b){for(this.displayedValue=this.minValue,f=this.gp||[],g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push(c.displayedValue=this.minValue);return g}},b.prototype.setOptions=function(a){return null==a&&(a=null),this.options=n(this.options,a),this.textField&&(this.textField.el.style.fontSize=a.fontSize+"px"),this.options.angle>.5&&(this.gauge.options.angle=.5),this.configDisplayScale(),this},b.prototype.configDisplayScale=function(){var a,b,c,d,e;return d=this.displayScale,this.options.highDpiSupport===!1?delete this.displayScale:(b=window.devicePixelRatio||1,a=this.ctx.webkitBackingStorePixelRatio||this.ctx.mozBackingStorePixelRatio||this.ctx.msBackingStorePixelRatio||this.ctx.oBackingStorePixelRatio||this.ctx.backingStorePixelRatio||1,this.displayScale=b/a),this.displayScale!==d&&(e=this.canvas.G__width||this.canvas.width,c=this.canvas.G__height||this.canvas.height,this.canvas.width=e*this.displayScale,this.canvas.height=c*this.displayScale,this.canvas.style.width=e+"px",this.canvas.style.height=c+"px",this.canvas.G__width=e,this.canvas.G__height=c),this},b}(j),i=function(){function a(a){this.el=a}return a.prototype.render=function(a){return this.el.innerHTML=m(a.displayedValue)},a}(),a=function(a){function b(a,b){this.elem=a,this.text=null!=b?b:!1,this.value=1*this.elem.innerHTML,this.text&&(this.value=0)}return r(b,a),b.prototype.displayedValue=0,b.prototype.value=0,b.prototype.setVal=function(a){return this.value=1*a},b.prototype.render=function(){var a;return a=this.text?o(this.displayedValue.toFixed(0)):k(m(this.displayedValue)),this.elem.innerHTML=a},b}(j),b={create:function(b){var c,d,e,f;for(f=[],d=0,e=b.length;e>d;d++)c=b[d],f.push(new a(c));return f}},h=function(a){function b(a){this.gauge=a,this.ctx=this.gauge.ctx,this.canvas=this.gauge.canvas,b.__super__.constructor.call(this,!1,!1),this.setOptions()}return r(b,a),b.prototype.displayedValue=0,b.prototype.value=0,b.prototype.options={strokeWidth:.035,length:.1,color:"#000000"},b.prototype.setOptions=function(a){return null==a&&(a=null),p(this.options,a),this.length=this.canvas.height*this.options.length,this.strokeWidth=this.canvas.height*this.options.strokeWidth,this.maxValue=this.gauge.maxValue,this.minValue=this.gauge.minValue,this.animationSpeed=this.gauge.animationSpeed,this.options.angle=this.gauge.options.angle},b.prototype.render=function(){var a,b,c,d,e,f,g,h,i;return a=this.gauge.getAngle.call(this,this.displayedValue),b=this.canvas.width/2,c=.9*this.canvas.height,h=Math.round(b+this.length*Math.cos(a)),i=Math.round(c+this.length*Math.sin(a)),f=Math.round(b+this.strokeWidth*Math.cos(a-Math.PI/2)),g=Math.round(c+this.strokeWidth*Math.sin(a-Math.PI/2)),d=Math.round(b+this.strokeWidth*Math.cos(a+Math.PI/2)),e=Math.round(c+this.strokeWidth*Math.sin(a+Math.PI/2)),this.ctx.fillStyle=this.options.color,this.ctx.beginPath(),this.ctx.arc(b,c,this.strokeWidth,0,2*Math.PI,!0),this.ctx.fill(),this.ctx.beginPath(),this.ctx.moveTo(f,g),this.ctx.lineTo(h,i),this.ctx.lineTo(d,e),this.ctx.fill()},b}(j),c=function(){function a(a){this.elem=a}return a.prototype.updateValues=function(a){return this.value=a[0],this.maxValue=a[1],this.avgValue=a[2],this.render()},a.prototype.render=function(){var a,b;return this.textField&&this.textField.text(m(this.value)),0===this.maxValue&&(this.maxValue=2*this.avgValue),b=this.value/this.maxValue*100,a=this.avgValue/this.maxValue*100,$(".bar-value",this.elem).css({width:b+"%"}),$(".typical-value",this.elem).css({width:a+"%"})},a}(),g=function(a){function b(a){this.canvas=a,b.__super__.constructor.call(this),this.percentColors=null,"undefined"!=typeof G_vmlCanvasManager&&(this.canvas=window.G_vmlCanvasManager.initElement(this.canvas)),this.ctx=this.canvas.getContext("2d"),this.gp=[new h(this)],this.setOptions(),this.render()}return r(b,a),b.prototype.elem=null,b.prototype.value=[20],b.prototype.maxValue=80,b.prototype.minValue=0,b.prototype.displayedAngle=0,b.prototype.displayedValue=0,b.prototype.lineWidth=40,b.prototype.paddingBottom=.1,b.prototype.percentColors=null,b.prototype.options={colorStart:"#6fadcf",colorStop:void 0,gradientType:0,strokeColor:"#e0e0e0",pointer:{length:.8,strokeWidth:.035},angle:.15,lineWidth:.44,fontSize:40,limitMax:!1},b.prototype.setOptions=function(a){var c,d,e,f;for(null==a&&(a=null),b.__super__.setOptions.call(this,a),this.configPercentColors(),this.lineWidth=this.canvas.height*(1-this.paddingBottom)*this.options.lineWidth,this.radius=this.canvas.height*(1-this.paddingBottom)-this.lineWidth,this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.render(),f=this.gp,d=0,e=f.length;e>d;d++)c=f[d],c.setOptions(this.options.pointer),c.render();return this},b.prototype.configPercentColors=function(){var a,b,c,d,e,f,g;if(this.percentColors=null,void 0!==this.options.percentColors){for(this.percentColors=new Array,f=[],c=d=0,e=this.options.percentColors.length-1;e>=0?e>=d:d>=e;c=e>=0?++d:--d)g=parseInt(l(this.options.percentColors[c][1]).substring(0,2),16),b=parseInt(l(this.options.percentColors[c][1]).substring(2,4),16),a=parseInt(l(this.options.percentColors[c][1]).substring(4,6),16),f.push(this.percentColors[c]={pct:this.options.percentColors[c][0],color:{r:g,g:b,b:a}});return f}},b.prototype.set=function(a){var b,c,d,e,f,g,i;if(a instanceof Array||(a=[a]),a.length>this.gp.length)for(b=c=0,g=a.length-this.gp.length;g>=0?g>c:c>g;b=g>=0?++c:--c)this.gp.push(new h(this));for(b=0,f=!1,d=0,e=a.length;e>d;d++)i=a[d],i>this.maxValue&&(this.maxValue=1.1*this.value,f=!0),this.gp[b].value=i,this.gp[b++].setOptions({maxValue:this.maxValue,angle:this.options.angle});return this.value=a[a.length-1],f&&this.options.limitMax?void 0:AnimationUpdater.run()},b.prototype.getAngle=function(a){return(1+this.options.angle)*Math.PI+(a-this.minValue)/(this.maxValue-this.minValue)*(1-2*this.options.angle)*Math.PI},b.prototype.getColorForPercentage=function(a,b){var c,d,e,f,g,h,i;if(0===a)c=this.percentColors[0].color;else for(c=this.percentColors[this.percentColors.length-1].color,e=f=0,h=this.percentColors.length-1;h>=0?h>=f:f>=h;e=h>=0?++f:--f)if(a<=this.percentColors[e].pct){b===!0?(i=this.percentColors[e-1],d=this.percentColors[e],g=(a-i.pct)/(d.pct-i.pct),c={r:Math.floor(i.color.r*(1-g)+d.color.r*g),g:Math.floor(i.color.g*(1-g)+d.color.g*g),b:Math.floor(i.color.b*(1-g)+d.color.b*g)}):c=this.percentColors[e].color;break}return"rgb("+[c.r,c.g,c.b].join(",")+")"},b.prototype.getColorForValue=function(a,b){var c;return c=(a-this.minValue)/(this.maxValue-this.minValue),this.getColorForPercentage(c,b)},b.prototype.render=function(){var a,b,c,d,e,f,g,h,i;for(i=this.canvas.width/2,d=this.canvas.height*(1-this.paddingBottom),a=this.getAngle(this.displayedValue),this.textField&&this.textField.render(this),this.ctx.lineCap="butt",void 0!==this.options.customFillStyle?b=this.options.customFillStyle(this):null!==this.percentColors?b=this.getColorForValue(this.displayedValue,!0):void 0!==this.options.colorStop?(b=0===this.options.gradientType?this.ctx.createRadialGradient(i,d,9,i,d,70):this.ctx.createLinearGradient(0,0,i,0),b.addColorStop(0,this.options.colorStart),b.addColorStop(1,this.options.colorStop)):b=this.options.colorStart,this.ctx.strokeStyle=b,this.ctx.beginPath(),this.ctx.arc(i,d,this.radius,(1+this.options.angle)*Math.PI,a,!1),this.ctx.lineWidth=this.lineWidth,this.ctx.stroke(),this.ctx.strokeStyle=this.options.strokeColor,this.ctx.beginPath(),this.ctx.arc(i,d,this.radius,a,(2-this.options.angle)*Math.PI,!1),this.ctx.stroke(),g=this.gp,h=[],e=0,f=g.length;f>e;e++)c=g[e],h.push(c.update(!0));return h},b}(e),d=function(a){function b(a){this.canvas=a,b.__super__.constructor.call(this),"undefined"!=typeof G_vmlCanvasManager&&(this.canvas=window.G_vmlCanvasManager.initElement(this.canvas)),this.ctx=this.canvas.getContext("2d"),this.setOptions(),this.render()}return r(b,a),b.prototype.lineWidth=15,b.prototype.displayedValue=0,b.prototype.value=33,b.prototype.maxValue=80,b.prototype.minValue=0,b.prototype.options={lineWidth:.1,colorStart:"#6f6ea0",colorStop:"#c0c0db",strokeColor:"#eeeeee",shadowColor:"#d5d5d5",angle:.35},b.prototype.getAngle=function(a){return(1-this.options.angle)*Math.PI+(a-this.minValue)/(this.maxValue-this.minValue)*(2+this.options.angle-(1-this.options.angle))*Math.PI},b.prototype.setOptions=function(a){return null==a&&(a=null),b.__super__.setOptions.call(this,a),this.lineWidth=this.canvas.height*this.options.lineWidth,this.radius=this.canvas.height/2-this.lineWidth/2,this},b.prototype.set=function(a){return this.value=a,this.value>this.maxValue&&(this.maxValue=1.1*this.value),AnimationUpdater.run()},b.prototype.render=function(){var a,b,c,d,e,f;return a=this.getAngle(this.displayedValue),f=this.canvas.width/2,c=this.canvas.height/2,this.textField&&this.textField.render(this),b=this.ctx.createRadialGradient(f,c,39,f,c,70),b.addColorStop(0,this.options.colorStart),b.addColorStop(1,this.options.colorStop),d=this.radius-this.lineWidth/2,e=this.radius+this.lineWidth/2,this.ctx.strokeStyle=this.options.strokeColor,this.ctx.beginPath(),this.ctx.arc(f,c,this.radius,(1-this.options.angle)*Math.PI,(2+this.options.angle)*Math.PI,!1),this.ctx.lineWidth=this.lineWidth,this.ctx.lineCap="round",this.ctx.stroke(),this.ctx.strokeStyle=b,this.ctx.beginPath(),this.ctx.arc(f,c,this.radius,(1-this.options.angle)*Math.PI,a,!1),this.ctx.stroke()},b}(e),f=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return r(b,a),b.prototype.strokeGradient=function(a,b,c,d){var e;return e=this.ctx.createRadialGradient(a,b,c,a,b,d),e.addColorStop(0,this.options.shadowColor),e.addColorStop(.12,this.options._orgStrokeColor),e.addColorStop(.88,this.options._orgStrokeColor),e.addColorStop(1,this.options.shadowColor),e},b.prototype.setOptions=function(a){var c,d,e,f;return null==a&&(a=null),b.__super__.setOptions.call(this,a),f=this.canvas.width/2,c=this.canvas.height/2,d=this.radius-this.lineWidth/2,e=this.radius+this.lineWidth/2,this.options._orgStrokeColor=this.options.strokeColor,this.options.strokeColor=this.strokeGradient(f,c,d,e),this},b}(d),window.AnimationUpdater={elements:[],animId:null,addAll:function(a){var b,c,d,e;for(e=[],c=0,d=a.length;d>c;c++)b=a[c],e.push(AnimationUpdater.elements.push(b));return e},add:function(a){return AnimationUpdater.elements.push(a)},run:function(){var a,b,c,d,e;for(a=!0,e=AnimationUpdater.elements,c=0,d=e.length;d>c;c++)b=e[c],b.update()&&(a=!1);return a?cancelAnimationFrame(AnimationUpdater.animId):AnimationUpdater.animId=requestAnimationFrame(AnimationUpdater.run)}},"function"==typeof window.define&&null!=window.define.amd?define(function(){return{Gauge:g,Donut:f,BaseDonut:d,TextRenderer:i}}):"undefined"!=typeof module&&null!=module.exports?module.exports={Gauge:g,Donut:f,BaseDonut:d,TextRenderer:i}:(window.Gauge=g,window.Donut=f,window.BaseDonut=d,window.TextRenderer=i)}).call(this);
\ No newline at end of file
index ad424abad8726d93f94bdb0412d08bf9e823b608..404944d1206f3a003b47ffb6ad23a206c067d433 100644 (file)
@@ -3,7 +3,7 @@
     "info": {
         "title": "NetData API",
         "description": "Real time data collection and graphs...",
-        "version": "1.4.1_master"
+        "version": "1.5.1_rolling"
     },
     "host": "registry.my-netdata.io",
     "schemes": [
                     }
                 }
             }
+        },
+        "/allmetrics": {
+            "get": {
+                "summary": "Get a value of all the metrics maintained by netdata",
+                "description": "The charts endpoint returns the latest value of all charts and dimensions stored in the netdata server.",
+                "parameters": [
+                    {
+                        "name": "format",
+                        "in": "query",
+                        "description": "The format of the response to be returned",
+                        "required": true,
+                        "type": "string",
+                        "enum": [
+                            "shell",
+                            "prometheus"
+                        ],
+                        "default": "shell"
+                    }
+                ],
+                "responses": {
+                    "200": {
+                        "description": "All the metrics returned in the format requested"
+                    },
+                    "400": {
+                        "description": "The format requested is not supported"
+                    }
+                }
+            }
         }
     },
     "definitions": {
                     "type": "string",
                     "description": "The hostname of the netdata server."
                 },
+                "version": {
+                    "type": "string",
+                    "description": "netdata version of the server."
+                },
+                "os": {
+                    "type": "string",
+                    "description": "The netdata server host operating system.",
+                    "enum": [
+                        "macos",
+                        "linux",
+                        "freebsd"
+                    ]
+                },
+                "history": {
+                    "type": "number",
+                    "description": "The duration, in seconds, of the round robin database maintained by netdata."
+                },
                 "update_every": {
                     "type": "number",
                     "description": "The default update frequency of the netdata server. All charts have an update frequency equal or bigger than this."
                             "$ref": "#/definitions/chart"
                         }
                     }
+                },
+                "charts_count": {
+                    "type": "number",
+                    "description": "The number of charts."
+                },
+                "dimensions_count": {
+                    "type": "number",
+                    "description": "The total number of dimensions."
+                },
+                "alarms_count": {
+                    "type": "number",
+                    "description": "The number of alarms."
+                },
+                "rrd_memory_bytes": {
+                    "type": "number",
+                    "description": "The size of the round robin database in bytes."
                 }
             }
         },
                             "$ref": "#/definitions/dimension"
                         }
                     }
+                },
+                "green": {
+                    "type": "number",
+                    "description": "Chart health green threshold"
+                },
+                "red": {
+                    "type": "number",
+                    "description": "Chart health red trheshold"
                 }
             }
         },
index 00a038ce75cdcc19f010aded72dd582d80b6e2a9..a74d66f5dc03c042890ef5f94b594339f877c1b8 100644 (file)
@@ -2,7 +2,7 @@ swagger: '2.0'
 info:
   title: NetData API
   description: 'Real time data collection and graphs...'
-  version: 1.4.1_master
+  version: 1.5.1_rolling
 host: registry.my-netdata.io
 schemes:
   - http
@@ -283,6 +283,16 @@ definitions:
       hostname:
         type: string
         description: 'The hostname of the netdata server.'
+      version:
+        type: string
+        description: 'netdata version of the server.'
+      os:
+        type: string
+        description: 'The netdata server host operating system.'
+        enum: [ 'macos', 'linux', 'freebsd' ]
+      history:
+        type: number
+        description: 'The duration, in seconds, of the round robin database maintained by netdata.'
       update_every:
         type: number
         description: 'The default update frequency of the netdata server. All charts have an update frequency equal or bigger than this.'
@@ -292,6 +302,18 @@ definitions:
         properties:
           key:
               $ref: '#/definitions/chart'
+      charts_count:
+        type: number
+        description: 'The number of charts.'
+      dimensions_count:
+        type: number
+        description: 'The total number of dimensions.'
+      alarms_count:
+        type: number
+        description: 'The number of alarms.'
+      rrd_memory_bytes:
+        type: number
+        description: 'The size of the round robin database in bytes.'
   chart:
     type: object
     properties:
@@ -344,13 +366,19 @@ definitions:
         properties:
           key:
               $ref: '#/definitions/dimension'
+      green:
+        type: number
+        description: 'Chart health green threshold'
+      red:
+        type: number
+        description: 'Chart health red trheshold'
   dimension:
     type: object
     properties:
       name:
         type: string
         description: 'The name of the dimension'
+        
   json_wrap:
     type: object
     properties: